Example #1
0
        /// <summary>
        ///     This function copies the schemas and geography data off an existing Swarmops installation. Runs in its own thread.
        /// </summary>
        public static void InitDatabaseThread()
        {
            // Ignore the session object, that method of sharing data didn't work, but a static variable did.

            _initProgress = 1;
            _initMessage  = "Loading schema from Swarmops servers; creating tables and procs...";
            Thread.Sleep(100);

            try
            {
                // Get the schema and initialize the database structures. Requires ADMIN access to database.

                DatabaseMaintenance.FirstInitialization();

                _initProgress = 3;
                _initMessage  = "Applying all post-baseline database schema upgrades...";
                DatabaseMaintenance.UpgradeSchemata();
                Thread.Sleep(100);

                // SECURITY: With schemata to hold them in place, initialize the encryption keys

                Authentication.InitializeSymmetricDatabaseKey();
                Authentication.InitializeSymmetricFileSystemKey();

                // Set Geography at baseline (TODO: Ask for what baseline we got)

                Persistence.Key["LastGeographyUpdateId"] = "0";
                Persistence.Key["LastGeographyUpdate"]   = Constants.DateTimeLow.ToString("yyyy-MM-dd");

                // Set an installation ID
                // Doubles as start signal to daemons (if installation ID exists, db is ready for processing)

                Persistence.Key["SwarmopsInstallationId"] = Guid.NewGuid().ToString();

                _initProgress = 4;
                _initMessage  = "Initializing currencies...";

                // Create initial currencies (European et al)

                Currency.CreateFiat("EUR", "Euros", "€");
                Currency.CreateFiat("USD", "US Dollars", "$");
                Currency.CreateFiat("CAD", "Canadian Dollars", "CA$");
                Currency.CreateFiat("SEK", "Swedish Krona", string.Empty);
                Currency.CreateFiat("NOK", "Norwegian Krona", string.Empty);
                Currency.CreateFiat("DKK", "Danish Krona", string.Empty);
                Currency.CreateFiat("ISK", "Icelandic Krona", string.Empty);
                Currency.CreateFiat("CHF", "Swiss Franc", string.Empty);
                Currency.CreateFiat("GBP", "Pounds Sterling", "£");
                Currency.CreateCrypto("BTC", "Bitcoin Core", "฿");
                Currency.CreateCrypto("BCH", "Bitcoin Cash", "฿");

                // Fetch the first set of exchange rates, completing the currency collection

                SupportFunctions.DisableSslCertificateChecks(); // needed bc SSL root store on Mono hosed
                ExchangeRateSnapshot.Create();

                // Disable SSL required - turn this on manually

                SystemSettings.RequireSsl = false;

                _initProgress = 5;
                _initMessage  = "Getting list of countries from Swarmops servers...";
                Thread.Sleep(100);

                // Create translation lists

                Dictionary <string, int> countryIdTranslation = new Dictionary <string, int>();

                // Initialize the root geography (which becomes #1 if everything works)

                int rootGeographyId = SwarmDb.GetDatabaseForWriting().CreateGeography("[LOC]World", 0);

                // Create the sandbox

                Organization sandbox = Organization.Create(0, "Sandbox", "Sandbox", "Sandbox", "swarmops.com", "Ops",
                                                           rootGeographyId, true,
                                                           true, 0);

                sandbox.EnableEconomy(Currency.FromCode("EUR"));

                Positions.CreateOrganizationDefaultPositions(sandbox);

                // Get the list of countries

                GetGeographyData geoDataFetcher = new GetGeographyData();

                Country[] countries = geoDataFetcher.GetCountries();

                _initProgress = 7;
                _initMessage  = "Creating all countries on local server...";
                Thread.Sleep(100);
                int count = 0;
                int total = countries.Length;

                // Create all countries in our own database

                foreach (Country country in countries)
                {
                    countryIdTranslation[country.Code] = SwarmDb.GetDatabaseForWriting().CreateCountry(country.Name,
                                                                                                       country.Code,
                                                                                                       country.Culture,
                                                                                                       rootGeographyId, country.PostalCodeLength,
                                                                                                       string.Empty);

                    count++;
                    _initMessage = String.Format("Creating all countries on local server... ({0}%)", count * 100 / total);
                }

                _initProgress = 10;

                // Construct list of countries that have geographic data

                List <string> initializableCountries = new List <string>();

                foreach (Country country in countries)
                {
                    if (country.GeographyId != 1)
                    {
                        initializableCountries.Add(country.Code);
                    }
                }

                float initStepPerCountry = 90f / initializableCountries.Count;
                int   countryCount       = 0;

                // For each country...

                foreach (string countryCode in initializableCountries)
                {
                    // Get the geography layout

                    _initMessage = "Initializing geography for country " + countryCode + "... ";
                    Thread.Sleep(100);

                    GeographyUpdate.PrimeCountry(countryCode);
                    GuidCache.Set("DbInitProgress", string.Empty);

                    countryCount++;

                    _initProgress = 10 + (int)(countryCount * initStepPerCountry);
                }

                _initProgress = 100;
                _initMessage  = "Complete.";
            }
            catch (Exception failedException)
            {
                // Use initMessage to push info about what went wrong to the user

                _initMessage = failedException.ToString();
            }

            Thread.Sleep(1000);
            // give some time for static var to stick and web interface to react before killing thread
        }
