Exemple #1
0
        public cAlarm(cDataAccess da, string code, string db, string table, string alarmField, string idRegName, int idRegValue, string emailSubject, string emailList, string selectCondition, string selectFields, bool flagged, string server, bool columnDate)
        {
            string _stage = "Creating object";

            try
            {
                DA              = da;
                Code            = code;
                DB              = db;
                Table           = table;
                AlarmField      = alarmField;
                IdRegName       = idRegName;
                IdRegValue      = idRegValue;
                EmailSubject    = emailSubject;
                EmailList       = emailList;
                SelectCondition = selectCondition;
                SelectFields    = selectFields;
                Flagged         = flagged;
                Server          = server;
                ColumnDate      = columnDate;
            }
            catch (Exception ex)
            {
                throw new Exception($"[{this.GetType().Name}/{System.Reflection.MethodBase.GetCurrentMethod().Name}#{_stage}] {ex.Message}");
            }
        }
Exemple #2
0
        private void data_NewCaseLoggedError(object sender, cPictureFile pictureFile, string errorDescription)
        {
            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];
            var data = new cDataAccess(setting.ConnectionString);

            lblInfo.Visible = true;
            lblInfo.Text    = "Errors at " + pictureFile.pEncryptedPicture.pEncryptedFileName;

            foreach (ListViewItem item in lsvFiles.Items)
            {
                cFilm film = pictureFile.pBelongsToFilm;

                if (item.Group != null)
                {
                    var groupFilm = (cFilm)item.Group.Tag;

                    cPictureFile pic      = film.getFirstValidPictureFile();
                    cPictureFile picGroup = groupFilm.getFirstValidPictureFile();

                    if (pic != null && picGroup != null)
                    {
                        if (pic.pFormattedSession == picGroup.pFormattedSession)
                        {
                            if (item.Text == pictureFile.pEncryptedPicture.pEncryptedFileName)
                            {
                                updateFilesListItemError(item, pictureFile, errorDescription);
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemple #3
0
        public void Start()
        {
            errorWriting = new ErrorLogging();
            errorWriting.WriteErrorLog("Service has started on " + Environment.MachineName);

            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];

            dataAccess = new cDataAccess(setting.ConnectionString);


            bool success = dataAccess.getImagePath(Environment.MachineName, out mImagePath);

            if (!success)
            {
                errorWriting.WriteErrorLog("Invalid Image path. Please check the computer name!");
                Stop();
            }

            try
            {
                _scheduler = StdSchedulerFactory.GetDefaultScheduler();

                _scheduler.Start();

                // define the job and tie it to our HelloJob class
                IJobDetail job = JobBuilder.Create <ProcessJob>()
                                 .Build();

                IJobDetail job2 = JobBuilder.Create <ProcessJob>()
                                  .Build();

                // Trigger the job to run now, and then repeat 0
                ITrigger trigger = TriggerBuilder.Create()
                                   .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(6, 0))
                                   .Build();

                // Tell quartz to schedule the job using our trigger
                _scheduler.ScheduleJob(job, trigger);

                ITrigger trigger2 = TriggerBuilder.Create()
                                    .StartNow()
                                    .Build();

                _scheduler.ScheduleJob(job2, trigger2);
            }
            catch (SchedulerException ex)
            {
                errorWriting.WriteErrorLog(ex.Message);
            }
        }
Exemple #4
0
        public void Execute(IJobExecutionContext context)
        {
            errorWriting = new ErrorLogging();
            try
            {
                retryCounter += 1;
                errorWriting.WriteErrorLog("iAutoLog Job has started on machine " + Environment.MachineName);
                var configurationCore = new TMT.Core.Camera.Interfaces.Configuration();

                var redRoomConfiguration = new cConfiguration();

                List <cCamera> cameras = redRoomConfiguration.GetCameras(Path.Combine(DefaultPath(), "Config"), "CameraConfig.xml");
                mPhysicalStudio = new cPhysicalStudio();

                // mPhysicalStudio.evFilmAdded += mPhysicalStudioFilmAdded;
                foreach (cCamera abstractCamera in cameras)
                {
                    mPhysicalStudio.Register(abstractCamera);
                }

                ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];

                dataAccess = new cDataAccess(setting.ConnectionString);
                errorWriting.WriteErrorLog("Get Server Time.");
                serverDateTime = dataAccess.GetDatabaseDate();

                dataAccess.evNewCaseLoggedError += data_NewCaseLoggedError;

                bool success = dataAccess.getImagePath(Environment.MachineName, out mImagePath);
                if (!success)
                {
                    errorWriting.WriteErrorLog("Invalid Image path. Please check the computer name!");
                }

                errorWriting.WriteErrorLog("StartProcessing");
                StartProcessing();
            }
            catch (Exception ex)
            {
                errorWriting.WriteErrorLog(ex.Message);
                if (retryCounter <= 2)
                {
                    Thread.Sleep(60000);
                    Execute(context);
                }
            }
        }
Exemple #5
0
        private IEnumerable <int> getFilesLogged(cFilm film)
        {
            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];
            var data = new cDataAccess(setting.ConnectionString);

            var filesLogged = new List <int>();

            if (mUserId > 0)
            {
                int result;
                data.checkLoggedSessions(film, out result);
                data.getCurrentLoggedCases(film, mUserId, mImagePath, out filesLogged);
                if (data.pError.Length > 0)
                {
                    MessageBox.Show("WARNING! Could not checked Logged Cases - " + data.pError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            return(filesLogged);
        }
Exemple #6
0
        private void btnLog_Click(object sender, EventArgs e)
        {
            if (mUserId <= 0)
            {
                MessageBox.Show("You must login with a valid username and password before you can log!", "Cannot Log", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int totalLoggedCases             = 0;
            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];
            var data = new cDataAccess(setting.ConnectionString);

            data.evNewCaseLogged           += data_NewCaseLogged;
            data.evNewCaseLoggedError      += data_NewCaseLoggedError;
            data.evNewCasePreviouslyLogged += data_NewCasePreviouslyLogged;

            Cursor.Current = Cursors.WaitCursor;

            try
            {
                if (lsvSessions.SelectedItems.Count > 0 && lsvSessions.Items.Count > 0)
                {
                    if (lsvSessions.SelectedItems.Count > 1)
                    {
                        if (MessageBox.Show("You have selected " + lsvSessions.SelectedItems.Count + " sessions to log. Are you sure you want to continue?", "Multi session Log mode", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        {
                            return;
                        }
                    }

                    foreach (ListViewItem selectedItem in lsvSessions.SelectedItems)
                    {
                        var film = (cFilm)selectedItem.Tag;

                        int   numberLoggedCases;
                        int   previouslyLogged;
                        cFilm reportFilm;
                        if (data.logNewCases(film, mUserId, mImagePath, out numberLoggedCases, out reportFilm, out previouslyLogged))
                        {
                            totalLoggedCases += numberLoggedCases;

                            var sf = new StatsReport();
                            sf.userId = mUserId;
                            sf.BindFormData(reportFilm);
                            sf.Show(this);

                            //Process vosi list
                            data.logVosiFile(film);

                            if (!string.IsNullOrEmpty(film.pStatsFileName))
                            {
                                FileInfo fileInfo         = new FileInfo(film.pStatsFileName);
                                var      encStatsFileList = data.ReadStatsFile(fileInfo);
                                data.SubmitStatsFile(encStatsFileList);
                            }

                            Application.DoEvents();

                            int sessionLogged;
                            data.checkLoggedSessions(film, out sessionLogged);
                            selectedItem.BackColor = sessionLogged == 1 ? Color.Purple : Color.Green;
                        }

                        if (data.pError.Length > 0)
                        {
                            if (film.getFirstValidPictureFile() != null)
                            {
                                MessageBox.Show("ERROR with logging film " + film.getFirstValidPictureFile().pFormattedSession + " - " + data.pError, "Log Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                MessageBox.Show("ERROR with logging film <SESSION READ ERROR> - " + data.pError, "Log Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }

                        mPhysicalStudio.ClearFilm(film);
                    }
                }
                else
                {
                    MessageBox.Show("You must select a session with encrypted files before you can log!", "Cannot Log", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("The system logged " + totalLoggedCases.ToString() + " new cases!", "Logged Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                lblInfo.Text = "The system logged " + totalLoggedCases + " new cases!";
            }
        }
Exemple #7
0
        private void btnImageReport_Click(object sender, EventArgs e)
        {
            if (mUserId <= 0)
            {
                MessageBox.Show("You must login with a valid username and password before you can validate logged images!", "Cannot Log", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            saveFileDialog1.Filter = "Text File|*.txt";
            saveFileDialog1.Title  = "Save Report as a Text File";
            saveFileDialog1.ShowDialog();

            // Get file name.
            string name = saveFileDialog1.FileName;

            // Write to the file name selected.
            // ... You can write the text from a TextBox instead of a string literal.

            if (string.IsNullOrEmpty(name))
            {
                return;
            }

            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];
            var data = new cDataAccess(setting.ConnectionString);

            data.evSyncedImage += data_SyncedImage;
            var aggregateOfMissingImages = new List <sLoggedImage>();

            Cursor.Current = Cursors.WaitCursor;

            try
            {
                if (lsvSessions.SelectedItems != null && lsvSessions.SelectedItems.Count > 0 && lsvSessions.Items.Count > 0)
                {
                    if (lsvSessions.SelectedItems.Count > 1)
                    {
                        if (MessageBox.Show("You have selected " + lsvSessions.SelectedItems.Count + " sessions to sync. Are you sure you want to continue?", "Multi session Sync mode", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        {
                            return;
                        }
                    }

                    foreach (ListViewItem selectedItem in lsvSessions.SelectedItems)
                    {
                        var film = (cFilm)selectedItem.Tag;

                        List <sLoggedImage> missingImages;
                        if (data.syncImages(txtMachineName.Text, film, out missingImages))
                        {
                            aggregateOfMissingImages.AddRange(missingImages);
                        }

                        if (data.pError.Length > 0)
                        {
                            if (film.getFirstValidPictureFile() != null)
                            {
                                MessageBox.Show("ERROR with sync film " + film.getFirstValidPictureFile().pFormattedSession + " - " + data.pError, "Sync Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                MessageBox.Show("ERROR with sync film <SESSION READ ERROR> - " + data.pError, "Sync Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }

                        mPhysicalStudio.ClearFilm(film);
                    }

                    lblInfo.Visible = true;
                    lblInfo.Text    = "Saving Report...";

                    foreach (sLoggedImage img in aggregateOfMissingImages)
                    {
                        var sb = new StringBuilder();

                        sb.Append(img.mLogDate);
                        sb.Append(",");
                        sb.Append(img.mSession);
                        sb.Append(",");
                        sb.Append(img.mLocationCode);
                        sb.Append(",");
                        sb.Append(img.mFileNumber);
                        sb.Append(",");
                        sb.Append(img.mFileName);
                        sb.Append(",");
                        sb.Append(img.mHasError);
                        sb.Append(",");
                        sb.Append(img.mMessage);
                        sb.Append(Environment.NewLine);

                        File.AppendAllText(name, sb.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("You must select a session with encrypted files before you can sync!", "Cannot Sync", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Your text based report contains " + aggregateOfMissingImages.Count + " missing images validated against the files in the database from " + dateTimePickerFilterAfter.Value.ToShortDateString() + ". You can now open and review the file.", "Sync Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                lblInfo.Text = "The system synced " + aggregateOfMissingImages.Count + " new images!";
            }
        }
Exemple #8
0
        private void loadFilms()
        {
            if (txtDirectory.Text.Length <= 0)
            {
                MessageBox.Show("You must enter a start directory first.", "No Directory Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDirectory.Focus();
                return;
            }

            var dirSelected = new DirectoryInfo(txtDirectory.Text);

            if (!dirSelected.Exists)
            {
                MessageBox.Show("The directory you selected does not exist.", "Directory does not Exist", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDirectory.Focus();
                return;
            }

            resetForm();

            lblInfo.Text    = "Loading Films...please be patient";
            lblInfo.Visible = true;
            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];
            var data = new cDataAccess(setting.ConnectionString);

            Cursor.Current = Cursors.WaitCursor;

            lsvSessions.BeginUpdate();

            try
            {
                if (mTree.SelectedNode != null)
                {
                    if (mTree.SelectedNode.GetType() != typeof(DirectoryNode))
                    {
                        MessageBox.Show("You cannot select a file from the treeview. Select a directory and try again.", "No Dir Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    var node = (DirectoryNode)mTree.SelectedNode;
                    if (!node.UserSecurity.canRead())
                    {
                        MessageBox.Show("Your User Account Control does not allow you to read files in the selected directory. Remove UAC or contact your system Administrator.", "No Access", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (!node.UserSecurity.canWrite())
                    {
                        MessageBox.Show("Your User Account Control does not allow you to write to files in the selected directory. Remove UAC or contact your system Administrator.", "No Access", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }



                    //create the entry here for calling the new camera methods in a dll
                    //getdevelopablefilms will need to accept new paramter - path
                    mPhysicalStudio.Path = node.FullPath;

                    List <cFilm> films = chkFilter.Checked ? mPhysicalStudio.GetDevelopableFilms(dateTimePickerFilterAfter.Value) : mPhysicalStudio.GetDevelopableFilms(null);
                    if (films.Count == 0)
                    {
                        var sb = new StringBuilder();
                        sb.Append("The system could not decrypt files in the selected path.");
                        sb.Append(Environment.NewLine);
                        sb.Append("Possible Reasons:");
                        sb.Append(Environment.NewLine);
                        sb.Append("1. No Files could be found, check the filter or if the path contains files.");
                        sb.Append(Environment.NewLine);
                        sb.Append("2. The files exists but are corrupted and cannot be decrypted.");
                        sb.Append(Environment.NewLine);
                        sb.Append("3. Invalid deskey or deskey not found.");
                        MessageBox.Show(sb.ToString(), "No pictures found.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    foreach (cFilm film in films)
                    {
                        ListViewItem item = new ListViewItem(film.pGroup);

                        item.SubItems.Add(film.pCreationTime != null ? film.pCreationTime.Value.ToString("yyyy-MM-dd") : "*Cannot Read Date");

                        item.SubItems.Add(film.pCameraDriver.pName + " " + film.pCameraDriver.pVersion);

                        item.SubItems.Add(film.pHasErrors ? "Yes" : "No");

                        if (mUserId > 0)
                        {
                            int result;
                            data.checkLoggedSessions(film, out result);
                            item.BackColor = result == 1 ? Color.Purple : Color.Green;
                        }
                        else
                        {
                            item.BackColor = Color.Orange;
                        }

                        item.Tag = film;
                        lsvSessions.Items.Add(item);
                    }
                }
            }
            finally
            {
                lsvSessions.EndUpdate();
                lblInfo.Visible = false;
                Cursor.Current  = Cursors.Default;
            }
        }
Exemple #9
0
        private void btnLoginLogout_Click(object sender, EventArgs e)
        {
            if (btnLoginLogout.Text == "Logout")
            {
                mUserId             = -1;
                mImagePath          = "";
                btnLoginLogout.Text = "LogIn";
                lblLogin.Text       = "You are not Logged In";
            }
            else
            {
                bool success;
                if (App.AuthenticatedUser != null)
                {
                    mUserId = (int)App.AuthenticatedUser.UserData.ID;
                }

                ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];

                var data = new cDataAccess(setting.ConnectionString);

                if (data.pError.Length > 0)
                {
                    MessageBox.Show("ERROR with Login Procedure! - " + data.pError, "Log Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (mUserId <= 0)
                {
                    if (App.AuthenticatedUser == null)
                    {
                        success = data.validateUser(txtUserName.Text, txtPassword.Text, out mUserId);

                        if (!success || mUserId < 0)
                        {
                            MessageBox.Show("Invalid User name or Password. Remeber, its case sensitive!" + " - " + data.pError, "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                }

                if (mImagePath == string.Empty)
                {
                    success = data.getImagePath(txtMachineName.Text, out mImagePath);

                    if (!success)
                    {
                        MessageBox.Show("Invalid Image path. Please check the computer name!", "Invalid Image Path", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        mUserId = -1;
                        return;
                    }

                    //MessageBox.Show("You are now logged in Please proceed to log!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    btnLoginLogout.Text = "Logout";
                    lblLogin.Text       = "Logged In, User Id: " + mUserId;
                }
            }

            if (lsvSessions.Items.Count > 0)
            {
                loadFilms();
            }
        }
Exemple #10
0
        public void BindFormData(cFilm film)
        {
            string statsFileName;

            if (film.pHasEncryptedPictureFiles)
            {
                film.applyStats();

                //*****First Record is the Operator and Stats
                ReportSource rsMain = new ReportSource
                {
                    AverageSpeed         = film.pAverageSpeed,
                    CountOfInfringements = film.pInfringements,
                    ErrorsCount          = film.pCaptureErrors,
                    HighestSpeed         = film.pHighestSpeed,
                    JammerCount          = film.pJammerCount,
                    TestPhotoCount       = film.pTestPhotos,
                    VehiclesChecked      = film.pVehiclesChecked
                };

                statsFileName = film.pStatsFileName == string.Empty ? "None" : film.pStatsFileName;

                if (film.pStartDate != null && film.pEndDate != null)
                {
                    rsMain.Time = film.pStartDate.Value.ToString("HH:mm:ss tt") + "-" + film.pEndDate.Value.ToString("HH:mm:ss tt");
                }

                _rs.Add(rsMain);

                int locationCounter = 0;

                var groupByDate = from f in film.getPicturesFiles()
                                  where f.pHasError == false
                                  group f by f.pOffenceDateStringDD_MM_YYYY into g
                                  select g;

                List <string> lst   = new List <string>();
                List <string> camId = new List <string>();

                foreach (IGrouping <string, cPictureFile> pictureFilesDate in groupByDate)
                {
                    var groupByLocation = from f in pictureFilesDate
                                          where f.pHasError == false
                                          group f by f.pLocationCode into g
                                          select g;

                    foreach (IGrouping <string, cPictureFile> pictureFilesLocation in groupByLocation)
                    {
                        locationCounter++;
                        ReportSource rs = new ReportSource {
                            CamDate = pictureFilesLocation.First().pOffenceDateStringDD_MM_YYYY, Session = "Actual", LocationCode = pictureFilesLocation.First().pLocationCode
                        };

                        foreach (cPictureFile pictureFile in pictureFilesLocation)
                        {
                            if (!lst.Contains(pictureFile.pOperatorId))
                            {
                                lst.Add(pictureFile.pOperatorId);
                            }

                            if (pictureFile.pIsTest)
                            {
                                rs.TestPhotoCount++;
                            }
                            else if (pictureFile.pIsJammer)
                            {
                                rs.JammerCount++;
                            }
                            else if (pictureFile.pHasError)
                            {
                                rs.ErrorsCount++;
                            }
                            else
                            {
                                rs.CountOfInfringements++;
                            }

                            if (!camId.Contains(pictureFile.pMachineId))
                            {
                                camId.Add(pictureFile.pMachineId);
                            }
                        }

                        DateTime?start = pictureFilesLocation.First().pOffenceDate;
                        DateTime?end   = pictureFilesLocation.Last().pOffenceDate;
                        if (start != null && end != null)
                        {
                            rs.Time = start.Value.ToString("HH:mm:ss tt") + "-" + end.Value.ToString("HH:mm:ss tt");
                        }

                        _rs.Add(rs);
                    }
                }

                StringBuilder sb = new StringBuilder();
                foreach (string s in lst)
                {
                    sb.Append(s);
                    sb.Append(",");
                }

                rsMain.Operators = sb.ToString().TrimEnd(',');

                cPictureFile pic = film.getFirstValidPictureFile();

                if (pic != null)
                {
                    rsMain.LocationCode = locationCounter > 1 ? "*VARIOUS" : pic.pLocationCode;
                    rsMain.CamDate      = pic.pOffenceDateStringDD_MM_YYYY;
                    rsMain.Session      = pic.pFormattedSession;
                }

                sb.Clear();
                foreach (string c in camId)
                {
                    sb.Append(c);
                    sb.Append(",");
                }

                rsMain.CamID = sb.ToString().TrimEnd(',');

                rsMain.StatsFileName = string.IsNullOrWhiteSpace(statsFileName) ? "No  File" : statsFileName;

                ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];
                var data = new cDataAccess(setting.ConnectionString);

                string userDetail = data.getUserDetail(userId);
                rsMain.LoggedBy = userDetail;
            }
        }
Exemple #11
0
        static void Main(string[] args)
        {
#if DEBUG
            pDebug = true;
#else
            pDebug = false;
#endif
            string _stage  = "Unknown Error";
            string _myName = System.Reflection.Assembly.GetCallingAssembly().GetName().Name;

            try
            {
                Console.WriteLine($"----==== Starting [{_myName}] at {System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")} ====----");

                //
                _stage = "Checking OS";
                if (cMiscTools.RunningOS == "Other")
                {
                    throw new Exception("OS not supported!");
                }

                // If the settings file exists, the params will be loaded from it
                _stage = "Loading settings file";
                Console.Write("> Loading settings file... ");
                string[] _lines = File.ReadAllLines((cMiscTools.RunningOS == "Windows" ? Directory.GetCurrentDirectory().Substring(0, 3) : $"/media/bin/{_myName}/") + $"C# Apps Settings/{_myName}.settings", Encoding.Unicode);

                //
                _stage = "Creating Parameters object";
                cParameters _params = new cParameters();

                //
                _stage = "Getting settings from file";
                _params.LoadParameters(_lines);

                //
                _stage = "Getting settings from args";
                Console.Write($"OK!\n> Parameters: {(args.Length!=0?String.Join(" ", args):"NONE")}\n> Getting settings from args... ");
                _params.LoadParameters(args);

                //
                _stage = "Checking settings";
                Console.WriteLine("OK!");
                Console.Write("> Checking settings... ");
                if (String.IsNullOrEmpty(_params.DBServer))
                {
                    throw new Exception("DB server is mandatory: DB_SERVER=<ServerAddress>");
                }
                if (String.IsNullOrEmpty(_params.DBUser))
                {
                    throw new Exception("DB user is mandatory: DB_USER=<UserCode>");
                }
                if (String.IsNullOrEmpty(_params.DBPassword))
                {
                    throw new Exception("DB password is mandatory: DB_PASSWORD=<Password>");
                }
                if (String.IsNullOrEmpty(_params.DBDataBase))
                {
                    throw new Exception("Database is mandatory: DB_DATABASE=<Database>");
                }
                Console.WriteLine("OK!");

                //
                _stage = "Creating connection objects";
                cConnDetails _connDetailsDB   = new cConnDetails(_params.DBServer, _params.DBUser, _params.DBPassword, _params.DBDataBase);
                cConnDetails _connDetailsMail = new cConnDetails(_params.MailServer, _params.MailUser, _params.MailPassword);

                //
                _stage = $"Connecting to {_connDetailsDB.Server}";
                cDataAccess _da = new cDataAccess(_connDetailsDB);
                _da.Connect();

                //
                _stage = "Getting alarms list";
                Recordset _rs = new Recordset("Select Codigo,BD,Tabla,Campo_alarma,Nombre_idreg,idreg_valor,asunto_email,emails_aviso,condicion_alarma,campos_select,flagged=dbo.checkflag(flags,'FLAGGED'),server=isnull(server,''),FechaColumn=dbo.checkflag(flags,'XFEC2FECHA')  from cab_alarmas where dbo.checkFlag(flags,'ACTIVE')=1 and codigo='ALARMTEST'", _da);
                _rs.Open();
                //Dictionary<int, Dictionary<string, string>> _alarms = _rs.ToDictionary();

                //
                string p;
                _stage = "Looping through alarms";

                while (!_rs.EOF)
                {
                    using (cAlarm _alarm = new cAlarm(_da, _rs["Codigo"].ToString(), _rs["BD"].ToString(), _rs["Tabla"].ToString(), _rs["Campo_alarma"].ToString(), _rs["Nombre_idreg"].ToString(), Convert.ToInt32(_rs["idreg_valor"]), _rs["asunto_email"].ToString(), _rs["emails_aviso"].ToString(), _rs["condicion_alarma"].ToString(), _rs["campos_select"].ToString(), Convert.ToInt32(_rs["flagged"]) == 1, _rs["server"].ToString(), Convert.ToInt32(_rs["FechaColumn"]) == 1))
                    {
                        try
                        {
                            //
                            _stage = $"Executing alarm {_alarm.Code}";
                            Console.Write($"> Executing alarm {_alarm.Code}...");
                            _alarm.Process();
                            Console.Write($" {(_alarm.Error ? "ERROR" : "OK")}! Sending {(_alarm.Error ? "error " : "")}email...");

                            //
                            if (_alarm.Triggered || _alarm.Error)
                            {
                                _stage = $"Sending {(_alarm.Error ? "error " : "")} email";
                                using (cEmail _email = new cEmail(_connDetailsMail, _alarm.Error ? _params.MailErrorTo : (!String.IsNullOrEmpty(_params.MailTo) ? _params.MailTo : _alarm.EmailList), $"ALARM: {_alarm.EmailSubject}", _alarm.Contents, error: _alarm.Error))
                                {
                                    if (_alarm.Error)
                                    {
                                        _email.Recipients = _params.MailErrorTo;
                                    }

                                    _email.Send();
                                }
                                Console.WriteLine(" OK!");
                            }
                            else
                            {
                                Console.WriteLine(" Not triggered.");
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    _rs.MoveNext();
                }

                //
                _stage = "Disconnecting from DB server";
                //_dbt.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Main#{_stage}] {ex.Message}");
                return;
            }


            Console.WriteLine($"----==== Ending [{_myName}] at {System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")} ====----");
        }