Beispiel #1
0
        /// Copy constructor
        public TSrvSetting(TSrvSetting ACopyFrom)
        {
            if (USingletonSrvSetting == null)
            {
                USingletonSrvSetting = this;
            }

            FConfigurationFile                            = ACopyFrom.FConfigurationFile;
            FExecutingOS                                  = ACopyFrom.FExecutingOS;
            FRDBMSType                                    = ACopyFrom.FRDBMSType;
            FDatabaseHostOrFile                           = ACopyFrom.FDatabaseHostOrFile;
            FDatabasePort                                 = ACopyFrom.FDatabasePort;
            FDatabaseName                                 = ACopyFrom.FDatabaseName;
            FDBUsername                                   = ACopyFrom.FDBUsername;
            FDBPassword                                   = ACopyFrom.FDBPassword;
            FIPBasePort                                   = ACopyFrom.FIPBasePort;
            FServerLogFile                                = ACopyFrom.FServerLogFile;
            FHostName                                     = ACopyFrom.FHostName;
            FHostIPAddresses                              = ACopyFrom.FHostIPAddresses;
            FClientIdleStatusAfterXMinutes                = ACopyFrom.FClientIdleStatusAfterXMinutes;
            FClientKeepAliveCheckIntervalInSeconds        = ACopyFrom.FClientKeepAliveCheckIntervalInSeconds;
            FClientKeepAliveTimeoutAfterXSecondsLAN       = ACopyFrom.FClientKeepAliveTimeoutAfterXSecondsLAN;
            FClientKeepAliveTimeoutAfterXSecondsRemote    = ACopyFrom.FClientKeepAliveTimeoutAfterXSecondsRemote;
            FClientConnectionTimeoutAfterXSeconds         = ACopyFrom.FClientConnectionTimeoutAfterXSeconds;
            FClientAppDomainShutdownAfterKeepAliveTimeout = ACopyFrom.FClientAppDomainShutdownAfterKeepAliveTimeout;
            FApplicationVersion                           = ACopyFrom.FApplicationVersion;
            FSMTPServer                                   = ACopyFrom.FSMTPServer;
            FAutomaticIntranetExportEnabled               = ACopyFrom.FAutomaticIntranetExportEnabled;
            FRunAsStandalone                              = ACopyFrom.FRunAsStandalone;
            FIntranetDataDestinationEmail                 = ACopyFrom.FIntranetDataDestinationEmail;
            FIntranetDataSenderEmail                      = ACopyFrom.FIntranetDataSenderEmail;
        }
Beispiel #2
0
        /// <summary>
        /// would this patch file apply to the current installed version
        /// </summary>
        /// <param name="APatchZipFile"></param>
        /// <returns></returns>
        public Boolean PatchApplies(String APatchZipFile)
        {
            StringCollection versions          = GetVersionsFromDiffZipName(APatchZipFile);
            TFileVersionInfo patchStartVersion = new TFileVersionInfo(versions[0]);

            return(patchStartVersion.Compare(this) == 0);
        }
        public static bool LoginServerAdmin()
        {
            string WelcomeMessage;
            bool   SystemEnabled;
            Int32  ClientID;
            Int64  SiteKey;

            TConnectedClient CurrentClient = TClientManager.ConnectClient(
                "SYSADMIN", string.Empty,
                HttpContext.Current.Request.UserHostName,
                HttpContext.Current.Request.UserHostAddress,
                TFileVersionInfo.GetApplicationVersion().ToVersion(),
                TClientServerConnectionType.csctRemote,
                out ClientID,
                out WelcomeMessage,
                out SystemEnabled,
                out SiteKey);

            TSession.SetVariable("LoggedIn", true);

            // the following values are stored in the session object
            DomainManager.GClientID     = ClientID;
            DomainManager.CurrentClient = CurrentClient;
            DomainManager.GSiteKey      = SiteKey;

            return(true);
        }
Beispiel #4
0
        /// <summary>
        /// Initialize the Petra server and connect to the database
        /// </summary>
        /// <param name="AConfigName">just provide the server config file, plus AutoLogin and AutoLoginPasswd</param>
        public static TServerManager Connect(string AConfigName)
        {
            if (File.Exists(AConfigName))
            {
                new TAppSettingsManager(AConfigName);
            }
            else
            {
                new TAppSettingsManager();
            }

            new TLogging(TAppSettingsManager.GetValue("Server.LogFile"));

            CommonNUnitFunctions.InitRootPath();

            Catalog.Init();
            TServerManager.TheServerManager = new TServerManager();

            DBAccess.GDBAccessObj = new TDataBase();
            DBAccess.GDBAccessObj.EstablishDBConnection(TSrvSetting.RDMBSType,
                                                        TSrvSetting.PostgreSQLServer, TSrvSetting.PostgreSQLServerPort,
                                                        TSrvSetting.PostgreSQLDatabaseName,
                                                        TSrvSetting.DBUsername, TSrvSetting.DBPassword, "", "Ict.Testing.NUnitPetraServer.TPetraServerConnector.Connect DB Connection");

            bool       SystemEnabled;
            string     WelcomeMessage;
            IPrincipal ThisUserInfo;
            Int32      ClientID;

            TConnectedClient CurrentClient = TClientManager.ConnectClient(
                TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                TAppSettingsManager.GetValue("AutoLoginPasswd"),
                "NUNITTEST", "127.0.0.1",
                TFileVersionInfo.GetApplicationVersion().ToVersion(),
                TClientServerConnectionType.csctLocal,
                out ClientID,
                out WelcomeMessage,
                out SystemEnabled,
                out ThisUserInfo);

            // the following values are stored in the session object
            DomainManager.GClientID     = ClientID;
            DomainManager.CurrentClient = CurrentClient;
            UserInfo.GUserInfo          = (TPetraPrincipal)ThisUserInfo;

            TSetupDelegates.Init();
            TSystemDefaultsCache.GSystemDefaultsCache = new TSystemDefaultsCache();
            DomainManager.GetSiteKeyFromSystemDefaultsCacheDelegate =
                @TSystemDefaultsCache.GSystemDefaultsCache.GetSiteKeyDefault;

            TUserDefaults.InitializeUnit();

            StringHelper.CurrencyFormatTable = DBAccess.GDBAccessObj.SelectDT("SELECT * FROM PUB_a_currency", "a_currency", null);

            return((TServerManager)TServerManager.TheServerManager);
        }
Beispiel #5
0
        /// Upgrade the database to the latest version
        public bool UpgradeDatabase()
        {
            bool upgraded = false;

            while (true)
            {
                TFileVersionInfo originalDBVersion = GetCurrentDBVersion();
                TFileVersionInfo currentDBVersion  = originalDBVersion;
                TLogging.LogAtLevel(1, "current DB version: " + currentDBVersion.ToStringDotsHyphen());

                System.Type t = typeof(TDBUpgrade);

                foreach (MethodInfo m in t.GetMethods())
                {
                    if (m.Name.StartsWith(
                            String.Format("UpgradeDatabase{0}{1}_",
                                          originalDBVersion.FileMajorPart.ToString("0000"),
                                          originalDBVersion.FileMinorPart.ToString("00"))))
                    {
                        TFileVersionInfo testDBVersion = new TFileVersionInfo(
                            m.Name.Substring("UpgradeDatabase000000_".Length, 4) + "." +
                            m.Name.Substring("UpgradeDatabase000000_".Length + 4, 2) + ".0-0");

                        // check if the exefileversion is below testDBVersion
                        if (TSrvSetting.ApplicationVersion.Compare(testDBVersion) < 0)
                        {
                            TLogging.Log("Database Upgrade: ignoring method " + m.Name +
                                         " because the application version is behind: " +
                                         TSrvSetting.ApplicationVersion.ToString());
                            continue;
                        }

                        TLogging.Log("Database Upgrade: applying method " + m.Name);

                        bool result = (bool)m.Invoke(null, BindingFlags.Static, null, null, null);

                        if (result == true)
                        {
                            upgraded         = true;
                            currentDBVersion = testDBVersion;
                            SetCurrentDBVersion(currentDBVersion);
                        }

                        break;
                    }
                }

                // if the database version does not change anymore, then we are finished
                if (currentDBVersion.Compare(originalDBVersion) == 0)
                {
                    break;
                }
            }

            return(upgraded);
        }