Example #2
0
        private static void Main(string[] args)
        {
            // Are we running yet?

            if (!SystemSettings.DatabaseInitialized)
            {
                // will restart the service every 15s until db initialized on OOBE
                // also, the read of DatabaseInitialized can and will fail if
                // we're not initalized enough to even have a database

                throw new InvalidOperationException();
            }

            // Checking for schemata upgrade first of all, after seeing that db exists

            int startupDbVersion = Database.SwarmDb.DbVersion;

            DatabaseMaintenance.UpgradeSchemata();

            testMode = false;

            SystemSettings.BackendHostname = Dns.GetHostName();


            // Other one-time initializations

            FinancialTransactions.FixAllUnsequenced();
            SupportFunctions.OperatingTopology = OperatingTopology.Backend;

            // Begin main loop

            UnixSignal[] killSignals = null;

            if (!Debugger.IsAttached)
            {
                killSignals = new UnixSignal[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) };
            }

            BotLog.Write(0, "MainCycle", string.Empty);
            BotLog.Write(0, "MainCycle", "-----------------------------------------------");
            BotLog.Write(0, "MainCycle", string.Empty);

            if (args.Length > 0)
            {
                if (args[0].ToLower() == "test")
                {
/*
 *                  BotLog.Write(0, "MainCycle", "Running self-tests");
 *                  HeartBeater.Instance.Beat(heartbeatFile);  // Otherwise Heartbeater.Beat() will fail in various places
 *
 *                  testMode = true;
 *                  Console.WriteLine("Testing All Maintenance Processes (except membership-changing ones).");
 *                  PWLog.Write(PWLogItem.None, 0, PWLogAction.SystemTest, string.Empty, string.Empty);
 *
 *                  Console.WriteLine("\r\n10-second intervals:");
 *                  OnEveryTenSeconds();
 *                  Console.WriteLine("\r\nEvery minute:");
 *                  OnEveryMinute();
 *                  Console.WriteLine("\r\nEvery five minutes:");
 *                  OnEveryFiveMinutes();
 *                  Console.WriteLine("\r\nEvery hour:");
 *                  OnEveryHour();
 *                  Console.WriteLine("\r\nNoon:");
 *                  OnNoon();
 *                  Console.WriteLine("\r\nMidnight:");
 *                  OnMidnight();
 */

                    Console.WriteLine("Testing database access...");

                    Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).Name);
                    Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).PasswordHash);

                    Console.WriteLine("Creating OutboundComm...");

                    OutboundComm.CreateNotification(null, NotificationResource.System_Startup_Backend);

                    Console.WriteLine("Transmitting...");

                    OutboundComms comms = OutboundComms.GetOpen();

                    Console.WriteLine("{0} open items in outbound comms.", comms.Count);

                    foreach (OutboundComm comm in comms)
                    {
                        if (comm.TransmitterClass != "Swarmops.Utility.Communications.CommsTransmitterMail")
                        {
                            throw new NotImplementedException();
                        }

                        ICommsTransmitter transmitter = new CommsTransmitterMail();

                        OutboundCommRecipients recipients = comm.Recipients;
                        PayloadEnvelope        envelope   = PayloadEnvelope.FromXml(comm.PayloadXml);

                        foreach (OutboundCommRecipient recipient in recipients)
                        {
                            transmitter.Transmit(envelope, recipient.Person);
                        }
                    }


                    Console.Write("\r\nAll tests run. Waiting for mail queue to flush... ");
                    while (!MailTransmitter.CanExit)
                    {
                        Thread.Sleep(50);
                    }

                    Console.WriteLine("done.");
                    BotLog.Write(0, "MainCycle", "Exiting self-tests");
                    return;
                }

                if (args[0].ToLower() == "console")
                {
                    Console.WriteLine("\r\nRunning Swarmops-Backend in CONSOLE mode.\r\n");

                    // -------------------------------------------------------------------------------------
                    // -------------------------------------------------------------------------------------
                    // -------------------------------------------------------------------------------------

                    // -----------------------    INSERT ANY ONE-OFF ACTIONS HERE  -------------------------


                    Console.Write("\r\nWaiting for mail queue to flush... ");

                    while (!MailTransmitter.CanExit)
                    {
                        Thread.Sleep(50);
                    }

                    Console.WriteLine("done.");

                    return;
                }

                if (args[0].ToLowerInvariant() == "pdfregen")
                {
                    if (args.Length > 1)
                    {
                        int docId = Int32.Parse(args[1]);
                        PdfProcessor.Rerasterize(Document.FromIdentity(docId));
                    }
                    else
                    {
                        Console.WriteLine("Regenerating all bitmaps from PDF uploads.");
                        PdfProcessor.RerasterizeAll();
                        Console.WriteLine("Done.");
                    }

                    return;
                }


                if (args[0].ToLower() == "rsm")
                {
                    Console.WriteLine("Testing character encoding: räksmörgås RÄKSMÖRGÅS");
                    return;
                }
            }

            /*
             * MailMessage message = new MailMessage();
             * message.From = new MailAddress(Strings.MailSenderAddress, Strings.MailSenderName);
             * message.To.Add (new MailAddress ("*****@*****.**", "Rick Falkvinge (Piratpartiet)"));
             * message.Subject = "Räksmörgåsarnas ékÖNÖMÏåvdëlnïng";
             * message.Body = "Hejsan hoppsan Räksmörgåsar.";
             * message.BodyEncoding = Encoding.Default;
             * message.SubjectEncoding = Encoding.Default;
             *
             * SmtpClient smtpClient = new SmtpClient ("localhost");
             * smtpClient.Credentials = null; // mono bug
             * smtpClient.Send (message);*/

            Console.WriteLine(" * Swarmops Backend starting");

            BotLog.Write(0, "MainCycle", "Backend STARTING");

            // Disable certificate checking due to Mono not installing with a certificate repository - this is UTTERLY broken

            SupportFunctions.DisableSslCertificateChecks(); // MONO BUG/MISFEATURE: Mono has no root certificates, so can't verify cert

            // Tell sysop we're starting

            OutboundComm.CreateNotification(null, NotificationResource.System_Startup_Backend);

            // Check for existence of installation ID. If not, create one. Warning: has privacy implications when communicated.

            if (Persistence.Key["SwarmopsInstallationId"] == string.Empty)
            {
                Persistence.Key["SwarmopsInstallationId"] = Guid.NewGuid().ToString();
            }

            // Check for existence of bitcoin hotwallet root

            BitcoinUtility.VerifyBitcoinHotWallet();

            // Initialize backend socket server

            int backendSocketPort = SystemSettings.WebsocketPortBackend;

            _socketServer = new WebSocketServer(backendSocketPort);
            _socketServer.AddWebSocketService <BackendServices>("/Backend");
            _socketServer.Start();

            // Initialize socket client to Blockchain.Info (pending our own services)

            using (
                _blockChainInfoSocket =
                    new WebSocket("wss://ws.blockchain.info/inv?api_code=" + SystemSettings.BlockchainSwarmopsApiKey))
            {
                // Begin maintenance loop

                DateTime cycleStartTime = DateTime.UtcNow;
                DateTime cycleEndTime;

                int lastSecond = cycleStartTime.Second;
                int lastMinute = cycleStartTime.Minute;
                int lastHour   = cycleStartTime.Hour;

                bool exitFlag = false;

                _blockChainInfoSocket.OnOpen    += new EventHandler(OnBlockchainOpen);
                _blockChainInfoSocket.OnError   += new EventHandler <ErrorEventArgs>(OnBlockchainError);
                _blockChainInfoSocket.OnClose   += new EventHandler <CloseEventArgs>(OnBlockchainClose);
                _blockChainInfoSocket.OnMessage += new EventHandler <MessageEventArgs>(OnBlockchainMessage);

                _blockChainInfoSocket.Connect();

                while (!exitFlag) // exit is handled by signals handling at end of loop
                {
                    BotLog.Write(0, "MainCycle", "Cycle Start");

                    cycleStartTime = DateTime.UtcNow;
                    cycleEndTime   = cycleStartTime.AddSeconds(10);

                    try
                    {
                        OnEveryTenSeconds();

                        if (cycleStartTime.Second < lastSecond)
                        {
                            OnEveryMinute();

                            if (cycleStartTime.Minute % 5 == 0)
                            {
                                OnEveryFiveMinutes();
                            }
                        }

                        if (cycleStartTime.Minute < lastMinute)
                        {
                            OnEveryHour();

                            if (DateTime.Now.Hour == 10 && DateTime.Today.DayOfWeek == DayOfWeek.Tuesday)
                            {
                                OnTuesdayMorning();
                            }

                            if (DateTime.Now.Hour == 7 && DateTime.Today.DayOfWeek == DayOfWeek.Monday)
                            {
                                OnMondayMorning();
                            }
                        }

                        if (cycleStartTime.Hour >= 12 && lastHour < 12)
                        {
                            OnNoon();
                        }

                        if (cycleStartTime.Hour < lastHour)
                        {
                            OnMidnight();
                        }
                    }

                    catch (Exception e)
                    {
                        // Note each "OnEvery..." catches its own errors and sends Exception mails,
                        // so that failure in one should not stop the others from running. This particular
                        // code should never run.

                        ExceptionMail.Send(new Exception("Failed in swarmops-backend main loop", e), true);
                    }

                    lastSecond = cycleStartTime.Second;
                    lastMinute = cycleStartTime.Minute;
                    lastHour   = cycleStartTime.Hour;

                    // Wait for a maximum of ten seconds (the difference between cycleStartTime and cycleEndTime)

                    int      iterationCount = 0;
                    DateTime utcNow         = DateTime.UtcNow;
                    while (utcNow < cycleEndTime && !exitFlag)
                    {
                        int signalIndex = 250;

                        // Handle important service orders (those that can't be lost in a random loss
                        // of connection of a socket):

                        BackendServiceOrders backendOrders = BackendServiceOrders.GetNextBatch(5);
                        backendOrders.Execute(); // takes at most 250ms per BSO reqs

                        // Block until a SIGINT or SIGTERM signal is generated, or 1/4 second has passed.
                        // However, we can't do that in a development environment - it won't have the
                        // Mono.Posix assembly, and won't understand UnixSignals. So people running this in
                        // a dev environment will need to stop it manually.

                        if (!Debugger.IsAttached)
                        {
                            signalIndex = UnixSignal.WaitAny(killSignals, 250);
                        }
                        else
                        {
                            TimeSpan timeLeft = (cycleEndTime - utcNow);

                            BotLog.Write(0, "MainCycle Debug",
                                         string.Format(CultureInfo.InvariantCulture,
                                                       "Waiting for {0:F2} more seconds for cycle end",
                                                       timeLeft.TotalMilliseconds / 1000.0));
                            Thread.Sleep(250);
                        }

                        if (signalIndex < 250)
                        {
                            exitFlag = true;
                            Console.WriteLine("Caught signal " + killSignals[signalIndex].Signum + ", exiting");
                            BotLog.Write(0, "MainCycle",
                                         "EXIT SIGNAL (" + killSignals[signalIndex].Signum + "), terminating backend");
                        }

                        utcNow = DateTime.UtcNow;

                        // Every second, send an internal heartbeat

                        if (iterationCount++ % 4 == 0)
                        {
                            InternalHeartbeat();
                        }
                    }
                }
            }

            Console.WriteLine(" * Swarmops Backend stopping");
            BotLog.Write(0, "MainCycle", "BACKEND EXITING, sending backend-termination notices");

            /*
             * if (HeartBeater.Instance.WasKilled)
             * {
             *  // removed unconditional delete, cron job that restarts bot uses it to know that it is intentionally down.
             *  ExceptionMail.Send(new Exception("HeartBeater triggered restart of Swarmops Backend. Will commence after 800 seconds."), false);
             * }*/

            BotLog.Write(0, "MainCycle", "...done");

            /*
             * while (!MailTransmitter.CanExit)
             * {
             *  System.Threading.Thread.Sleep(50);
             * }*/

            _socketServer.Stop();

            Thread.Sleep(2000);
        }
