public void TestUpdatePerson()
        {
            AddDataForTestingTransaction addDataForTesting = new AddDataForTestingTransaction();

            clientManagement = new ClientManager(DataUtil.TESTDB);
            clientServices   = new ClientServices(clientManagement);

            DeleteAllData();
            ApplicationSettingsServices _appSettings = ServicesProvider.GetInstance().GetApplicationSettingsServices();

            _appSettings.FillGeneralDatabaseParameter();
            _appSettings.UpdateSelectedParameter(OGeneralSettings.ID_PATTERN, "[0-9]{2}[A-Z]{2}");

            EconomicActivity agriculture = addDataForTesting.AddDomainOfApplicationAgriculture();
            District         district    = addDataForTesting.AddDistrictIntoDatabase();

            Person person = AddPerson(true, agriculture, 1, "Dushambe", district, "Nicolas", "MANGIN", 'M', "12ED");

            person.Branch = _branch;
            Assert.AreEqual(String.Empty, clientServices.SavePerson(ref person));

            person.FirstName          = "floriane";
            person.IdentificationData = "34PP";
            Assert.AreEqual(String.Empty, clientServices.SavePerson(ref person));
        }
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                Log.Debug("");
                Log.Info("Executing password reset job");

                IEmailSender _emailSender = new DefaultEmailSender();
                var          UserService  = ServiceProvider.GetUserServices();
                ApplicationSettingsServices generalSettingsService = ServiceProvider.GetApplicationSettingsServices();

                //Send reminders
                var users = UserService.FindAll(true)
                            .Where(user =>
                                   (user.LastUpdated == null || user.LastUpdated <= DateTime.Now.AddDays(-20))
                                   &&
                                   (!user.IsExpired.HasValue || !user.IsExpired.Value));
                foreach (var user in users)
                {
                    try
                    {
                        ISms sms = new EstoreSms();
                        sms.UserName = Convert.ToString(generalSettingsService.SelectParameterValue(OGeneralSettings.SMS_GATEWAY_USERNAME));
                        sms.Password = Convert.ToString(generalSettingsService.SelectParameterValue(OGeneralSettings.SMS_GATEWAY_PASSWORD));

                        var daysRemaining = 30;// DateTime.Now - user.LastUpdated;
                        sms.Message = @"Hi " + user.Name +
                                      @". \nPlease ensure to update you password on OpenCBS within the next " + daysRemaining;
                        sms.AddRecipient(user.Phone);
                        sms.MessageFrom = "OpenCBS";
                        string response = sms.SendSms();
                        Log.Info(response);
                    }
                    catch (Exception exc)
                    {
                        Log.Error(string.Format("Error sending sms: {0}", exc.Message), exc);
                    }
                }

                //Expire user accounts
                users = UserService.FindAll(false).Where(user => user.LastUpdated == null || user.LastUpdated <= DateTime.Now.AddDays(-30));
                foreach (var user in users)
                {
                    user.IsExpired = true;
                    user.TimedOut  = true;
                    UserService.UpdateUserAccess(user);
                }
            }
            catch (Exception exc)
            {
                Log.Error(string.Format("Error resetting user passwords: {0}", exc.Message), exc);
            }
            finally
            {
            }
        }