Beispiel #6
0
        public eLoginEnum Login(string username, string password)
        {
            string     WelcomeMessage;
            bool       SystemEnabled;
            IPrincipal UserInfo;
            Int32      ClientID;

            return(LoginInternal(username, password, TFileVersionInfo.GetApplicationVersion().ToVersion(),
                                 out ClientID, out WelcomeMessage, out SystemEnabled, out UserInfo));
        }
Beispiel #7
0
        public string GetVersion()
        {
            object loggedIn = TSession.GetVariable("LoggedIn");

            if ((null != loggedIn) && ((bool)loggedIn == true))
            {
                return(TFileVersionInfo.GetApplicationVersion().ToVersion().ToString());
            }

            return("0.0.0.0");
        }
Beispiel #8
0
        public void TestVersionMismatch()
        {
            StreamReader     sr = new StreamReader("../../delivery/bin/version.txt");
            string           strServerVersion = sr.ReadLine();
            TFileVersionInfo ServerVersion    = new TFileVersionInfo(strServerVersion);

            sr.Close();

            Assert.AreEqual(eLoginEnum.eLoginSucceeded, TPetraConnector.Connect(
                                "../../etc/TestClient.config", false), "connecting with the same version number");
            TPetraConnector.Disconnect();

            TFileVersionInfo.FManualApplicationVersion =
                new TFileVersionInfo(new Version(ServerVersion.FileMajorPart, ServerVersion.FileMinorPart, ServerVersion.FileBuildPart,
                                                 ServerVersion.FilePrivatePart + 1));
            Assert.AreEqual(eLoginEnum.eLoginVersionMismatch, TPetraConnector.Connect(
                                "../../etc/TestClient.config", false), "client is too new, only change in private part");

            int FileMajorPart   = ServerVersion.FileMajorPart;
            int FileMinorPart   = ServerVersion.FileMinorPart;
            int FileBuildPart   = ServerVersion.FileBuildPart - 1;
            int FilePrivatePart = ServerVersion.FilePrivatePart;

            if (FileBuildPart < 0)
            {
                FileMinorPart -= 1;
                FileBuildPart  = 0;
            }
            else if (FileMinorPart < 0)
            {
                FileMajorPart -= 1;
                FileMinorPart  = 0;
            }

            TFileVersionInfo.FManualApplicationVersion =
                new TFileVersionInfo(new Version(FileMajorPart, FileMinorPart, FileBuildPart,
                                                 FilePrivatePart));
            Assert.AreEqual(eLoginEnum.eLoginVersionMismatch, TPetraConnector.Connect("../../etc/TestClient.config", false), "client is too old");

            TFileVersionInfo.FManualApplicationVersion =
                new TFileVersionInfo(new Version(ServerVersion.FileMajorPart, ServerVersion.FileMinorPart, ServerVersion.FileBuildPart + 1,
                                                 ServerVersion.FilePrivatePart));
            Assert.AreEqual(eLoginEnum.eLoginVersionMismatch, TPetraConnector.Connect("../../etc/TestClient.config", false), "client is too new");

            TFileVersionInfo.FManualApplicationVersion = new TFileVersionInfo(new Version());
            Assert.AreEqual(eLoginEnum.eLoginVersionMismatch, TPetraConnector.Connect(
                                "../../etc/TestClient.config", false), "version 0.0.0.0 should not be accepted");

            // reset values
            TFileVersionInfo.FManualApplicationVersion = ServerVersion;
        }
        /// <summary>
        /// runs all patches against the database;
        /// can send an email when the last patch has been applied (see RunDBPatch)
        /// </summary>
        public Boolean RunDBPatches()
        {
            Boolean          ReturnValue = false;
            TFileVersionInfo dbVersion;
            TFileVersionInfo appVersion;
            TFileVersionInfo desiredVersion;
            Boolean          lastPatch;

            DBAccess.GDBAccessObj = new TDataBase();
            DBAccess.GDBAccessObj.EstablishDBConnection(CommonTypes.ParseDBType(TAppSettingsManager.GetValue("Server.RDBMSType")),
                                                        TAppSettingsManager.GetValue("Server.DBHostOrFile"),
                                                        TAppSettingsManager.GetValue("Server.DBPort"),
                                                        TAppSettingsManager.GetValue("Server.DBName"),
                                                        TAppSettingsManager.GetValue("Server.DBUserName"),
                                                        TAppSettingsManager.GetValue("Server.DBPassword"),
                                                        "");

            dbVersion = GetDBPatchLevel();
            dbVersion.FilePrivatePart = 0;
            TLogging.Log("Current version of the database is " + dbVersion.ToString());

            if (dbVersion != null)
            {
                ReturnValue = true;

                StreamReader sr = new StreamReader(FPatchesPath + Path.DirectorySeparatorChar + "version.txt");
                appVersion = new TFileVersionInfo(sr.ReadLine());
                appVersion.FilePrivatePart = 0;
                TLogging.Log("We want to update to version " + appVersion.ToString());
                sr.Close();

                if (dbVersion.Compare(appVersion) == 0)
                {
                    // rerun the last patch; perhaps the patch file itself was patched
                    ReturnValue = RunDBPatch(dbVersion, true);
                }

                for (Int32 Counter = dbVersion.FileBuildPart + 1; Counter <= appVersion.FileBuildPart; Counter += 1)
                {
                    if (ReturnValue)
                    {
                        desiredVersion = new TFileVersionInfo(dbVersion);
                        desiredVersion.FileBuildPart = (ushort)Counter;
                        lastPatch   = (Counter == appVersion.FileBuildPart);
                        ReturnValue = RunDBPatch(desiredVersion, lastPatch);
                    }
                }
            }

            return(ReturnValue);
        }
Beispiel #10
0
        /// <summary>
        /// would this patch file apply to the current installed version
        /// </summary>
        static public Boolean PatchApplies(TFileVersionInfo ACurrentVersion, string APatchZipFile)
        {
            StringCollection versions          = GetVersionsFromDiffZipName(APatchZipFile);
            TFileVersionInfo patchStartVersion = new TFileVersionInfo(versions[0]);

            // generic patch
            if (patchStartVersion.FilePrivatePart == 0)
            {
                TFileVersionInfo patchEndVersion = new TFileVersionInfo(versions[1]);
                return(patchEndVersion.Compare(ACurrentVersion) > 0);
            }

            return(patchStartVersion.Compare(ACurrentVersion) == 0);
        }