Example #3
0
        private static void OnEveryHour()
        {
            try
            {
                BotLog.Write(0, "MainCycle", "One-hour entry");

                try
                {
                    // This will upgrade the database schema if and only if we failed to do so on entry.

                    if (SwarmDb.DbVersion < SwarmDb.DbVersionExpected)
                    {
                        BotLog.Write(1, "OneHour", "Entering DbUpgrade");
                        DatabaseMaintenance.UpgradeSchemata();
                        BotLog.Write(1, "OneHour", "Exited DbUpgrade");
                    }
                }
                catch (Exception e)
                {
                    TraceAndReport(e);
                }


                try
                {
                    BotLog.Write(1, "OneHour", "Entering Automatch");
                    Organizations organizations = Organizations.GetAll();
                    foreach (Organization organization in organizations)
                    {
                        if (organization.IsEconomyEnabled)
                        {
                            BotLog.Write(1, "OneHour", "Automatching org #" + organization.Identity.ToString(CultureInfo.InvariantCulture));
                            Payouts.AutomatchAgainstUnbalancedTransactions(organization);
                        }
                    }
                    BotLog.Write(1, "OneHour", "Exited Automatch");

                    /*TestTrace("Running PaymentGroupMapper.Run()...");
                     * PaymentGroupMapper.Run();
                     * TestTrace(" done.\r\n");*/
                }
                catch (Exception e)
                {
                    TraceAndReport(e);
                }

                try
                {
                    /*TestTrace("Running BlogTop50Scraper.Run()...");
                     * BlogTop50Scraper.Run();
                     * TestTrace(" done.\r\n");*/
                }
                catch (Exception e)
                {
                    TraceAndReport(e);
                }

                try
                {
                    /*TestTrace("Running Mappery.CreatePiratpartietOrganizationStrengthCircuitMap()...");
                     * Mappery.CreatePiratpartietOrganizationStrengthCircuitMap();
                     * TestTrace(" done.\r\n");*/
                }
                catch (Exception e)
                {
                    TraceAndReport(e);
                }

                try
                {
                    /*TestTrace("Running Mappery.CreatePiratpartietOrganizationStrengthCityMap()...");
                     * Mappery.CreatePiratpartietOrganizationStrengthCityMap();
                     * TestTrace(" done.\r\n");*/
                }
                catch (Exception e)
                {
                    TraceAndReport(e);
                }

                BotLog.Write(0, "MainCycle", "One-hour exit");
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }
        }