Exemple #3
0
        protected override void OnStart(string[] args)
        {
#if DEBUG
            //Debugger.Launch();
#endif

            Log.Info("Job factory startup task configuration");

            try
            {
                scheduler = StdSchedulerFactory.GetDefaultScheduler();
                //ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
                //scheduler = schedulerFactory.GetScheduler();

                ApplicationSettingsServices generalSettingsService = ServiceProvider.GetApplicationSettingsServices();
                generalSettingsService.FillGeneralDatabaseParameter();
                Log.Debug("Application settings loaded");

                //IJobDetail InitializationJob = JobBuilder.Create<SMSChargeJob>().WithIdentity(typeof(InitializationJob).Name).Build();
                IJobDetail SMSChargeJob      = JobBuilder.Create <SMSChargeJob>().WithIdentity(typeof(SMSChargeJob).Name).Build();
                IJobDetail MessagingJob      = JobBuilder.Create <MessagingJob>().WithIdentity(typeof(MessagingJob).Name).Build();
                IJobDetail ChequeCloseOutJob = JobBuilder.Create <ChequeCloseOutJob>().WithIdentity(typeof(ChequeCloseOutJob).Name).Build();

                IJobDetail PasswordResetJob = JobBuilder.Create <PasswordResetJob>().WithIdentity(typeof(PasswordResetJob).Name).Build();

                //ITrigger InitializationJobTrigger = TriggerBuilder.Create().WithIdentity("InitializationJobTrigger")
                //.StartNow().WithPriority(5).WithSimpleSchedule(s => s.WithRepeatCount(0).WithIntervalInMinutes(1)).Build();

                ITrigger SMSChargeJobTrigger = TriggerBuilder.Create().WithIdentity("SMSChargeJobTrigger")
                                               .WithCronSchedule("0 0 1 ? * 6L").Build(); //Fires at 1am every last friday

                ITrigger MessagingJobTrigger = TriggerBuilder.Create().WithIdentity("MessagingJobTrigger")
                                               .StartNow().WithSimpleSchedule(x => x.WithIntervalInMinutes(2).RepeatForever()
                                                                              .WithMisfireHandlingInstructionNextWithExistingCount()).StartNow().Build();

                ITrigger ChequeCloseOutJobTrigger = TriggerBuilder.Create().WithIdentity("ChequeCloseOutJobTrigger")

                                                                                              /*.StartNow()
                                                                                               * .WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever()
                                                                                               * .WithMisfireHandlingInstructionNextWithExistingCount()).StartNow()
                                                                                               * .Build();*/
                                                    .WithCronSchedule("0 0 0 * * ?").Build(); // Fires at midnight everyday.

                ITrigger PasswordResetJobTrigger = TriggerBuilder.Create().WithIdentity("PasswordResetJobTrigger")
                                                   .WithCronSchedule("0 0 0 * * ?").Build(); // Fires at midnight everyday.


                //scheduler.ScheduleJob(InitializationJob, InitializationJobTrigger);
                scheduler.ScheduleJob(MessagingJob, MessagingJobTrigger);
                scheduler.ScheduleJob(SMSChargeJob, SMSChargeJobTrigger);
                scheduler.ScheduleJob(ChequeCloseOutJob, ChequeCloseOutJobTrigger);
                scheduler.ScheduleJob(PasswordResetJob, PasswordResetJobTrigger);
                scheduler.Start();

                Log.Info("Job factory started");
            }
            catch (SchedulerException se)
            {
                Log.Error(se);
            }
        }
Exemple #4
0
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                Log.Debug("");
                Log.Info("Executing queued message send job");

                IEmailSender                _emailSender           = new DefaultEmailSender();
                QueuedEmailServices         _queuedEmailService    = ServiceProvider.GetQueuedEmailServices();
                QueuedSMSServices           _queuedSMSService      = ServiceProvider.GetQueuedSMSServices();
                ApplicationSettingsServices generalSettingsService = ServiceProvider.GetApplicationSettingsServices();

                var sendTriesStart = 0;
                var sendTriesEnd   = OpenCBSConstants.MessagingMaxSentTries;

                int enableSmsMsg = Convert.ToInt32(generalSettingsService.SelectParameterValue(OGeneralSettings.ENABLE_SMS_MESSAGING));
                Log.Debug("Send SMS status: " + enableSmsMsg);
                if (enableSmsMsg == 1)
                {
                    var queuedsms = _queuedSMSService.SearchSMSs(null, null, null, null, true, sendTriesStart, sendTriesEnd, false, 0, 10000);

                    Log.Debug("");
                    Log.Debug("-------------------------------------");
                    Log.Info("Sending SMS");
                    Log.Debug("Queued sms count: " + queuedsms.Count);

                    foreach (var qe in queuedsms)
                    {
                        try
                        {
                            ISms sms = new EstoreSms();
                            sms.UserName = Convert.ToString(generalSettingsService.SelectParameterValue(OGeneralSettings.SMS_GATEWAY_USERNAME));
                            sms.Password = Convert.ToString(generalSettingsService.SelectParameterValue(OGeneralSettings.SMS_GATEWAY_PASSWORD));

                            sms.Message = qe.Message;
                            sms.AddRecipient(qe.Recipient);
                            sms.MessageFrom = qe.From;

                            qe.Response = sms.SendSms();

                            if (qe.Response.ToLower().Contains("ok"))
                            {
                                qe.SentOnUtc = DateTime.UtcNow;
                            }
                            Log.Info(qe.Response);
                        }
                        catch (Exception exc)
                        {
                            Log.Error(string.Format("Error sending sms: {0}", exc.Message), exc);
                        }
                        finally
                        {
                            qe.SentTries = qe.SentTries + 1;
                            _queuedSMSService.Update(qe);
                        }
                    }
                }

                var queuedEmails = _queuedEmailService.SearchEmails(null, null, null, null, true, sendTriesStart, sendTriesEnd, false, 0, 10000);

                Log.Debug("");
                Log.Debug("");
                Log.Debug("-------------------------------------");
                Log.Info("Sending Emails");
                Log.Debug("Queued email count: " + queuedEmails.Count);

                foreach (var qe in queuedEmails)
                {
                    var bcc = String.IsNullOrWhiteSpace(qe.Bcc)
                                ? null
                                : qe.Bcc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    var cc = String.IsNullOrWhiteSpace(qe.CC)
                                ? null
                                : qe.CC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    try
                    {
                        var smtpContext = new SmtpContext(qe.EmailAccount);

                        var msg = new EmailMessage(
                            new EmailAddress(qe.To, qe.ToName),
                            qe.Subject,
                            qe.Body,
                            new EmailAddress(qe.From, qe.FromName));

                        if (qe.ReplyTo.HasValue())
                        {
                            msg.ReplyTo.Add(new EmailAddress(qe.ReplyTo, qe.ReplyToName));
                        }

                        if (cc != null)
                        {
                            msg.Cc.AddRange(cc.Where(x => x.HasValue()).Select(x => new EmailAddress(x)));
                        }

                        if (bcc != null)
                        {
                            msg.Bcc.AddRange(bcc.Where(x => x.HasValue()).Select(x => new EmailAddress(x)));
                        }

                        _emailSender.SendEmail(smtpContext, msg);

                        qe.SentOnUtc = DateTime.UtcNow;
                    }
                    catch (Exception exc)
                    {
                        Log.Error(string.Format("Error sending e-mail: {0}", exc.Message), exc);
                    }
                    finally
                    {
                        qe.SentTries = qe.SentTries + 1;
                        _queuedEmailService.Update(qe);
                    }
                }
                Log.Info("Queued message send completed");
            }
            catch (Exception exc)
            {
                Log.Error(exc);
            }
        }