Beispiel #11
0
        /// <summary>
        /// set current database version
        /// </summary>
        private static bool SetCurrentDBVersion(TFileVersionInfo ANewVersion)
        {
            using (TDBTransaction transaction = DBAccess.GDBAccessObj.BeginTransaction())
            {
                string newVersionSql =
                    String.Format("UPDATE s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion';",
                                  ANewVersion.ToStringDotsHyphen());
                DBAccess.GDBAccessObj.ExecuteNonQuery(newVersionSql, transaction);

                DBAccess.GDBAccessObj.CommitTransaction();
            }

            return(true);
        }
Beispiel #12
0
        public string Login(string username, string password)
        {
            string     WelcomeMessage;
            bool       SystemEnabled;
            IPrincipal UserInfo;
            Int32      ClientID;

            eLoginEnum resultCode = LoginInternal(username, password, TFileVersionInfo.GetApplicationVersion().ToVersion(),
                                                  out ClientID, out WelcomeMessage, out SystemEnabled, out UserInfo);

            Dictionary <string, object> result = new Dictionary <string, object>();

            result.Add("resultcode", resultCode.ToString());
            return(JsonConvert.SerializeObject(result));
        }
Beispiel #13
0
        /// <summary>
        /// would this patch file apply to the current installed version
        /// </summary>
        /// <param name="APatchZipFile"></param>
        /// <param name="AMaxVersion">maximum version to upgrade to, usually this is the version of the exe files</param>
        /// <returns></returns>
        public Boolean PatchApplies(String APatchZipFile, TFileVersionInfo AMaxVersion)
        {
            try
            {
                StringCollection versions          = GetVersionsFromDiffZipName(APatchZipFile);
                TFileVersionInfo patchStartVersion = new TFileVersionInfo(versions[0]);
                TFileVersionInfo patchEndVersion   = new TFileVersionInfo(versions[1]);

                return(patchStartVersion.Compare(this) == 0 && patchEndVersion.Compare(AMaxVersion) <= 0);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #14
0
        /// <summary>
        /// set current database version
        /// </summary>
        private static bool SetCurrentDBVersion(TFileVersionInfo ANewVersion, TDataBase ADataBase)
        {
            TDBTransaction transaction = new TDBTransaction();
            bool           SubmitOK    = true;

            ADataBase.WriteTransaction(ref transaction, ref SubmitOK,
                                       delegate
            {
                string newVersionSql =
                    String.Format("UPDATE s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion';",
                                  ANewVersion.ToStringDotsHyphen());
                ADataBase.ExecuteNonQuery(newVersionSql, transaction);
            });

            return(true);
        }
Beispiel #15
0
        public string Login(string username, string password)
        {
            string WelcomeMessage;
            bool   SystemEnabled;
            Int32  ClientID;
            bool   MustChangePassword;

            eLoginEnum resultCode = LoginInternal(username, password, TFileVersionInfo.GetApplicationVersion().ToVersion(),
                                                  out ClientID, out WelcomeMessage, out SystemEnabled, out MustChangePassword);

            Dictionary <string, object> result = new Dictionary <string, object>();

            result.Add("resultcode", resultCode.ToString());
            result.Add("mustchangepassword", MustChangePassword);

            if (resultCode == eLoginEnum.eLoginSucceeded)
            {
                result.Add("ModulePermissions", UserInfo.GetUserInfo().GetPermissions());
            }

            return(JsonConvert.SerializeObject(result));
        }
Beispiel #16
0
        /// <summary>
        /// todoComment
        /// </summary>
        public static void InitializeUnit()
        {
            Networking.DetermineNetworkConfig(out UClientComputerName, out UClientIPAddress);
            UClientOS = Utilities.DetermineExecutingOS();
            UClientAssemblyVersion = TFileVersionInfo.GetApplicationVersion().ToString();

            if (TClientSettings.RunAsRemote)
            {
                UInstallationKind = "Remote Client";
            }
            else
            {
                if (TClientSettings.RunAsStandalone)
                {
                    UInstallationKind = "Standalone Installation";
                }
                else
                {
                    UInstallationKind = "Network Client";
                }
            }
        }
        public static bool LoginServerAdmin()
        {
            // create a new session, with database connection and everything that is needed
            // see also Ict.Petra.Server.App.WebService.TOpenPetraOrgSessionManager.Login()
            if (DBAccess.GDBAccessObj == null)
            {
                TServerManager.TheCastedServerManager.EstablishDBConnection();
            }

            string     WelcomeMessage;
            bool       SystemEnabled;
            IPrincipal LocalUserInfo;
            Int32      ClientID;

            TConnectedClient CurrentClient = TClientManager.ConnectClient(
                "SYSADMIN", string.Empty,
                HttpContext.Current.Request.UserHostName,
                HttpContext.Current.Request.UserHostAddress,
                TFileVersionInfo.GetApplicationVersion().ToVersion(),
                TClientServerConnectionType.csctRemote,
                out ClientID,
                out WelcomeMessage,
                out SystemEnabled,
                out LocalUserInfo);

            TSession.SetVariable("LoggedIn", true);

            // the following values are stored in the session object
            DomainManager.GClientID     = ClientID;
            DomainManager.CurrentClient = CurrentClient;
            UserInfo.GUserInfo          = (TPetraPrincipal)LocalUserInfo;

            DBAccess.GDBAccessObj.UserID = "SYSADMIN";

            TServerManager.TheCastedServerManager.AddDBConnection(DBAccess.GDBAccessObj);

            return(true);
        }
Beispiel #18
0
        public static bool ResetDatabase(string AZippedNewDatabaseData)
        {
            List <string>  tables           = TTableList.GetDBNames();
            bool           SubmissionResult = false;
            TDBTransaction Transaction      = null;

            string ClientID = "ClientID";

            try
            {
                ClientID = DomainManager.GClientID.ToString();
            }
            catch (Exception)
            {
            }

            TProgressTracker.InitProgressTracker(ClientID,
                                                 Catalog.GetString("Restoring Database..."),
                                                 tables.Count + 3);

            DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref Transaction,
                                                       ref SubmissionResult,
                                                       delegate
            {
                try
                {
                    tables.Reverse();

                    TProgressTracker.SetCurrentState(ClientID,
                                                     Catalog.GetString("Deleting current data..."),
                                                     0);

                    foreach (string table in tables)
                    {
                        DBAccess.GDBAccessObj.ExecuteNonQuery("DELETE FROM pub_" + table, Transaction);
                    }

                    if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(ClientID);

                        // As SubmissionResult is still false, a DB Transaction Rollback will get
                        // executed automatically and the Method will be exited with return value 'false'!
                        return;
                    }

                    TSimpleYmlParser ymlParser = new TSimpleYmlParser(PackTools.UnzipString(AZippedNewDatabaseData));

                    ymlParser.ParseCaptions();

                    tables.Reverse();

                    TProgressTracker.SetCurrentState(ClientID,
                                                     Catalog.GetString("Loading initial tables..."),
                                                     1);

                    // one transaction to import the user table and user permissions. otherwise logging in will not be possible if other import fails?
                    bool success = true;
                    success      = success && LoadTable("s_user", ymlParser, Transaction);
                    success      = success && LoadTable("s_module", ymlParser, Transaction);
                    success      = success && LoadTable("s_user_module_access_permission", ymlParser, Transaction);
                    success      = success && LoadTable("s_system_defaults", ymlParser, Transaction);
                    success      = success && LoadTable("s_system_status", ymlParser, Transaction);

                    // make sure we have the correct database version
                    TFileVersionInfo serverExeInfo = new TFileVersionInfo(TSrvSetting.ApplicationVersion);
                    DBAccess.GDBAccessObj.ExecuteNonQuery(String.Format(
                                                              "UPDATE PUB_s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion'",
                                                              serverExeInfo.ToString()), Transaction);

                    if (!success)
                    {
                        // As SubmissionResult is still TSubmitChangesResult.scrError, a DB Transaction Rollback will get
                        // executed automatically and the Method will be exited with return value 'false'!
                        return;
                    }

                    if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(ClientID);

                        // As SubmissionResult is still false, a DB Transaction Rollback will get
                        // executed automatically and the Method will be exited with return value 'false'!
                        return;
                    }

                    tables.Remove("s_user");
                    tables.Remove("s_module");
                    tables.Remove("s_user_module_access_permission");
                    tables.Remove("s_system_defaults");
                    tables.Remove("s_system_status");

                    FCurrencyPerLedger = new SortedList <int, string>();

                    int tableCounter = 2;

                    foreach (string table in tables)
                    {
                        TProgressTracker.SetCurrentState(ClientID,
                                                         String.Format(Catalog.GetString("Loading Table {0}..."), table),
                                                         tableCounter);

                        tableCounter++;

                        if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true)
                        {
                            TProgressTracker.FinishJob(ClientID);

                            // As SubmissionResult is still false, a DB Transaction Rollback will get
                            // executed automatically and the Method will be exited with return value 'false'!
                            return;
                        }

                        LoadTable(table, ymlParser, Transaction);
                    }

                    TProgressTracker.SetCurrentState(ClientID,
                                                     Catalog.GetString("Loading Sequences..."),
                                                     tables.Count + 5 + 3);

                    // set sequences appropriately, not lagging behind the imported data
                    foreach (string seq in TTableList.GetDBSequenceNames())
                    {
                        LoadSequence(seq, ymlParser, Transaction);
                    }

                    TProgressTracker.SetCurrentState(ClientID,
                                                     Catalog.GetString("Finishing Restore..."),
                                                     tables.Count + 5 + 4);

                    SubmissionResult = true;

                    // reset all cached tables
                    TCacheableTablesManager.GCacheableTablesManager.MarkAllCachedTableNeedsRefreshing();

                    TProgressTracker.FinishJob(ClientID);
                }
                catch (Exception e)
                {
                    TLogging.Log("Problem in ResetDatabase: " + e.ToString());
                    TLogging.LogStackTrace(TLoggingType.ToLogfile);

                    throw;
                }
            });

            return(SubmissionResult);
        }