Example #4
0
        /// <summary>
        /// Pokrećemo proceduru BACKUP-a
        /// </summary>
        public void Start()
        {
            // ----------------------------------------------------------------------------------------------------------------------------
            // Automatski backup baze
            // ----------------------------------------------------------------------------------------------------------------------------
            // postavljamo automatski backup ukoliko nije podešen
            if (string.IsNullOrEmpty(Mipsed7.Core.ApplicationDatabaseInformation.AutoBackup_MIPSED7_dbBackup_StartAutomatically))
            {
                Mipsed7.Core.ApplicationDatabaseInformation.AutoBackup_MIPSED7_dbBackup_StartAutomatically = "1";
            }

            if (Mipsed7.Core.ApplicationDatabaseInformation.AutoBackup_MIPSED7_dbBackup_StartAutomatically == "1")
            {
                Mipsed7.Core.ApplicationDatabaseInformation.AutoBackup_MIPSED7_dbBackup = AppDomain.CurrentDomain.BaseDirectory + "MIPSED.7.dbbackup.exe";
            }
            else
            {
                Mipsed7.Core.ApplicationDatabaseInformation.AutoBackup_MIPSED7_dbBackup = string.Empty;

                // gasimo aplikaciju
                System.Diagnostics.Process.GetCurrentProcess().Kill();

                // ukoliko automatski backup nije podešen, izađi iz procedure
                return;
            }


            // pristup INTERNETU - ukoliko je FALSE izađi iz procedure
            if (!IsConnectedToInternet())
            {
                return;
            }

            // STEP #1 - planiranje backupo-ova
            DatabaseMaintenance databaseMaintenance = new DatabaseMaintenance();
            ZipFile             zipFile             = new ZipFile();
            FTPClient           ftpClient           = new FTPClient();

            string oibKorisnika           = Mipsed7.Core.ApplicationDatabaseInformation.OIB;
            string databaseBackupFilename = string.Empty;
            string backupPath             = string.Empty;


            // ----------------------------------------------
            // DNEVNI backup
            // ----------------------------------------------
            databaseBackupFilename = string.Format("{0}_database_{1}_dnevni_{2}_{3}_{4}.bak", Mipsed7.Core.ApplicationDatabaseInformation.DatabaseName.Replace(" ", "_"), oibKorisnika, DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);

            DatabaseObject databaseObject = new DatabaseObject(DatabaseType.Dnevna, oibKorisnika, databaseBackupFilename);

            // provjera
            if (!ftpClient.FileExists(databaseObject))
            {
                // backup
                databaseMaintenance.Backup(databaseObject, out backupPath);

                // compress file into ZIP archive
                zipFile.CompressFile(backupPath);

                // upload
                ftpClient.FileUpload(databaseObject, backupPath);
            }



            // ----------------------------------------------
            // TJEDNI backup
            // ----------------------------------------------
            databaseBackupFilename = string.Format("{0}_database_{1}_tjedni_{2}_{3}.bak", Mipsed7.Core.ApplicationDatabaseInformation.DatabaseName.Replace(" ", "_"), oibKorisnika, DateTime.Today.Year, ApplicationLogic.Tools.DateTimeTool.WeekIndex(DateTime.Today));

            databaseObject = new DatabaseObject(DatabaseType.Tjedna, oibKorisnika, databaseBackupFilename);

            // provjera
            if (!ftpClient.FileExists(databaseObject))
            {
                // backup
                databaseMaintenance.Backup(databaseObject, out backupPath);

                // compress file into ZIP archive
                zipFile.CompressFile(backupPath);

                // upload
                ftpClient.FileUpload(databaseObject, backupPath);

                // delete daily backups
                ftpClient.DeleteDailyBackups(string.Format("/{0}/{1}", oibKorisnika, DateTime.Today.Year));
            }



            // ----------------------------------------------
            // MJESEČNI backup - prvog u mjesecu za prošli mjesec
            // ----------------------------------------------
            databaseBackupFilename = string.Format("{0}_database_{1}_mjesecni_{2}_{3}.bak", Mipsed7.Core.ApplicationDatabaseInformation.DatabaseName.Replace(" ", "_"), oibKorisnika, DateTime.Today.AddMonths(-1).Year, DateTime.Today.AddMonths(-1).Month);

            databaseObject = new DatabaseObject(DatabaseType.Mjesecna, oibKorisnika, databaseBackupFilename);

            // provjera
            if (!ftpClient.FileExists(databaseObject))
            {
                // backup
                databaseMaintenance.Backup(databaseObject, out backupPath);

                // compress file into ZIP archive
                zipFile.CompressFile(backupPath);

                // upload
                ftpClient.FileUpload(databaseObject, backupPath);

                // delete daily & week backups
                ftpClient.DeleteDailyBackups(string.Format("/{0}/{1}", oibKorisnika, DateTime.Today.Year));
                ftpClient.DeleteWeeklyBackups(string.Format("/{0}/{1}", oibKorisnika, DateTime.Today.Year));
            }

            databaseMaintenance.DeleteBackupFolder();
        }
Example #5
0
        ///<summary>Return false to indicate exit app.  Only called when program first starts up at the beginning of FormOpenDental.PrefsStartup.</summary>
        public bool Convert(string fromVersion, string toVersion, bool silent)
        {
            FromVersion = new Version(fromVersion);
            ToVersion   = new Version(toVersion);        //Application.ProductVersion);
            if (FromVersion >= new Version("3.4.0") && PrefC.GetBool(PrefName.CorruptedDatabase))
            {
                MsgBox.Show(this, "Your database is corrupted because a conversion failed.  Please contact us.  This database is unusable and you will need to restore from a backup.");
                return(false);               //shuts program down.
            }
            if (FromVersion == ToVersion)
            {
                return(true);                         //no conversion necessary
            }
            if (FromVersion.CompareTo(ToVersion) > 0) //"Cannot convert database to an older version."
            //no longer necessary to catch it here.  It will be handled soon enough in CheckProgramVersion
            {
                return(true);
            }
            if (FromVersion < new Version("2.8.0"))
            {
                MsgBox.Show(this, "This database is too old to easily convert in one step. Please upgrade to 2.1 if necessary, then to 2.8.  Then you will be able to upgrade to this version. We apologize for the inconvenience.");
                return(false);
            }
            if (FromVersion < new Version("6.6.2"))
            {
                MsgBox.Show(this, "This database is too old to easily convert in one step. Please upgrade to 11.1 first.  Then you will be able to upgrade to this version. We apologize for the inconvenience.");
                return(false);
            }
            if (FromVersion < new Version("3.0.1"))
            {
                MsgBox.Show(this, "This is an old database.  The conversion must be done using MySQL 4.1 (not MySQL 5.0) or it will fail.");
            }
            if (FromVersion.ToString() == "2.9.0.0" || FromVersion.ToString() == "3.0.0.0" || FromVersion.ToString() == "4.7.0.0")
            {
                MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                return(false);
            }
            if (FromVersion > new Version("4.7.0") && FromVersion.Build == 0)
            {
                MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                return(false);
            }
            if (FromVersion >= ConvertDatabases.LatestVersion)
            {
                return(true);               //no conversion necessary
            }
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                MsgBox.Show(this, "Web client cannot convert database.  Must be using a direct connection.");
                return(false);
            }
            if (ReplicationServers.ServerIsBlocked())
            {
                MsgBox.Show(this, "This replication server is blocked from performing updates.");
                return(false);
            }