Exemple #5
0
        static void Main(string[] args)
        {
            CsvFileDescription fileDescription = new CsvFileDescription
            {
                SeparatorChar           = ',',
                FirstLineHasColumnNames = true
            };
            CsvContext cc = new CsvContext();

            var dir = Directory.GetCurrentDirectory();

            string sourceFilePath = dir + "/client_table.csv";

            Console.WriteLine("***********************************************************");
            Console.WriteLine("***********************************************************");
            Console.WriteLine("****************OpenCBS DATABASE MIGRATOR******************");
            Console.WriteLine("***********************************************************");
            Console.WriteLine("***********************************************************");
            Console.WriteLine("                                                           ");
            Console.WriteLine("**   Ensure that a csv file named \"client_table.csv\"     **");
            Console.WriteLine("**   exists in the bin directory of the migrator before  **");
            Console.WriteLine("**                       proceeding.                     **");
            Console.WriteLine("******            Press 'enter' to continue        ********");
            Console.WriteLine("                                                           ");
            Console.WriteLine("***********************************************************");
            Console.WriteLine("***********************************************************");

            Console.ReadKey();
            try
            {
                ApplicationSettingsServices generalSettingsService = ServicesProvider.GetInstance().GetApplicationSettingsServices();
                generalSettingsService.FillGeneralDatabaseParameter();

                SelectDefaultUser();
                SelectDefaultBranch();
                SelectDefaultEconomicActivity();
                SelectDefaultLocation();

                List <FromModel.Client> clients = cc.Read <FromModel.Client>(sourceFilePath, fileDescription).ToList();
                Console.WriteLine("");
                Console.WriteLine("***********************************************************");
                Console.WriteLine(String.Format("Migrating {0} clients data", clients.Count));
                Console.WriteLine("***********************************************************");
                Console.WriteLine("");

                var             _clientService = ServicesProvider.GetInstance().GetClientServices();
                int             count          = 0;
                MigrationResult result         = null;
                foreach (FromModel.Client client in clients)
                {
                    result            = new MigrationResult();
                    result.full_name  = client.full_name;
                    result.surname    = client.surname;
                    result.first_name = client.first_name;

                    try
                    {
                        if (!String.IsNullOrEmpty(client.first_name)
                            ||
                            !String.IsNullOrEmpty(client.surname)
                            ||
                            !String.IsNullOrEmpty(client.full_name))
                        {
                            #region Individual migration
                            if (client.c_type == ClientType.INDIVIDUAL ||
                                client.c_type == ClientType.DIRECTORS ||
                                client.c_type == ClientType.CHILDREN ||
                                client.c_type == ClientType.JOINT ||
                                client.c_type == ClientType.STAFF ||
                                client.c_type == ClientType.CASHIER)
                            {
                                result.type = "INDIVIDUAL";

                                var _query = client.full_name;
                                int onlyActive = 2; //inactive and active
                                int _numbersTotalPage, _numberOfRecords;

                                var results = ServicesProvider.GetInstance().GetClientServices().FindTiers(out _numbersTotalPage, out _numberOfRecords,
                                                                                                           _query, onlyActive, 1, 1, 1, 1);

                                if (results.Count > 0)
                                {
                                    exist.Add(client);

                                    result.migrated       = "no";
                                    result.failure_reason = "duplicate";
                                    dump.Add(result);
                                    continue;
                                }
                                ++count;
                                Console.WriteLine(count + "). Migrating \"INDIVIDUAL\" " + client.full_name);
                                SavePerson(client);
                                result.migrated       = "yes";
                                result.failure_reason = "";
                                dump.Add(result);
                                migrated.Add(client);
                            }
                            #endregion
                            #region Corporate migration
                            else if (client.c_type == ClientType.GOVT ||
                                     client.c_type == ClientType.SOLE_PROPRIETORSHIP ||
                                     client.c_type == ClientType.FINANCIAL_INSTITUTION ||
                                     client.c_type == ClientType.EDUCATIONAL_INSTITUTION ||
                                     client.c_type == ClientType.COMPANY)
                            {
                                result.type = "CORPORATE";

                                var _query = client.full_name;
                                int onlyActive = 2; //inactive and active
                                int _numbersTotalPage, _numberOfRecords;


                                var results = ServicesProvider.GetInstance().GetClientServices().
                                              FindTiersCorporates(onlyActive, 1, out _numbersTotalPage, out _numberOfRecords, _query);

                                if (results.Count > 0)
                                {
                                    exist.Add(client);
                                    result.migrated       = "no";
                                    result.failure_reason = "duplicate";
                                    dump.Add(result);
                                    continue;
                                }

                                ++count;
                                Console.WriteLine(count + "). Migrating \"CORPORATE\" " + client.full_name);
                                SaveCorporate(client);
                                result.migrated       = "yes";
                                result.failure_reason = "";
                                dump.Add(result);
                                migrated.Add(client);
                            }
                            #endregion
                            #region Group migration
                            else if (client.c_type == ClientType.GROUP ||
                                     client.c_type == ClientType.CHURCH_MINISTRIES)
                            {
                                result.type = "GROUP";

                                /*var _query = "";
                                 * int onlyActive = 2; //inactive and active
                                 * int _numbersTotalPage, _numberOfRecords;
                                 *
                                 * var results = ServicesProvider.GetInstance().GetClientServices().FindTiers(out _numbersTotalPage, out _numberOfRecords,
                                 *              _query, onlyActive, 1, 1, 1, 1);
                                 *
                                 * if (results.Count > 0)
                                 * {
                                 *  exist.Add(client);
                                 *  continue;
                                 * }
                                 */
                                //++count;
                                Console.WriteLine(count + "). Migrating \"GROUP\" " + client.full_name);
                                error.Add(client);
                                result.migrated       = "no";
                                result.failure_reason = "Requires group members";
                                dump.Add(result);
                                //SaveGroup(client);
                            }
                            #endregion
                        }
                    }
                    catch (CustomFieldsAreNotFilledCorrectlyException exc)
                    {
                        Console.WriteLine(CustomExceptionHandler.ShowExceptionText(exc));
                        error.Add(client);
                        result.migrated       = "no";
                        result.failure_reason = exc.Message;
                        dump.Add(result);
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine(CustomExceptionHandler.ShowExceptionText(exc));
                        error.Add(client);
                        result.migrated       = "no";
                        result.failure_reason = exc.Message;
                        dump.Add(result);
                    }
                    finally
                    {
                        //dump.Add(result);
                    }
                }

                string resultDir = dir + "/result";
                if (!Directory.Exists(resultDir))
                {
                    Directory.CreateDirectory(resultDir);
                }

                string resultFilePath     = resultDir + "/migration.csv";
                string errorFilePath      = resultDir + "/error.csv";
                string successfulFilePath = resultDir + "/successful.csv";
                string duplicatesFilePath = resultDir + "/duplicates.csv";

                cc.Write(dump, resultFilePath, fileDescription);
                cc.Write(error, errorFilePath, fileDescription);
                cc.Write(migrated, successfulFilePath, fileDescription);
                cc.Write(exist, duplicatesFilePath, fileDescription);

                Console.WriteLine("");
                Console.WriteLine("");
                Console.WriteLine("***********************************************************");
                //Console.WriteLine(String.Format("Migrated {0} clients data", migrated.Count));
                Console.WriteLine("Results:");
                Console.WriteLine("Total: " + clients.Count);
                Console.WriteLine("Successful: " + migrated.Count);
                Console.WriteLine("Failed: " + error.Count);
                Console.WriteLine("Duplicates: " + exist.Count);
                Console.WriteLine("Migration result saved to " + resultDir);
                Console.WriteLine("***********************************************************");


                Console.ReadLine();
            }
            catch (Exception exc)
            {
                Console.WriteLine("Exception: " + exc);
                Console.ReadLine();
            }
        }