Beispiel #19
0
        /// <summary>
        /// check whether there is a patch available; if this is a remote version, try to download a patch from the server this will also get the version of the currently installed code, and the list of patches that can be installed, in local
        /// variables
        /// </summary>
        /// <param name="AShowStatus">Set to true to show status messages as a MessageBox
        /// if there is a problem, or to false to have them returned in
        /// <paramref name="AStatusMessage" /></param>.
        /// <param name="AStatusMessage">A Status Message in case there is a problem AND
        /// <paramref name="AShowStatus" /> is false.</param>
        public Boolean CheckForRecentPatch(bool AShowStatus, out string AStatusMessage)
        {
            string           localname;
            TFileVersionInfo fileStartVersion;
            TFileVersionInfo filePatchVersion;
            string           directoryListing;
            string           searchPattern;
            string           filesignature;

            AStatusMessage    = "";
            FListOfNewPatches = new SortedList();

            // first get the version of the currently installed binaries
            // read from version.txt in the bin directory; it contains the currently installed version in RPM style (e.g. 3.0.0-14)
            if (!File.Exists(FBinPath + Path.DirectorySeparatorChar + "version.txt"))
            {
                throw new Exception(String.Format("Cannot search for new patch, since I cannot find file {0}", FBinPath +
                                                  Path.DirectorySeparatorChar + "version.txt"));
            }

            StreamReader srVersion = new StreamReader(FBinPath + Path.DirectorySeparatorChar + "version.txt");

            FCurrentlyInstalledVersion = new TFileVersionInfo(srVersion.ReadLine());
            srVersion.Close();

            if (FRemotePatchesPath.StartsWith("http://") || FRemotePatchesPath.StartsWith("https://"))
            {
                directoryListing = THTTPUtils.ReadWebsite(FRemotePatchesPath);

                if (directoryListing == null)
                {
                    if (AShowStatus)
                    {
                        MessageBox.Show(String.Format(StrProblemConnecting, FRemotePatchesPath),
                                        StrProblemConnectingTitle);
                    }
                    else
                    {
                        AStatusMessage = String.Format(StrProblemConnecting, FRemotePatchesPath);
                    }

                    return(false);
                }

                // find all the files names that match the pattern
                // eg <a href="Patch2.2.7-2_2.2.8-0.zip">
                searchPattern = "<a href=\"";

                while (directoryListing.IndexOf(searchPattern) != -1)
                {
                    string filename = directoryListing.Substring(
                        directoryListing.IndexOf(searchPattern) + searchPattern.Length,
                        directoryListing.Substring(
                            directoryListing.IndexOf(searchPattern) + searchPattern.Length).IndexOf('"'));
                    directoryListing = directoryListing.Substring(directoryListing.IndexOf(searchPattern) + searchPattern.Length);

                    // signature e.g: gr1100o.r">gr1100o.r</a>                    14-Oct-2008 13:11  153K
                    filesignature = directoryListing.Substring(0, directoryListing.IndexOf("\n"));

                    if (filename.ToLower().StartsWith("patch") && filename.ToLower().EndsWith(".zip"))
                    {
                        filePatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(filename);

                        if ((filePatchVersion.Compare(FCurrentlyInstalledVersion) > 0) &&
                            (!System.IO.File.Exists(FPatchesPath + Path.DirectorySeparatorChar + Path.GetFileName(filename))))
                        {
                            string LocalName = FPatchesPath + Path.DirectorySeparatorChar + Path.GetFileName(filename);
                            FListOfNewPatches.Add(LocalName, LocalName);
                        }
                    }
                    else if (filename.Contains("Setup") && filename.EndsWith(".exe"))
                    {
                        // ignore setup executable
                    }
                    else if (filename.ToLower().EndsWith(".dll") ||
                             filename.ToLower().EndsWith(".exe"))
                    {
                        // download .dll/.exe files from the netpatches directory if there is no file with same date already
                        if (System.IO.File.Exists(FPatchesPath + Path.DirectorySeparatorChar + filename + ".signature"))
                        {
                            StreamReader sr = new StreamReader(FPatchesPath + Path.DirectorySeparatorChar + filename + ".signature");

                            if (sr.ReadLine().Trim() == filesignature.Trim())
                            {
                                if (System.IO.File.Exists(FPatchesPath + Path.DirectorySeparatorChar + filename + ".old") &&
                                    !System.IO.File.Exists(FPatchesPath + Path.DirectorySeparatorChar + filename))
                                {
                                    // the file has been renamed by the patch, and needs to be reinstated
                                    System.IO.File.Move(FPatchesPath + Path.DirectorySeparatorChar + filename + ".old",
                                                        FPatchesPath + Path.DirectorySeparatorChar + filename);
                                }

                                filename = "ALREADY_LATEST";
                            }

                            sr.Close();
                        }

                        if (filename != "ALREADY_LATEST")
                        {
                            string localFile = FPatchesPath + Path.DirectorySeparatorChar + filename;

                            if (filename.ToLower().EndsWith(".dll") ||
                                filename.ToLower().EndsWith(".exe"))
                            {
                                localFile = FBinPath + Path.DirectorySeparatorChar + filename;

                                // make backup copy of .dll/.exe if there does not already one exist; don't overwrite .orig files
                                if (!File.Exists(localFile + ".orig"))
                                {
                                    System.IO.File.Move(localFile, localFile + ".orig");
                                }
                            }

                            THTTPUtils.DownloadFile(FRemotePatchesPath + "/" + filename, localFile);
                            StreamWriter sw = new StreamWriter(FPatchesPath + Path.DirectorySeparatorChar + filename + ".signature");
                            sw.WriteLine(filesignature);
                            sw.Close();
                        }
                    }
                }

                // todo: remove local .r files if they are not in the net-patches directory
                // todo: the same for *.dll and *.exe; careful: only create an .orig copy once.
                // todo: somehow revert to .orig dll/exe file if there is no patched file in net-patches on the server?
                // todo: patch has to remove dll and exe from net-patches
                // todo: on the server side as well; check net-patches
            }
            else if ((FRemotePatchesPath.Length > 0) && (System.IO.Directory.Exists(FRemotePatchesPath)))
            {
                // check if there are newer patches on the remote server
                string[] files = System.IO.Directory.GetFiles(FRemotePatchesPath, "Patch*.zip");

                foreach (string filename in files)
                {
                    filePatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(filename);

                    if ((filePatchVersion.Compare(FCurrentlyInstalledVersion) > 0) &&
                        ((!System.IO.File.Exists(FPatchesPath + Path.DirectorySeparatorChar + Path.GetFileName(filename)))))
                    {
                        localname = FPatchesPath + Path.DirectorySeparatorChar + Path.GetFileName(filename);
                        FListOfNewPatches.Add(localname, localname);
                    }
                }
            }

            // create a list of patches that should be installed
            string[] patchfiles = System.IO.Directory.GetFiles(FPatchesPath, "Patch*.zip");

            foreach (string filename in patchfiles)
            {
                fileStartVersion = TPatchFileVersionInfo.GetStartVersionFromDiffZipName(filename);
                filePatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(filename);

                if ((fileStartVersion.Compare(FCurrentlyInstalledVersion) >= 0) &&
                    (filePatchVersion.Compare(FCurrentlyInstalledVersion) > 0))
                {
                    FListOfNewPatches.Add(filename, filename);
                }
            }

            // see if any patches are missing; is there a direct line between FCurrentlyInstalledVersion and FLatestAvailablePatch?
            FListOfNewPatches = CheckPatchesConsistent(FListOfNewPatches);
            return(FListOfNewPatches.Count > 0);
        }