#if TRIALONLY
            //Trial users should never be able to update a database.
            MsgBox.Show(this, "Trial versions cannot connect to live databases.  Please run the Setup.exe in the AtoZ folder to reinstall your original version.");
            return(false);
#endif
            if (PrefC.GetString(PrefName.WebServiceServerName) != "" &&       //using web service
                !ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.WebServiceServerName).ToLower()))                   //and not on web server
            {
#if !DEBUG
                MessageBox.Show(Lan.g(this, "Updates are only allowed from the web server: ") + PrefC.GetString(PrefName.WebServiceServerName));
                return(false);
#endif
            }
            //If MyISAM and InnoDb mix, then try to fix
            if (DataConnection.DBtype == DatabaseType.MySql)                    //not for Oracle
            {
                string namesInnodb = DatabaseMaintenance.GetInnodbTableNames(); //Or possibly some other format.
                int    numMyisam   = DatabaseMaintenance.GetMyisamTableCount();
                if (namesInnodb != "" && numMyisam > 0)
                {
                    MessageBox.Show(Lan.g(this, "A mixture of database tables in InnoDB and MyISAM format were found.  A database backup will now be made, and then the following InnoDB tables will be converted to MyISAM format: ") + namesInnodb);
                    try {
                        MiscData.MakeABackup();                        //Does not work for Oracle, due to some MySQL specific commands inside.
                    }
                    catch (Exception e) {
                        Cursor.Current = Cursors.Default;
                        if (e.Message != "")
                        {
                            MessageBox.Show(e.Message);
                        }
                        MsgBox.Show(this, "Backup failed. Your database has not been altered.");
                        return(false);
                    }
                    if (!DatabaseMaintenance.ConvertTablesToMyisam())
                    {
                        MessageBox.Show(Lan.g(this, "Failed to convert InnoDB tables to MyISAM format. Please contact support."));
                        return(false);
                    }
                    MessageBox.Show(Lan.g(this, "All tables converted to MyISAM format successfully."));
                    namesInnodb = "";
                }
                if (namesInnodb == "" && numMyisam > 0)             //if all tables are myisam
                //but default storage engine is innodb, then kick them out.
                {
                    if (DatabaseMaintenance.GetStorageEngineDefaultName().ToUpper() != "MYISAM")                    //Probably InnoDB but could be another format.
                    {
                        MessageBox.Show(Lan.g(this, "The database tables are in MyISAM format, but the default database engine format is InnoDB. You must change the default storage engine within the my.ini (or my.cnf) file on the database server and restart MySQL in order to fix this problem. Exiting."));
                        return(false);
                    }
                }
            }
#if DEBUG
            if (!silent && MessageBox.Show("You are in Debug mode.  Your database can now be converted" + "\r"
                                           + "from version" + " " + FromVersion.ToString() + "\r"
                                           + "to version" + " " + ToVersion.ToString() + "\r"
                                           + "You can click Cancel to skip conversion and attempt to the newer code against the older database."
                                           , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(true);               //If user clicks cancel, then do nothing
            }
#else
            if (!silent && MessageBox.Show(Lan.g(this, "Your database will now be converted") + "\r"
                                           + Lan.g(this, "from version") + " " + FromVersion.ToString() + "\r"
                                           + Lan.g(this, "to version") + " " + ToVersion.ToString() + "\r"
                                           + Lan.g(this, "The conversion works best if you are on the server.  Depending on the speed of your computer, it can be as fast as a few seconds, or it can take as long as 10 minutes.")
                                           , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(false);               //If user clicks cancel, then close the program
            }
#endif
            Cursor.Current = Cursors.WaitCursor;
#if !DEBUG
            if (DataConnection.DBtype != DatabaseType.MySql &&
                !MsgBox.Show(this, true, "If you have not made a backup, please Cancel and backup before continuing.  Continue?"))
            {
                return(false);
            }
            try{
                if (DataConnection.DBtype == DatabaseType.MySql)
                {
                    MiscData.MakeABackup();                    //Does not work for Oracle, due to some MySQL specific commands inside.
                }
            }
            catch (Exception e) {
                Cursor.Current = Cursors.Default;
                if (e.Message != "")
                {
                    MessageBox.Show(e.Message);
                }
                MsgBox.Show(this, "Backup failed. Your database has not been altered.");
                return(false);
            }
            try{
#endif
            if (FromVersion < new Version("7.5.17"))             //Insurance Plan schema conversion
            {
                Cursor.Current = Cursors.Default;
                YN InsPlanConverstion_7_5_17_AutoMergeYN = YN.Unknown;
                if (FromVersion < new Version("7.5.1"))
                {
                    FormInsPlanConvert_7_5_17 form = new FormInsPlanConvert_7_5_17();
                    if (PrefC.GetBoolSilent(PrefName.InsurancePlansShared, true))
                    {
                        form.InsPlanConverstion_7_5_17_AutoMergeYN = YN.Yes;
                    }
                    else
                    {
                        form.InsPlanConverstion_7_5_17_AutoMergeYN = YN.No;
                    }
                    form.ShowDialog();
                    if (form.DialogResult == DialogResult.Cancel)
                    {
                        MessageBox.Show("Your database has not been altered.");
                        return(false);
                    }
                    InsPlanConverstion_7_5_17_AutoMergeYN = form.InsPlanConverstion_7_5_17_AutoMergeYN;
                }
                ConvertDatabases.Set_7_5_17_AutoMerge(InsPlanConverstion_7_5_17_AutoMergeYN);                //does nothing if this pref is already present for some reason.
                Cursor.Current = Cursors.WaitCursor;
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, true);
            }
            ConvertDatabases.FromVersion = FromVersion;
            ConvertDatabases.To2_8_2();            //begins going through the chain of conversion steps
            Cursor.Current = Cursors.Default;
            if (FromVersion >= new Version("3.4.0"))
            {
                //CacheL.Refresh(InvalidType.Prefs);//or it won't know it has to update in the next line.
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false, true);              //more forceful refresh in order to properly change flag
            }
            if (!silent)
            {
                MsgBox.Show(this, "Database update successful");
            }
            Cache.Refresh(InvalidType.Prefs);
            return(true);

#if !DEBUG
        }

        catch (System.IO.FileNotFoundException e) {
            MessageBox.Show(e.FileName + " " + Lan.g(this, "could not be found. Your database has not been altered and is still usable if you uninstall this version, then reinstall the previous version."));
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false);
            }
            //Prefs.Refresh();
            return(false);
        }
        catch (System.IO.DirectoryNotFoundException) {
            MessageBox.Show(Lan.g(this, "ConversionFiles folder could not be found. Your database has not been altered and is still usable if you uninstall this version, then reinstall the previous version."));
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false);
            }
            //Prefs.Refresh();
            return(false);
        }
        catch (Exception ex) {
            //	MessageBox.Show();
            MessageBox.Show(ex.Message + "\r\n\r\n"
                            + Lan.g(this, "Conversion unsuccessful. Your database is now corrupted and you cannot use it.  Please contact us."));
            //Then, application will exit, and database will remain tagged as corrupted.
            return(false);
        }