Beispiel #20
0
 /// Updating of a Postgresql database has not been implemented yet, need to do this still manually
 public void UpdateDatabase(TFileVersionInfo ADBVersion, TFileVersionInfo AExeVersion,
                            string AHostOrFile, string ADatabasePort, string ADatabaseName, string AUsername, string APassword)
 {
     throw new EDBUnsupportedDBUpgradeException(
               "Cannot connect to old database, please restore the latest clean demo database or run nant patchDatabase");
 }
Beispiel #21
0
        /// <summary>
        /// see if any patches are missing; is there a direct line between FCurrentlyInstalledVersion and FLatestAvailablePatch?
        /// </summary>
        /// <returns>return a list of all patches that should be applied. empty list if there is a problem</returns>
        public SortedList CheckPatchesConsistent(SortedList AOrderedListOfAllPatches)
        {
            SortedList       ResultPatchList = new SortedList();
            TFileVersionInfo testPatchVersion;

            // get the latest patch that is available
            FLatestAvailablePatch = new TFileVersionInfo(FCurrentlyInstalledVersion);

            foreach (string patch in AOrderedListOfAllPatches.GetValueList())
            {
                testPatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(patch);

                if (testPatchVersion.Compare(FLatestAvailablePatch) > 0)
                {
                    FLatestAvailablePatch = testPatchVersion;
                }
            }

            // drop unnecessary patch files
            // ie. patch files leading to the same version, eg. 2.2.11-1 and 2.2.12-2 to 2.2.12-3
            // we only want the biggest step
            testPatchVersion = new TFileVersionInfo(FCurrentlyInstalledVersion);
            bool patchesAvailable = true;

            while (patchesAvailable)
            {
                StringCollection applyingPatches = new StringCollection();

                foreach (string patch in AOrderedListOfAllPatches.GetValueList())
                {
                    if (TPatchFileVersionInfo.PatchApplies(testPatchVersion, patch))
                    {
                        applyingPatches.Add(patch);
                    }
                }

                patchesAvailable = (applyingPatches.Count > 0);

                if (applyingPatches.Count > 0)
                {
                    // see which of the applying patches takes us further
                    string           highestPatch        = applyingPatches[0];
                    TFileVersionInfo highestPatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(highestPatch);

                    foreach (string patch in applyingPatches)
                    {
                        if (TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(patch).Compare(highestPatchVersion) > 0)
                        {
                            highestPatch        = patch;
                            highestPatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(highestPatch);
                        }
                    }

                    ResultPatchList.Add(highestPatch, highestPatch);
                    testPatchVersion = highestPatchVersion;
                }
            }

            if (FLatestAvailablePatch.Compare(testPatchVersion) != 0)
            {
                // check for a generic patch file, starting from version 0.0.99.99
                foreach (string patch in AOrderedListOfAllPatches.GetValueList())
                {
                    if (patch.Contains("0.0.99.99"))
                    {
                        testPatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(patch);
                        ResultPatchList.Clear();
                        ResultPatchList.Add(patch, patch);
                    }
                }
            }

            if (FLatestAvailablePatch.Compare(testPatchVersion) != 0)
            {
                TLogging.Log("missing patchfile from version " + testPatchVersion.ToString() + " to " + FLatestAvailablePatch.ToString());
                return(new SortedList());
            }

            return(ResultPatchList);
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            new TLogging("../../log/TestRemotingClient.log");

            try
            {
                new TAppSettingsManager("../../etc/Client.config");

                TLogging.DebugLevel = Convert.ToInt32(TAppSettingsManager.GetValue("Client.DebugLevel", "0"));

                new TClientSettings();

                // initialize the client
                new TRemoteTest();

                // need to call this as well to make the progress dialog work
                new TRemote();

                // allow self signed ssl certificate for test purposes
                ServicePointManager.ServerCertificateValidationCallback = delegate {
                    return(true);
                };

                THttpConnector.InitConnection(TAppSettingsManager.GetValue("OpenPetra.HTTPServer"));

                TClientInfo.InitializeUnit();

                Catalog.Init("en-GB", "en-GB");

                SortedList <string, object> Parameters = new SortedList <string, object>();
                Parameters.Add("username", "demo");
                Parameters.Add("password", "demo");
                Parameters.Add("version", TFileVersionInfo.GetApplicationVersion().ToString());

                List <object> ResultList = THttpConnector.CallWebConnector("SessionManager", "LoginClient", Parameters, "list");
                eLoginEnum    Result     = (eLoginEnum)ResultList[0];

                if (Result != eLoginEnum.eLoginSucceeded)
                {
                    // failed login
                    return;
                }

                IMyUIConnector MyUIConnector = TRemoteTest.MyService.SubNamespace.MyUIConnector();
                TRemoteTest.TMyService.TMySubNamespace test = TRemoteTest.MyService.SubNamespace;

                while (true)
                {
                    try
                    {
                        TLogging.Log("before call");
                        TLogging.Log(TRemoteTest.MyService.HelloWorld("Hello World"));
                        TLogging.Log("after call");
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("problem with MyService HelloWorld: " + Environment.NewLine + e.ToString());
                    }

                    try
                    {
                        DateTime DateTomorrow;
                        TLogging.Log("should show today's date: " + TRemoteTest.MyService.TestDateTime(DateTime.Today,
                                                                                                       out DateTomorrow).ToShortDateString());
                        TLogging.Log("should show tomorrow's date: " + DateTomorrow.ToShortDateString());
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("problem with TestDateTime: " + Environment.NewLine + e.ToString());
                    }

                    try
                    {
                        TLogging.Log(test.HelloSubWorld("Hello SubWorld"));
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("problem with sub namespace HelloSubWorld: " + Environment.NewLine + e.ToString());
                    }

                    try
                    {
                        TLogging.Log(MyUIConnector.HelloWorldUIConnector());
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("problem with HelloWorldUIConnector: " + Environment.NewLine + e.ToString());
                    }

                    // start long running job
                    Thread t = new Thread(() => TRemoteTest.MyService.LongRunningJob());

                    using (TProgressDialog dialog = new TProgressDialog(t))
                    {
                        if (dialog.ShowDialog() == DialogResult.Cancel)
                        {
                            return;
                        }
                    }

                    Console.WriteLine("Press ENTER to say Hello World again... ");
                    Console.WriteLine("Press CTRL-C to exit ...");
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                Console.ReadLine();
            }
        }
Beispiel #23
0
        /// <summary>
        /// For standalone installations, we update the SQLite database on the fly.
        /// </summary>
        public void UpdateDatabase(TFileVersionInfo ADBVersion, TFileVersionInfo AExeVersion,
                                   string AHostOrFile, string ADatabasePort, string ADatabaseName, string AUsername, string APassword)
        {
            // we do not support updating standalone databases at the moment
            if (AExeVersion.FileMajorPart == 0)
            {
                DBAccess.GDBAccessObj.CloseDBConnection();

                throw new EDBUnsupportedDBUpgradeException(String.Format(Catalog.GetString(
                                                                             "Unsupported upgrade: Please rename the file {0} so that we can start with a fresh database!   " +
                                                                             "Please restart the OpenPetra Client after that."),
                                                                         AHostOrFile));
            }

            string dbpatchfilePath = Path.GetDirectoryName(TAppSettingsManager.GetValue("Server.SQLiteBaseFile"));

            ADBVersion.FilePrivatePart  = 0;
            AExeVersion.FilePrivatePart = 0;

            using (TDBTransaction transaction = DBAccess.GDBAccessObj.BeginTransaction())
            {
                try
                {
                    // run all available patches. for each release there could be a patch file
                    string[] sqlFiles = Directory.GetFiles(dbpatchfilePath, "*.sql");

                    bool foundUpdate = true;

                    // run through all sql files until we have no matching update files anymore
                    while (foundUpdate)
                    {
                        foundUpdate = false;

                        foreach (string sqlFile in sqlFiles)
                        {
                            if (!sqlFile.EndsWith("pg.sql") && (new TPatchFileVersionInfo(ADBVersion)).PatchApplies(sqlFile, AExeVersion))
                            {
                                foundUpdate = true;
                                StreamReader sr = new StreamReader(sqlFile);

                                while (!sr.EndOfStream)
                                {
                                    string line = sr.ReadLine().Trim();

                                    if (!line.StartsWith("--"))
                                    {
                                        DBAccess.GDBAccessObj.ExecuteNonQuery(line, transaction);
                                    }
                                }

                                sr.Close();
                                ADBVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(sqlFile);
                            }
                        }
                    }

                    if (ADBVersion.Compare(AExeVersion) == 0)
                    {
                        // if patches have been applied successfully, update the database version
                        string newVersionSql =
                            String.Format("UPDATE s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion';",
                                          AExeVersion.ToStringDotsHyphen());

                        DBAccess.GDBAccessObj.ExecuteNonQuery(newVersionSql, transaction);

                        DBAccess.GDBAccessObj.CommitTransaction();
                    }
                    else
                    {
                        DBAccess.GDBAccessObj.RollbackTransaction();

                        throw new Exception(String.Format(Catalog.GetString(
                                                              "Cannot connect to old database (version {0}), there are some missing sql patch files"),
                                                          ADBVersion));
                    }
                }
                catch (Exception)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();

                    throw;
                }
            }
        }
Beispiel #24
0
        /// <summary>
        /// Initialises the internal variables that hold the Server Settings, using the current config file.
        ///
        /// </summary>
        /// <returns>void</returns>
        public TSrvSetting()
        {
            if (USingletonSrvSetting == null)
            {
                USingletonSrvSetting = this;
            }

            FConfigurationFile = TAppSettingsManager.ConfigFileName;
            FExecutingOS       = Utilities.DetermineExecutingOS();

            // Server.RDBMSType
            FRDBMSType = CommonTypes.ParseDBType(TAppSettingsManager.GetValue("Server.RDBMSType", "postgresql"));

            FDatabaseHostOrFile = TAppSettingsManager.GetValue("Server.DBHostOrFile", "localhost");
            FDatabasePort       = TAppSettingsManager.GetValue("Server.DBPort", "5432");
            FDatabaseName       = TAppSettingsManager.GetValue("Server.DBName", "openpetra");
            FDBUsername         = TAppSettingsManager.GetValue("Server.DBUserName", "petraserver");
            FDBPassword         = TAppSettingsManager.GetValue("Server.DBPassword", string.Empty, false);

            if (FDBPassword == "PG_OPENPETRA_DBPWD")
            {
                // get the password from the file ~/.pgpass. This currently only works for PostgreSQL on Linux
                using (StreamReader sr = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.Personal) +
                                                          Path.DirectorySeparatorChar + ".pgpass"))
                {
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();

                        if (line.StartsWith(FDatabaseHostOrFile + ":" + FDatabasePort + ":" + FDatabaseName + ":" + FDBUsername + ":") ||
                            line.StartsWith("*:" + FDatabasePort + ":" + FDatabaseName + ":" + FDBUsername + ":"))
                        {
                            FDBPassword = line.Substring(line.LastIndexOf(':') + 1);
                            break;
                        }
                    }
                }
            }

            if (TAppSettingsManager.HasValue("Server.LogFile"))
            {
                FServerLogFile = TAppSettingsManager.GetValue("Server.LogFile", false);
            }
            else
            {
                // maybe the log file has already been set, eg. by the NUnit Server Test
                FServerLogFile = TLogging.GetLogFileName();

                if (FServerLogFile.Length == 0)
                {
                    // this is effectively the bin directory (current directory)
                    FServerLogFile = "Server.log";
                }
            }

            // Server.Port
            FIPBasePort = TAppSettingsManager.GetInt16("Server.Port", 9000);

            FRunAsStandalone = TAppSettingsManager.GetBoolean("Server.RunAsStandalone", false);

            // Server.ClientIdleStatusAfterXMinutes
            FClientIdleStatusAfterXMinutes = TAppSettingsManager.GetInt32("Server.ClientIdleStatusAfterXMinutes", 5);

            // Server.ClientKeepAliveCheckIntervalInSeconds
            FClientKeepAliveCheckIntervalInSeconds = TAppSettingsManager.GetInt32("Server.ClientKeepAliveCheckIntervalInSeconds", 60);

            // Server.ClientKeepAliveTimeoutAfterXSeconds_LAN
            FClientKeepAliveTimeoutAfterXSecondsLAN = TAppSettingsManager.GetInt32("Server.ClientKeepAliveTimeoutAfterXSeconds_LAN", 60);

            // Server.ClientKeepAliveTimeoutAfterXSeconds_Remote
            FClientKeepAliveTimeoutAfterXSecondsRemote =
                TAppSettingsManager.GetInt32("Server.ClientKeepAliveTimeoutAfterXSeconds_Remote", (ClientKeepAliveTimeoutAfterXSecondsLAN * 2));

            // Server.ClientConnectionTimeoutAfterXSeconds
            FClientConnectionTimeoutAfterXSeconds = TAppSettingsManager.GetInt32("Server.ClientConnectionTimeoutAfterXSeconds", 20);

            // Server.ClientAppDomainShutdownAfterKeepAliveTimeout
            FClientAppDomainShutdownAfterKeepAliveTimeout = TAppSettingsManager.GetBoolean("Server.ClientAppDomainShutdownAfterKeepAliveTimeout",
                                                                                           true);

            FSMTPServer = TAppSettingsManager.GetValue("Server.SMTPServer", "localhost");

            // This is disabled in processing at the moment, so we reflect that here. When it works change to true
            FAutomaticIntranetExportEnabled = TAppSettingsManager.GetBoolean("Server.AutomaticIntranetExportEnabled", false);

            // The following setting specifies the email address where the Intranet Data emails are sent to when "Server.AutomaticIntranetExportEnabled" is true.
            FIntranetDataDestinationEmail = TAppSettingsManager.GetValue("Server.IntranetDataDestinationEmail", "???@???.org");

            // The following setting is temporary - until we have created a GUI where users can specify the email address for the
            // responsible Personnel and Finance persons themselves. Those will be stored in SystemDefaults then.
            FIntranetDataSenderEmail = TAppSettingsManager.GetValue("Server.IntranetDataSenderEmail", "???@???.org");

            // Determine network configuration of the Server
            Networking.DetermineNetworkConfig(out FHostName, out FHostIPAddresses);

            FApplicationVersion = TFileVersionInfo.GetApplicationVersion();
        }