#endif
        }
        private void InitializeMaintenance(DatabaseMaintenance maintenance)
        {
            if (grdResult.Redraw)
            {
                grdResult.BeginUpdate();
            }
            grdResult.ClearRowsAndColumns();
            btnAnalyze.Enabled  = false; btnCheck.Enabled = false;
            btnOptimize.Enabled = false; btnRepair.Enabled = false;
            pctLoad.Show(); pctLoad.BringToFront();

            Func <DatabaseMaintenance, DataTable> _delelgate = new Func <DatabaseMaintenance, DataTable>(GetMaintenanceResult);
            IAsyncResult _result = _delelgate.BeginInvoke(maintenance, null, _delelgate);

            while (!_result.IsCompleted &&
                   !_cancelled)
            {
                Thread.Sleep(1); Application.DoEvents();
            }

            if (_cancelled)
            {
                if (!_result.IsCompleted)
                {
                    try { _result = null; }
                    catch { }
                    finally { Materia.RefreshAndManageCurrentProcess(); }
                }

                return;
            }
            else
            {
                DataTable _table = _delelgate.EndInvoke(_result);
                if (_table != null)
                {
                    DataTable _datasource = new DataTable();
                    _datasource.TableName = "maintenance";

                    DataColumn _pk = _datasource.Columns.Add("Id", typeof(long));
                    _datasource.Columns.Add("Image", typeof(Image));
                    _datasource.Columns.Add("Table", typeof(string));
                    _datasource.Columns.Add("Remarks", typeof(string));

                    _pk.AutoIncrement     = true; _pk.AutoIncrementSeed = 1;
                    _pk.AutoIncrementStep = 1;

                    _datasource.Constraints.Add("PK", _pk, true);

                    var _query = from _tbl in _table.AsEnumerable()
                                 select new
                    {
                        Table   = _tbl.Field <string>("Table"),
                        Image   = (_tbl.Field <string>("Msg_Text").ToUpper() == "OK" ? _images.Images["check"] : _images.Images["warning"]),
                        Remarks = _tbl.Field <string>("Msg_Text")
                    };

                    foreach (var _row in _query)
                    {
                        _datasource.Rows.Add(new object[] { null,
                                                            _row.Image, _row.Table, _row.Remarks });
                    }

                    _datasource.AcceptChanges();

                    grdResult.DataSource = _datasource;
                    ColumnCollection _cols = grdResult.Cols;
                    _cols["Id"].Visible = false; _cols["Image"].Caption = "";

                    string _tablecaption = "";

                    switch (maintenance)
                    {
                    case DatabaseMaintenance.Analyze:
                        _tablecaption = "Analyzed Table"; break;

                    case DatabaseMaintenance.Check:
                        _tablecaption = "Checked Table"; break;

                    case DatabaseMaintenance.Optimize:
                        _tablecaption = "Optimized Table"; break;

                    case DatabaseMaintenance.Repair:
                        _tablecaption = "Repaired Table"; break;

                    default: break;
                    }

                    _cols["Table"].Caption = _tablecaption;
                    grdResult.AutoSizeCols(); grdResult.ExtendLastCol = true;
                    _cols[_cols.Fixed - 1].Visible = false;
                    _cols["Image"].Width           = 30;

                    Cursor = Cursors.WaitCursor;
                    IAsyncResult _logresult = SCMS.CurrentSystemUser.LogActionAsync(UserAction.MaintainDatabase, _tablecaption);
                    _logresult.WaitToFinish(); Cursor = Cursors.Default;

                    while (!grdResult.Redraw)
                    {
                        grdResult.EndUpdate();
                    }
                }
            }

            btnAnalyze.Enabled  = true; btnCheck.Enabled = true;
            btnOptimize.Enabled = true; btnRepair.Enabled = true;
            pctLoad.Hide();
        }
Example #7
0
 ///<summary>Inserts one DatabaseMaintenance into the database.  Returns the new priKey.</summary>
 public static long Insert(DatabaseMaintenance databaseMaintenance)
 {
     return(Insert(databaseMaintenance, false));
 }