Beispiel #25
0
        public static bool ResetDatabase(string AZippedNewDatabaseData)
        {
            List <string> tables = TTableList.GetDBNames();

            TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("Importing database"),
                                                 tables.Count + 3);

            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                tables.Reverse();

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("deleting current data"),
                                                 0);

                foreach (string table in tables)
                {
                    DBAccess.GDBAccessObj.ExecuteNonQuery("DELETE FROM pub_" + table, Transaction);
                }

                if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                {
                    TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    return(false);
                }

                TSimpleYmlParser ymlParser = new TSimpleYmlParser(PackTools.UnzipString(AZippedNewDatabaseData));

                ymlParser.ParseCaptions();

                tables.Reverse();

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("loading initial tables"),
                                                 1);

                // one transaction to import the user table and user permissions. otherwise logging in will not be possible if other import fails?
                bool success = true;
                success = success && LoadTable("s_user", ymlParser, Transaction);
                success = success && LoadTable("s_module", ymlParser, Transaction);
                success = success && LoadTable("s_user_module_access_permission", ymlParser, Transaction);
                success = success && LoadTable("s_system_defaults", ymlParser, Transaction);
                success = success && LoadTable("s_system_status", ymlParser, Transaction);

                // make sure we have the correct database version
                TFileVersionInfo serverExeInfo = new TFileVersionInfo(TSrvSetting.ApplicationVersion);
                DBAccess.GDBAccessObj.ExecuteNonQuery(String.Format(
                                                          "UPDATE PUB_s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion'",
                                                          serverExeInfo.ToString()), Transaction);

                if (!success)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    return(false);
                }

                if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                {
                    TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    return(false);
                }

                DBAccess.GDBAccessObj.CommitTransaction();

                tables.Remove("s_user");
                tables.Remove("s_module");
                tables.Remove("s_user_module_access_permission");
                tables.Remove("s_system_defaults");
                tables.Remove("s_system_status");

                FCurrencyPerLedger = new SortedList <int, string>();

                Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

                int tableCounter = 2;

                foreach (string table in tables)
                {
                    TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                     String.Format(Catalog.GetString("loading table {0}"), table),
                                                     tableCounter);

                    tableCounter++;

                    if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true)
                    {
                        TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
                        DBAccess.GDBAccessObj.RollbackTransaction();
                        return(false);
                    }

                    LoadTable(table, ymlParser, Transaction);
                }

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("loading sequences"),
                                                 tables.Count + 5 + 3);

                // set sequences appropriately, not lagging behind the imported data
                foreach (string seq in TTableList.GetDBSequenceNames())
                {
                    LoadSequence(seq, ymlParser, Transaction);
                }

                TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                                 Catalog.GetString("finish import"),
                                                 tables.Count + 5 + 4);

                DBAccess.GDBAccessObj.CommitTransaction();

                // reset all cached tables
                TCacheableTablesManager.GCacheableTablesManager.MarkAllCachedTableNeedsRefreshing();

                TProgressTracker.FinishJob(DomainManager.GClientID.ToString());
            }
            catch (Exception e)
            {
                TLogging.Log("Problem in ResetDatabase: " + e.Message);
                TLogging.Log(e.StackTrace);
                DBAccess.GDBAccessObj.RollbackTransaction();
                return(false);
            }

            return(true);
        }
Beispiel #26
0
 /// <summary>
 /// constructor for base class
 /// </summary>
 /// <param name="version"></param>
 public TPatchFileVersionInfo(TFileVersionInfo version)
     : base(version)
 {
 }
Beispiel #27
0
        /// <summary>
        /// apply one single database patch.
        /// if this is the last patch, an email could be sent, etc
        /// </summary>
        /// <param name="ADesiredVersion"></param>
        /// <param name="ALastPatch"></param>
        /// <returns></returns>
        private Boolean RunDBPatch(TFileVersionInfo ADesiredVersion, Boolean ALastPatch)
        {
            TDBTransaction WriteTransaction = null;
            bool           SubmissionResult = false;

            // TODO: run sql script or code from DLL to update the database
            // TODO: if last patch, send an email to central support etc
            TLogging.Log("RunDBPatch " + ADesiredVersion.ToString());


            // find appropriate sql script that updates to this version
            string[] files = Directory.GetFiles(FPatchesPath,
                                                String.Format("*_{0}.{1}.{2}.sql",
                                                              ADesiredVersion.FileMajorPart,
                                                              ADesiredVersion.FileMinorPart,
                                                              ADesiredVersion.FileBuildPart));

            if (files.Length > 1)
            {
                throw new Exception("There are too many files for upgrading to version " + ADesiredVersion.ToString() + " in " + FPatchesPath);
            }

            if (files.Length == 0)
            {
                throw new Exception("We cannot find a file for upgrading to version " + ADesiredVersion.ToString() + " in " + FPatchesPath);
            }

            TLogging.Log("Applying " + Path.GetFileName(files[0]));

            DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref WriteTransaction,
                                                       ref SubmissionResult,
                                                       delegate
            {
                // always upgrade the version number
                DBAccess.GDBAccessObj.ExecuteNonQuery(
                    String.Format(
                        "UPDATE s_system_defaults SET s_default_value_c = '{0}.{1}.{2}-0' WHERE s_default_code_c='CurrentDatabaseVersion'",
                        ADesiredVersion.FileMajorPart,
                        ADesiredVersion.FileMinorPart,
                        ADesiredVersion.FileBuildPart), WriteTransaction);

                StreamReader reader = new StreamReader(files[0]);
                string line;
                string stmt = string.Empty;

                while ((line = reader.ReadLine()) != null)
                {
                    if (!line.Trim().StartsWith("--"))
                    {
                        if (!line.Trim().EndsWith(";"))
                        {
                            stmt += line.Trim() + " ";
                        }
                        else
                        {
                            stmt += line.Trim();
                            DBAccess.GDBAccessObj.ExecuteNonQuery(stmt, WriteTransaction);
                        }
                    }

                    if (stmt.Length > 0)
                    {
                        DBAccess.GDBAccessObj.ExecuteNonQuery(stmt, WriteTransaction);
                    }
                }

                SubmissionResult = true;
            });

            return(true);
        }
Beispiel #28
0
        /// <summary>
        /// Initialize the Petra server and connect to the database
        /// </summary>
        /// <param name="AConfigName">just provide the server config file, plus AutoLogin and AutoLoginPasswd</param>
        public static TServerManager Connect(string AConfigName)
        {
            TDBTransaction LoginTransaction;
            bool           CommitLoginTransaction = false;
            bool           SystemEnabled;
            string         WelcomeMessage;
            IPrincipal     ThisUserInfo;
            Int32          ClientID;

            if (File.Exists(AConfigName))
            {
                new TAppSettingsManager(AConfigName);
            }
            else if (AConfigName.Length > 0)
            {
                TLogging.Log("cannot find config file " + Path.GetFullPath(AConfigName));
                Environment.Exit(-1);
            }
            else
            {
                new TAppSettingsManager();
            }

            new TLogging(TAppSettingsManager.GetValue("Server.LogFile"));

            CommonNUnitFunctions.InitRootPath();

            Catalog.Init();
            TServerManager.TheServerManager = new TServerManager();

            DBAccess.GDBAccessObj = new TDataBase();
            DBAccess.GDBAccessObj.EstablishDBConnection(TSrvSetting.RDMBSType,
                                                        TSrvSetting.PostgreSQLServer, TSrvSetting.PostgreSQLServerPort,
                                                        TSrvSetting.PostgreSQLDatabaseName,
                                                        TSrvSetting.DBUsername, TSrvSetting.DBPassword, "",
                                                        "Ict.Testing.NUnitPetraServer.TPetraServerConnector.Connect DB Connection");

            LoginTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.RepeatableRead,
                                                                      ATransactionName: "Ict.Testing.NUnitPetraServer.TPetraServerConnector.Connect (Unit Test Login)");

            try
            {
                TClientManager.PerformLoginChecks(TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                                                  TAppSettingsManager.GetValue("AutoLoginPasswd"),
                                                  "NUNITTEST", "127.0.0.1", out SystemEnabled, LoginTransaction);

                CommitLoginTransaction = true;
            }
            catch (EPetraSecurityException)
            {
                // We need to set this flag to true here to get the failed login to be stored in the DB!!!
                CommitLoginTransaction = true;
            }
            finally
            {
                if (CommitLoginTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
                else
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }
            }

            TConnectedClient CurrentClient = TClientManager.ConnectClient(
                TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                TAppSettingsManager.GetValue("AutoLoginPasswd"),
                "NUNITTEST", "127.0.0.1",
                TFileVersionInfo.GetApplicationVersion().ToVersion(),
                TClientServerConnectionType.csctLocal,
                out ClientID,
                out WelcomeMessage,
                out SystemEnabled,
                out ThisUserInfo);

            // the following values are stored in the session object
            DomainManager.GClientID     = ClientID;
            DomainManager.CurrentClient = CurrentClient;
            UserInfo.GUserInfo          = (TPetraPrincipal)ThisUserInfo;

            TSetupDelegates.Init();
            TSystemDefaultsCache.GSystemDefaultsCache = new TSystemDefaultsCache();
            DomainManager.GetSiteKeyFromSystemDefaultsCacheDelegate =
                @TSystemDefaultsCache.GSystemDefaultsCache.GetSiteKeyDefault;

            TUserDefaults.InitializeUnit();

            StringHelper.CurrencyFormatTable = DBAccess.GDBAccessObj.SelectDT("SELECT * FROM PUB_a_currency", "a_currency", null);

            return((TServerManager)TServerManager.TheServerManager);
        }
Beispiel #29
0
        /// <summary>
        /// Initialize the Petra server and connect to the database
        /// </summary>
        /// <param name="AConfigName">just provide the server config file, plus AutoLogin and AutoLoginPasswd</param>
        public static TServerManager Connect(string AConfigName)
        {
            TDBTransaction LoginTransaction;
            bool           CommitLoginTransaction = false;
            bool           SystemEnabled;
            string         WelcomeMessage;
            Int32          ClientID;
            Int64          SiteKey;

            if (!File.Exists(AConfigName) && (AConfigName.Length > 0))
            {
                TLogging.Log("cannot find config file " + Path.GetFullPath(AConfigName));
                Environment.Exit(-1);
            }

            TSession.InitThread("NUnitPetraServer.TPetraServerConnector.Connect", AConfigName);

            CommonNUnitFunctions.InitRootPath();

            Catalog.Init();
            TServerManager.TheServerManager = new TServerManager();

            ErrorCodeInventory.Init();

            // initialise the cached tables and the delegates
            TSetupDelegates.Init();

            TDataBase db = DBAccess.Connect(
                "Ict.Testing.NUnitPetraServer.TPetraServerConnector.Connect DB Connection");

            // we need a serializable transaction, to store the session
            LoginTransaction = db.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                TClientManager.PerformLoginChecks(TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                                                  TAppSettingsManager.GetValue("AutoLoginPasswd"),
                                                  "NUNITTEST", "127.0.0.1", out SystemEnabled, LoginTransaction);

                CommitLoginTransaction = true;
            }
            catch (EPetraSecurityException)
            {
                // We need to set this flag to true here to get the failed login to be stored in the DB!!!
                CommitLoginTransaction = true;
            }
            finally
            {
                if (CommitLoginTransaction)
                {
                    LoginTransaction.Commit();
                }
                else
                {
                    LoginTransaction.Rollback();
                }
            }

            TConnectedClient CurrentClient = TClientManager.ConnectClient(
                TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                TAppSettingsManager.GetValue("AutoLoginPasswd"),
                "NUNITTEST", "127.0.0.1",
                TFileVersionInfo.GetApplicationVersion().ToVersion(),
                TClientServerConnectionType.csctLocal,
                out ClientID,
                out WelcomeMessage,
                out SystemEnabled,
                out SiteKey,
                db);

            // the following values are stored in the session object
            DomainManager.GClientID     = ClientID;
            DomainManager.CurrentClient = CurrentClient;
            DomainManager.GSiteKey      = SiteKey;

            TSetupDelegates.Init();

            db.CloseDBConnection();

            return((TServerManager)TServerManager.TheServerManager);
        }
Beispiel #30
0
 /// Updating of a MySQL database has not been implemented yet, need to do this still manually
 public void UpdateDatabase(TFileVersionInfo ADBVersion, TFileVersionInfo AExeVersion,
     string AHostOrFile, string ADatabasePort, string ADatabaseName, string AUsername, string APassword)
 {
     throw new EDBUnsupportedDBUpgradeException(
         "Cannot connect to old database, please restore the latest clean demo database or run nant patchDatabase");
 }