Example #8
0
        private void Run(bool isCheck)
        {
            Cursor = Cursors.WaitCursor;
            bool          verbose = checkShow.Checked;
            StringBuilder strB    = new StringBuilder();

            strB.Append('-', 90);
            textLog.Text = DateTime.Now.ToString() + strB.ToString() + "\r\n";
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.MySQLTables(verbose, isCheck);
            if (!DatabaseMaintenance.GetSuccess())
            {
                Cursor = Cursors.Default;
                return;
            }
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.DatesNoZeros(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.DecimalValues(verbose, isCheck);
            Application.DoEvents();
            //Now, methods that apply to specific tables----------------------------------------------------------------------------
            textLog.Text += DatabaseMaintenance.AppointmentsNoPattern(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.AppointmentsNoDateOrProcs(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.AppointmentsNoPatients(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.AppointmentPlannedNoPlannedApt(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.AutoCodesDeleteWithNoItems(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.AutomationTriggersWithNoSheetDefs(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.BillingTypesInvalid(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.CanadaCarriersCdaMissingInfo(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimDeleteWithNoClaimProcs(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimWithInvalidInsSubNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimWriteoffSum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimPaymentCheckAmt(verbose, isCheck);         //also fixes resulting deposit misbalances.
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimPaymentDeleteWithNoSplits(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcDateNotMatchCapComplete(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcDateNotMatchPayment(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcWithInvalidClaimNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcDeleteWithInvalidClaimNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcDeleteEstimateWithInvalidProcNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcEstNoBillIns(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcEstWithInsPaidAmt(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcPatNumMissing(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcProvNumMissing(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcPreauthNotMatchClaim(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcStatusNotMatchClaim(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcWithInvalidClaimPaymentNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClaimProcWriteOffNegative(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ClockEventInFuture(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.DocumentWithNoCategory(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.FeeDeleteDuplicates(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.InsPlanInvalidCarrier(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.InsPlanNoClaimForm(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.InsPlanInvalidNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.InsSubNumMismatchPlanNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.LaboratoryWithInvalidSlip(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.MedicationPatDeleteWithInvalidMedNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatFieldsDeleteDuplicates(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatientBadGuarantor(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatientDeletedWithClinicNumSet(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatientsNoClinicSet(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatientPriProvHidden(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatientPriProvMissing(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatientUnDeleteWithBalance(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatPlanDeleteWithInvalidInsSubNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatPlanOrdinalZeroToOne(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PatPlanOrdinalTwoToOne(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PaymentDetachMissingDeposit(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PaymentMissingPaySplit(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PayPlanChargeGuarantorMatch(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PayPlanChargeProvNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PayPlanSetGuarantorToPatForIns(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PaySplitWithInvalidPayNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PaySplitAttachedToPayPlan(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PreferenceDateDepositsStarted(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.PreferencePracticeProv(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcButtonItemsDeleteWithInvalidAutoCode(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogAttachedToApptWithProcStatusDeleted(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogAttachedToWrongAppts(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogAttachedToWrongApptDate(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogBaseUnitsZero(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogCodeNumInvalid(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogLabAttachedToDeletedProc(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogProvNumMissing(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogToothNums(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogTpAttachedToClaim(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProcedurelogUnitQtyZero(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.ProviderHiddenWithClaimPayments(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.RecallDuplicatesWarn(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.RecallTriggerDeleteBadCodeNum(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.SchedulesDeleteShort(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.SchedulesDeleteProvClosed(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.SignalInFuture(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.StatementDateRangeMax(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += DatabaseMaintenance.TaskSubscriptionsInvalid(verbose, isCheck);
            Application.DoEvents();
            textLog.Text += Lan.g("FormDatabaseMaintenance", "Done");
            SaveLogToFile();
            Cursor = Cursors.Default;
        }
Example #9
0
        private static void Main(string[] args)
        {
            testMode = false;

            UnixSignal[] killSignals = new UnixSignal[] {
                new UnixSignal(Signum.SIGINT),
                new UnixSignal(Signum.SIGTERM),
            };

            BotLog.Write(0, "MainCycle", string.Empty);
            BotLog.Write(0, "MainCycle", "-----------------------------------------------");
            BotLog.Write(0, "MainCycle", string.Empty);

            if (args.Length > 0)
            {
                if (args[0].ToLower() == "test")
                {/*
                  * BotLog.Write(0, "MainCycle", "Running self-tests");
                  * HeartBeater.Instance.Beat(heartbeatFile);  // Otherwise Heartbeater.Beat() will fail in various places
                  *
                  * testMode = true;
                  * Console.WriteLine("Testing All Maintenance Processes (except membership-changing ones).");
                  * PWLog.Write(PWLogItem.None, 0, PWLogAction.SystemTest, string.Empty, string.Empty);
                  *
                  * Console.WriteLine("\r\n10-second intervals:");
                  * OnEveryTenSeconds();
                  * Console.WriteLine("\r\nEvery minute:");
                  * OnEveryMinute();
                  * Console.WriteLine("\r\nEvery five minutes:");
                  * OnEveryFiveMinutes();
                  * Console.WriteLine("\r\nEvery hour:");
                  * OnEveryHour();
                  * Console.WriteLine("\r\nNoon:");
                  * OnNoon();
                  * Console.WriteLine("\r\nMidnight:");
                  * OnMidnight();
                  */
                    Console.WriteLine("Testing database access...");

                    Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).Name);
                    Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).PasswordHash);

                    Console.WriteLine("Creating OutboundComm...");

                    OutboundComm.CreateNotification(null, NotificationResource.System_Startup);

                    Console.WriteLine("Transmitting...");

                    OutboundComms comms = OutboundComms.GetOpen();

                    Console.WriteLine("{0} open items in outbound comms.", comms.Count);

                    foreach (OutboundComm comm in comms)
                    {
                        if (comm.TransmitterClass != "Swarmops.Utility.Communications.CommsTransmitterMail")
                        {
                            throw new NotImplementedException();
                        }

                        ICommsTransmitter transmitter = new Swarmops.Utility.Communications.CommsTransmitterMail();

                        OutboundCommRecipients recipients = comm.Recipients;
                        PayloadEnvelope        envelope   = PayloadEnvelope.FromXml(comm.PayloadXml);

                        foreach (OutboundCommRecipient recipient in recipients)
                        {
                            transmitter.Transmit(envelope, recipient.Person);
                        }
                    }


                    Console.Write("\r\nAll tests run. Waiting for mail queue to flush... ");
                    while (!MailTransmitter.CanExit)
                    {
                        System.Threading.Thread.Sleep(50);
                    }

                    Console.WriteLine("done.");
                    BotLog.Write(0, "MainCycle", "Exiting self-tests");
                    return;
                }

                if (args[0].ToLower() == "console")
                {
                    Console.WriteLine("\r\nRunning Swarmops-Backend in CONSOLE mode.\r\n");

                    // -------------------------------------------------------------------------------------
                    // -------------------------------------------------------------------------------------
                    // -------------------------------------------------------------------------------------

                    // -----------------------    INSERT ANY ONE-OFF ACTIONS HERE  -------------------------


                    Console.Write("\r\nWaiting for mail queue to flush... ");

                    while (!MailTransmitter.CanExit)
                    {
                        System.Threading.Thread.Sleep(50);
                    }

                    Console.WriteLine("done.");

                    return;
                }

                if (args[0].ToLower() == "rsm")
                {
                    Console.WriteLine("Testing character encoding: räksmörgås RÄKSMÖRGÅS");
                    return;
                }
            }

            /*
             * MailMessage message = new MailMessage();
             * message.From = new MailAddress(Strings.MailSenderAddress, Strings.MailSenderName);
             * message.To.Add (new MailAddress ("*****@*****.**", "Rick Falkvinge (Piratpartiet)"));
             * message.Subject = "Räksmörgåsarnas ékÖNÖMÏåvdëlnïng";
             * message.Body = "Hejsan hoppsan Räksmörgåsar.";
             * message.BodyEncoding = Encoding.Default;
             * message.SubjectEncoding = Encoding.Default;
             *
             * SmtpClient smtpClient = new SmtpClient ("localhost");
             * smtpClient.Credentials = null; // mono bug
             * smtpClient.Send (message);*/

            Console.WriteLine(" * Swarmops Backend starting");

            BotLog.Write(0, "MainCycle", "Backend STARTING");

            OutboundComm.CreateNotification(null, NotificationResource.System_Startup);

            // Checking for schemata upgrade

            DatabaseMaintenance.UpgradeSchemata();

            // Check for existence of installation ID. If not, create one. Warning: has privacy implications when communicated.

            if (Persistence.Key["SwarmopsInstallationId"] == string.Empty)
            {
                Persistence.Key["SwarmopsInstallationId"] = Guid.NewGuid().ToString();
            }

            DateTime cycleStartTime = DateTime.Now;

            int lastSecond = cycleStartTime.Second;
            int lastMinute = cycleStartTime.Minute;
            int lastHour   = cycleStartTime.Hour;

            bool exitFlag = false;

            while (!exitFlag)  // exit is handled by signals handling at end of loop
            {
                BotLog.Write(0, "MainCycle", "Cycle Start");

                cycleStartTime = DateTime.Now;

                try
                {
                    OnEveryTenSeconds();

                    if (cycleStartTime.Second < lastSecond)
                    {
                        OnEveryMinute();

                        if (cycleStartTime.Minute % 5 == 0)
                        {
                            OnEveryFiveMinutes();
                        }
                    }

                    if (cycleStartTime.Minute < lastMinute)
                    {
                        OnEveryHour();

                        if (DateTime.Now.Hour == 10 && DateTime.Today.DayOfWeek == DayOfWeek.Tuesday)
                        {
                            OnTuesdayMorning();
                        }
                    }

                    if (cycleStartTime.Hour >= 12 && lastHour < 12)
                    {
                        OnNoon();
                    }

                    if (cycleStartTime.Hour < lastHour)
                    {
                        OnMidnight();
                    }
                }

                catch (Exception e)
                {
                    // Note each "OnEvery..." catches its own errors and sends Exception mails,
                    // so that failure in one should not stop the others from running. This particular
                    // code should never run.

                    ExceptionMail.Send(new Exception("Failed in swarmops-backend main loop", e), true);
                }

                lastSecond = cycleStartTime.Second;
                lastMinute = cycleStartTime.Minute;
                lastHour   = cycleStartTime.Hour;

                // Wait for a maximum of ten seconds

                while (DateTime.Now < cycleStartTime.AddSeconds(10) && !exitFlag)
                {
                    // block until a SIGINT or SIGTERM signal is generated, or one second has passed.
                    int signalIndex = UnixSignal.WaitAny(killSignals, 1000);

                    if (signalIndex < 1000)
                    {
                        exitFlag = true;
                        Console.WriteLine("Caught signal " + killSignals[signalIndex].Signum.ToString() + ", exiting");
                        BotLog.Write(0, "MainCycle", "EXIT SIGNAL (" + killSignals[signalIndex].Signum.ToString() + "), terminating backend");
                    }
                }
            }

            Console.WriteLine(" * Swarmops Backend stopping");
            BotLog.Write(0, "MainCycle", "BACKEND EXITING, sending backend-termination notices");

            /*
             * if (HeartBeater.Instance.WasKilled)
             * {
             *  // removed unconditional delete, cron job that restarts bot uses it to know that it is intentionally down.
             *  ExceptionMail.Send(new Exception("HeartBeater triggered restart of Swarmops Backend. Will commence after 800 seconds."), false);
             * }*/

            BotLog.Write(0, "MainCycle", "...done");

            /*
             * while (!MailTransmitter.CanExit)
             * {
             *  System.Threading.Thread.Sleep(50);
             * }*/

            Thread.Sleep(2000);
        }
Example #10
0
        ///<summary>This ONLY runs when first opening the program.  Gets run early in the sequence. Returns false if the program should exit.</summary>
        public static bool CheckMySqlVersion()
        {
            if (DataConnection.DBtype != DatabaseType.MySql)
            {
                return(true);
            }
            bool   hasBackup    = false;
            string thisVersion  = MiscData.GetMySqlVersion();
            float  floatVersion = PIn.Float(thisVersion.Substring(0, 3));

            if (floatVersion < 5.0f)
            {
                //We will force users to upgrade to 5.0, but not yet to 5.5
                MessageBox.Show(Lan.g("Prefs", "Your version of MySQL won't work with this program") + ": " + thisVersion
                                + ".  " + Lan.g("Prefs", "You should upgrade to MySQL 5.0 using the installer on our website."));
                Application.Exit();
                return(false);
            }
            if (!PrefC.ContainsKey("MySqlVersion"))             //db has not yet been updated to store this pref
            //We're going to skip this.  We will recommend that people first upgrade OD, then MySQL, so this won't be an issue.
            {
            }
            else if (Prefs.UpdateString(PrefName.MySqlVersion, floatVersion.ToString("f1")))
            {
                if (!MsgBox.Show("Prefs", MsgBoxButtons.OKCancel, "Tables will now be backed up, optimized, and repaired.  This will take a minute or two.  Continue?"))
                {
                    Application.Exit();
                    return(false);
                }
                try {
                    DatabaseMaintenance.BackupRepairAndOptimize();
                    hasBackup = true;
                }
                catch (Exception e) {
                    if (e.Message != "")
                    {
                        MessageBox.Show(e.Message);
                    }
                    MsgBox.Show("Prefs", "Backup failed. Your database has not been altered.");
                    Application.Exit();
                    return(false);                   //but this should never happen
                }
            }
            if (PrefC.ContainsKey("DatabaseConvertedForMySql41"))
            {
                return(true);               //already converted
            }
            if (!MsgBox.Show("Prefs", true, "Your database will now be converted for use with MySQL 4.1."))
            {
                Application.Exit();
                return(false);
            }
            //ClassConvertDatabase CCD=new ClassConvertDatabase();
            try {
                if (!hasBackup)                 //A backup could have been made if the tables were optimized and repaired above.
                {
                    MiscData.MakeABackup();
                }
            }
            catch (Exception e) {
                if (e.Message != "")
                {
                    MessageBox.Show(e.Message);
                }
                MsgBox.Show("Prefs", "Backup failed. Your database has not been altered.");
                Application.Exit();
                return(false);               //but this should never happen
            }
            MessageBox.Show("Backup performed");
            Prefs.ConvertToMySqlVersion41();
            MessageBox.Show("converted");
            //Refresh();
            return(true);
        }