/// <summary> /// compare two file versions, while ignoring the private part /// </summary> /// <returns>-1 if this < ACmp, 1 if this > ACmp, and 0 if equals</returns> public Int16 CompareWithoutPrivatePart(TFileVersionInfo ACmp) { Int16 ReturnValue; if (FileMajorPart > ACmp.FileMajorPart) { ReturnValue = 1; } else if (FileMajorPart < ACmp.FileMajorPart) { ReturnValue = -1; } else if (FileMinorPart > ACmp.FileMinorPart) { ReturnValue = 1; } else if (FileMinorPart < ACmp.FileMinorPart) { ReturnValue = -1; } else if (FileBuildPart > ACmp.FileBuildPart) { ReturnValue = 1; } else if (FileBuildPart < ACmp.FileBuildPart) { ReturnValue = -1; } else { ReturnValue = 0; } return(ReturnValue); }
/// <summary> /// get the version of the current application. /// Parse version.txt in the same directory if that file exists. /// Otherwise use the version of the exe or dll file /// </summary> /// <returns></returns> public static TFileVersionInfo GetApplicationVersion() { TFileVersionInfo Result = new TFileVersionInfo(); // retrieve the current version of the server from the file version.txt in the bin directory // this is easier to manage than to check the assembly version in case you only need to quickly update the client string BinPath = TAppSettingsManager.ApplicationDirectory; if (File.Exists(BinPath + Path.DirectorySeparatorChar + "version.txt")) { StreamReader srVersion = new StreamReader(BinPath + Path.DirectorySeparatorChar + "version.txt"); Result = new TFileVersionInfo(srVersion.ReadLine()); srVersion.Close(); } else if ((System.Reflection.Assembly.GetEntryAssembly() != null) && (System.Reflection.Assembly.GetEntryAssembly().GetName() != null)) { Result = new TFileVersionInfo(System.Reflection.Assembly.GetEntryAssembly().GetName().Version); } else { // this is with the web services, started with xsp.exe, or running from NUnit Result = new TFileVersionInfo(new Version(0, 0, 0, 0)); } return(Result); }
/// <summary> /// Initialises the internal variables that hold the Server Settings, using the current config file. /// /// </summary> /// <returns>void</returns> public TSrvSetting() { FConfigurationFile = TAppSettingsManager.ConfigFileName; FExecutingOS = Utilities.DetermineExecutingOS(); // Server.RDBMSType FRDBMSType = CommonTypes.ParseDBType(TAppSettingsManager.GetValue("Server.RDBMSType", "postgresql")); FApplicationBinFolder = TAppSettingsManager.GetValue("Server.ApplicationBinDirectory", string.Empty, false); 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", 80); // Determine network configuration of the Server Networking.DetermineNetworkConfig(out FHostName, out FHostIPAddresses); FApplicationVersion = TFileVersionInfo.GetApplicationVersion(); }
/// 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; FApplicationBinFolder = ACopyFrom.FApplicationBinFolder; }
/// <summary> /// copy constructor /// </summary> /// <param name="AInfo"></param> public TFileVersionInfo(TFileVersionInfo AInfo) { FileMajorPart = AInfo.FileMajorPart; FileMinorPart = AInfo.FileMinorPart; FileBuildPart = AInfo.FileBuildPart; FilePrivatePart = AInfo.FilePrivatePart; }
/// <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; }
/// 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; FDBConnectionCheckInterval = ACopyFrom.FDBConnectionCheckInterval; 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; FSmtpHost = ACopyFrom.FSmtpHost; FSmtpPort = ACopyFrom.FSmtpPort; FSmtpUser = ACopyFrom.FSmtpUser; FSmtpPassword = ACopyFrom.FSmtpPassword; FSmtpEnableSsl = ACopyFrom.FSmtpEnableSsl; FSmtpAuthenticationType = ACopyFrom.FSmtpAuthenticationType; FSmtpIgnoreServerCertificateValidation = ACopyFrom.FSmtpIgnoreServerCertificateValidation; FRunAsStandalone = ACopyFrom.FRunAsStandalone; FApplicationBinFolder = ACopyFrom.FApplicationBinFolder; }
private void ReadLongApplicationForm(TFileVersionInfo APetraVersion, PmGeneralApplicationRow AGeneralApplicationRow, TDBTransaction ATransaction, out Boolean ARecordAddedOrModified) { ARecordAddedOrModified = false; PmYearProgramApplicationRow YearProgramApplicationRow = FMainDS.PmYearProgramApplication.NewRowTyped(); YearProgramApplicationRow.PartnerKey = FPartnerKey; YearProgramApplicationRow.ApplicationKey = AGeneralApplicationRow.ApplicationKey; YearProgramApplicationRow.YpAppDate = AGeneralApplicationRow.GenAppDate; YearProgramApplicationRow.YpBasicAppType = AGeneralApplicationRow.AppTypeName; YearProgramApplicationRow.RegistrationOffice = AGeneralApplicationRow.RegistrationOffice; YearProgramApplicationRow.HoOrientConfBookingKey = ReadString(); YearProgramApplicationRow.YpAgreedJoiningCharge = ReadDecimal(); YearProgramApplicationRow.YpAgreedSupportFigure = ReadDecimal(); if (APetraVersion.FileMajorPart < 3) { ReadBoolean(); // Field removed: YearProgramApplicationRow.YpAppFeeReceived } YearProgramApplicationRow.YpBasicDeleteFlag = ReadBoolean(); YearProgramApplicationRow.YpJoiningConf = ReadInt32(); YearProgramApplicationRow.StartOfCommitment = ReadNullableDate(); YearProgramApplicationRow.EndOfCommitment = ReadNullableDate(); YearProgramApplicationRow.IntendedComLengthMonths = ReadInt32(); YearProgramApplicationRow.PositionName = ReadString(); YearProgramApplicationRow.PositionScope = ReadString(); YearProgramApplicationRow.AssistantTo = ReadBoolean(); if (APetraVersion.FileMajorPart < 3) { ReadString(); // Field removed: YearProgramApplicationRow.YpScholarshipAthrizedBy ReadNullableDate(); // Field removed: YearProgramApplicationRow.YpScholarshipBeginDate ReadNullableDate(); // Field removed: YearProgramApplicationRow.YpScholarshipEndDate ReadDecimal(); // Field removed: YearProgramApplicationRow.YpScholarship ReadString(); // Field removed: YearProgramApplicationRow.YpScholarshipPeriod ReadNullableDate(); // Field removed: YearProgramApplicationRow.YpScholarshipReviewDate } YearProgramApplicationRow.YpSupportPeriod = ReadString(); if (!FIgnoreApplication) { PmYearProgramApplicationAccess.AddOrModifyRecord( YearProgramApplicationRow.PartnerKey, YearProgramApplicationRow.ApplicationKey, YearProgramApplicationRow.RegistrationOffice, FMainDS.PmYearProgramApplication, YearProgramApplicationRow, FDoNotOverwrite, ATransaction); ARecordAddedOrModified = true; } }
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> /// 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; }
/// <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); FDBConnectionCheckInterval = TAppSettingsManager.GetInt32("Server.DBConnectionCheckInterval", 0); FApplicationBinFolder = TAppSettingsManager.GetValue("Server.ApplicationBinDirectory", 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); FSmtpHost = TAppSettingsManager.GetValue("SmtpHost", ""); FSmtpPort = TAppSettingsManager.GetInt32("SmtpPort", 25); FSmtpUser = TAppSettingsManager.GetValue("SmtpUser", "YourSmtpUser"); FSmtpPassword = TAppSettingsManager.GetValue("SmtpPassword", "YourSmtpPassword"); FSmtpEnableSsl = TAppSettingsManager.GetBoolean("SmtpEnableSsl", true); FSmtpAuthenticationType = TAppSettingsManager.GetValue("SmtpAuthenticationType", "config").ToLower(); FSmtpIgnoreServerCertificateValidation = TAppSettingsManager.GetBoolean("IgnoreServerCertificateValidation", false); // Determine network configuration of the Server Networking.DetermineNetworkConfig(out FHostName, out FHostIPAddresses); FApplicationVersion = TFileVersionInfo.GetApplicationVersion(); }
/// Updating of a Progress or ODBC 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 Exception( "Cannot connect to old database, please restore the latest clean demo database or run nant patchDatabase"); }
private void ImportApplication(TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { Boolean RecordAddedOrModified = false; FIgnoreApplication = FIgnorePartner; PtApplicationTypeRow ApplicationTypeRow = FMainDS.PtApplicationType.NewRowTyped(); ApplicationTypeRow.AppFormType = ReadString(); ApplicationTypeRow.AppTypeName = ReadString(); ApplicationTypeRow.AppTypeDescr = ReadString(); PmGeneralApplicationRow GeneralApplicationRow = FMainDS.PmGeneralApplication.NewRowTyped(); GeneralApplicationRow.PartnerKey = FPartnerKey; GeneralApplicationRow.AppTypeName = ApplicationTypeRow.AppTypeName; GeneralApplicationRow.GenAppDate = ReadDate(); GeneralApplicationRow.OldLink = ReadString(); if (FExistingPartnerOldLinks.Contains(GeneralApplicationRow.OldLink)) { // if there is already an application with this "OldLink" then don't import this one AddVerificationResult( "OldLink already exists for this Person: " + GeneralApplicationRow.OldLink + ". This application will not be imported!"); FIgnoreApplication = true; } GeneralApplicationRow.GenApplicantType = ReadString(); GeneralApplicationRow.GenApplicationHoldReason = ReadString(); GeneralApplicationRow.GenApplicationOnHold = ReadBoolean(); GeneralApplicationRow.GenApplicationStatus = ReadString(); GeneralApplicationRow.GenAppCancelled = ReadNullableDate(); GeneralApplicationRow.GenAppCancelReason = ReadString(); GeneralApplicationRow.GenAppDeleteFlag = ReadBoolean(); GeneralApplicationRow.Closed = ReadBoolean(); GeneralApplicationRow.ClosedBy = ReadString(); GeneralApplicationRow.DateClosed = ReadNullableDate(); Int64? GenAppPossSrvUnitKey = ReadNullableInt64(); if (GenAppPossSrvUnitKey.HasValue && (GenAppPossSrvUnitKey.Value != 0)) { GeneralApplicationRow.GenAppPossSrvUnitKey = GenAppPossSrvUnitKey.Value; AddRequiredOffice(GeneralApplicationRow.GenAppPossSrvUnitKey); } GeneralApplicationRow.GenAppRecvgFldAccept = ReadNullableDate(); GeneralApplicationRow.GenAppSrvFldAccept = ReadBoolean(); GeneralApplicationRow.GenAppSendFldAcceptDate = ReadNullableDate(); GeneralApplicationRow.GenAppSendFldAccept = ReadBoolean(); GeneralApplicationRow.GenAppCurrencyCode = CheckCurrencyCode(ReadString(), ATransaction); Int64? PlacementPartnerKey = ReadNullableInt64(); if (PlacementPartnerKey.HasValue && (PlacementPartnerKey.Value != 0)) { GeneralApplicationRow.PlacementPartnerKey = PlacementPartnerKey.Value; } GeneralApplicationRow.GenAppUpdate = ReadNullableDate(); GeneralApplicationRow.GenCancelledApp = ReadBoolean(); GeneralApplicationRow.GenContact1 = ReadString(); GeneralApplicationRow.GenContact2 = ReadString(); if (APetraVersion.FileMajorPart < 3) { ReadString(); // field removed: GeneralApplicationRow.GenYearProgram } GeneralApplicationRow.ApplicationKey = ReadInt32(); GeneralApplicationRow.RegistrationOffice = ReadInt64(); if (!PUnitAccess.Exists(GeneralApplicationRow.RegistrationOffice, ATransaction)) { AddVerificationResult(String.Format("Unknown Registration Office {0}.\n{1} substituted in Application form.", GeneralApplicationRow.RegistrationOffice, DomainManager.GSiteKey)); GeneralApplicationRow.RegistrationOffice = DomainManager.GSiteKey; // I can't do this because this is part of GeneralApplicationRow's primary Key // So I mustn't change it after calling AddOrModifyRecord, below. // AddRequiredOffice(GeneralApplicationRow.RegistrationOffice); } } GeneralApplicationRow.Comment = ReadMultiLine(); if (ApplicationTypeRow.AppFormType == MPersonnelConstants.APPLICATIONFORMTYPE_SHORTFORM) { ReadShortApplicationForm(APetraVersion, GeneralApplicationRow, ATransaction, out RecordAddedOrModified); } else if (ApplicationTypeRow.AppFormType == MPersonnelConstants.APPLICATIONFORMTYPE_LONGFORM) { ReadLongApplicationForm(APetraVersion, GeneralApplicationRow, ATransaction, out RecordAddedOrModified); } if (!FIgnoreApplication && RecordAddedOrModified) { if (!FExistingPartnerOldLinks.Contains(GeneralApplicationRow.OldLink)) { FExistingPartnerOldLinks.Add(GeneralApplicationRow.OldLink); } PmGeneralApplicationAccess.AddOrModifyRecord( GeneralApplicationRow.PartnerKey, GeneralApplicationRow.ApplicationKey, GeneralApplicationRow.RegistrationOffice, FMainDS.PmGeneralApplication, GeneralApplicationRow, FDoNotOverwrite, ATransaction); } if (APetraVersion.FileMajorPart < 3) { string KeyWord = ReadString(); // needs to be kept in to support versions < 3.0.0 while (KeyWord == "APPL-FORM") { ReadApplicationForm(GeneralApplicationRow, ATransaction); KeyWord = ReadString(); } if (KeyWord == "END") { CheckForKeyword("FORMS"); } } }
/// 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; }
private void ImportPersonalData(TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { PmPersonalDataRow PersonalDataRow = FMainDS.PmPersonalData.NewRowTyped(); PersonalDataRow.PartnerKey = FPartnerKey; if (APetraVersion.FileMajorPart < 3) { ReadString(); // Field removed: PersonalDataRow.DriverStatus ReadBoolean(); // Field removed: PersonalDataRow.GenDriverLicense ReadString(); // Field removed: PersonalDataRow.DrivingLicenseNumber ReadBoolean(); // Field removed: PersonalDataRow.InternalDriverLicense if (((APetraVersion.FileMinorPart == 2) && (APetraVersion.FileBuildPart >= 20)) || ((APetraVersion.FileMinorPart == 3) && (APetraVersion.FileBuildPart >= 6))) { // blood type added with release 2.2.20 and 2.3.6 PersonalDataRow.BloodType = ReadString(); } } else { Int32? BelieverSinceYear = ReadNullableInt32(); if (BelieverSinceYear.HasValue) { PersonalDataRow.BelieverSinceYear = BelieverSinceYear.Value; } PersonalDataRow.BelieverSinceComment = ReadString(); PersonalDataRow.BloodType = ReadString(); } if (!FIgnorePartner) { PmPersonalDataAccess.AddOrModifyRecord(FPartnerKey, FMainDS.PmPersonalData, PersonalDataRow, FDoNotOverwrite, ATransaction); } }
private void ImportSpecialNeeds(TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { PmSpecialNeedRow SpecialNeedRow = FMainDS.PmSpecialNeed.NewRowTyped(); SpecialNeedRow.PartnerKey = FPartnerKey; SpecialNeedRow.DateCreated = ReadNullableDate(); if (APetraVersion.FileMajorPart < 3) { ReadBoolean(); // Field removed: SpecialNeedRow.ContactHomeOffice } SpecialNeedRow.VegetarianFlag = ReadBoolean(); SpecialNeedRow.DietaryComment = ReadString(); SpecialNeedRow.MedicalComment = ReadString(); SpecialNeedRow.OtherSpecialNeed = ReadString(); if (!FIgnorePartner) { PmSpecialNeedAccess.AddOrModifyRecord(SpecialNeedRow.PartnerKey, FMainDS.PmSpecialNeed, SpecialNeedRow, FDoNotOverwrite, ATransaction); } }
private void ImportPassport(TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { PmPassportDetailsRow PassportDetailsRow = FMainDS.PmPassportDetails.NewRowTyped(); PassportDetailsRow.PartnerKey = FPartnerKey; PassportDetailsRow.PassportNumber = ReadString(); if (APetraVersion.Compare(new TFileVersionInfo("2.3.3")) >= 0) { PassportDetailsRow.MainPassport = ReadBoolean(); } PassportDetailsRow.CountryOfIssue = CheckCountryCode(ReadString(), ATransaction); PassportDetailsRow.DateOfExpiration = ReadNullableDate(); PassportDetailsRow.DateOfIssue = ReadNullableDate(); PassportDetailsRow.FullPassportName = ReadString(); PassportDetailsRow.PassportNationalityCode = ReadString(); PassportDetailsRow.PassportDetailsType = ReadString(); PassportDetailsRow.PassportDob = ReadNullableDate(); PassportDetailsRow.PlaceOfBirth = ReadString(); PassportDetailsRow.PlaceOfIssue = ReadString(); if (!FIgnorePartner) { PmPassportDetailsAccess.AddOrModifyRecord(PassportDetailsRow.PartnerKey, PassportDetailsRow.PassportNumber, FMainDS.PmPassportDetails, PassportDetailsRow, FDoNotOverwrite, ATransaction); } }
private void ImportPreviousExperience(TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { PmPastExperienceRow PastExperienceRow = FMainDS.PmPastExperience.NewRowTyped(); PastExperienceRow.PartnerKey = FPartnerKey; PastExperienceRow.SiteKey = ReadInt64(); PastExperienceRow.Key = ReadInt64(); PastExperienceRow.PrevLocation = ReadString(); PastExperienceRow.StartDate = ReadNullableDate(); PastExperienceRow.EndDate = ReadNullableDate(); PastExperienceRow.PrevWorkHere = ReadBoolean(); PastExperienceRow.PrevWork = ReadBoolean(); PastExperienceRow.OtherOrganisation = ReadString(); PastExperienceRow.PrevRole = ReadString(); if (APetraVersion.Compare(new TFileVersionInfo("2.3.3")) >= 0) { PastExperienceRow.Category = ReadString(); } PastExperienceRow.PastExpComments = ReadString(); if (!FIgnorePartner) { PmPastExperienceAccess.AddOrModifyRecord(PastExperienceRow.SiteKey, PastExperienceRow.Key, FMainDS.PmPastExperience, PastExperienceRow, FDoNotOverwrite, ATransaction); } }
private void ImportLanguage(TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { PmPersonLanguageRow PersonLanguageRow = FMainDS.PmPersonLanguage.NewRowTyped(); PersonLanguageRow.PartnerKey = FPartnerKey; PersonLanguageRow.LanguageCode = ReadString(); if (APetraVersion.FileMajorPart < 3) { ReadBoolean(); // field removed: PersonLanguageRow.WillingToTranslate ReadBoolean(); // field removed: PersonLanguageRow.TranslateInto ReadBoolean(); // field removed: PersonLanguageRow.TranslateOutOf } PersonLanguageRow.YearsOfExperience = ReadInt32(); PersonLanguageRow.LanguageLevel = CheckLanguageLevel(ReadInt32(), APetraVersion, ATransaction); PersonLanguageRow.YearsOfExperienceAsOf = ReadNullableDate(); PersonLanguageRow.Comment = ReadString(); if (!FIgnorePartner && (PersonLanguageRow.LanguageCode != "")) { PmPersonLanguageAccess.AddOrModifyRecord(PersonLanguageRow.PartnerKey, PersonLanguageRow.LanguageCode, FMainDS.PmPersonLanguage, PersonLanguageRow, FDoNotOverwrite, ATransaction); } }
/// <summary> /// get the version of the current application. /// Parse version.txt in the same directory if that file exists. /// Otherwise use the version of the exe or dll file /// </summary> /// <returns></returns> public static TFileVersionInfo GetApplicationVersion() { TFileVersionInfo Result = new TFileVersionInfo(); // retrieve the current version of the server from the file version.txt in the bin directory // this is easier to manage than to check the assembly version in case you only need to quickly update the client string BinPath = TAppSettingsManager.ApplicationDirectory; if (File.Exists(BinPath + Path.DirectorySeparatorChar + "version.txt")) { StreamReader srVersion = new StreamReader(BinPath + Path.DirectorySeparatorChar + "version.txt"); Result = new TFileVersionInfo(srVersion.ReadLine()); srVersion.Close(); } else if ((System.Reflection.Assembly.GetEntryAssembly() != null) && (System.Reflection.Assembly.GetEntryAssembly().GetName() != null)) { Result = new TFileVersionInfo(System.Reflection.Assembly.GetEntryAssembly().GetName().Version); } else { // this is with the web services, started with xsp.exe, or running from NUnit Result = new TFileVersionInfo(new Version(0, 0, 0, 0)); } return Result; }
/// 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; }
/// <summary> /// compare two file versions, while ignoring the private part /// </summary> /// <returns>-1 if this < ACmp, 1 if this > ACmp, and 0 if equals</returns> public Int16 CompareWithoutPrivatePart(TFileVersionInfo ACmp) { Int16 ReturnValue; if (FileMajorPart > ACmp.FileMajorPart) { ReturnValue = 1; } else if (FileMajorPart < ACmp.FileMajorPart) { ReturnValue = -1; } else if (FileMinorPart > ACmp.FileMinorPart) { ReturnValue = 1; } else if (FileMinorPart < ACmp.FileMinorPart) { ReturnValue = -1; } else if (FileBuildPart > ACmp.FileBuildPart) { ReturnValue = 1; } else if (FileBuildPart < ACmp.FileBuildPart) { ReturnValue = -1; } else { ReturnValue = 0; } return ReturnValue; }
/// <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; }
/// <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); FApplicationBinFolder = TAppSettingsManager.GetValue("Server.ApplicationBinDirectory", 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(); }
/// <summary> /// constructor for base class /// </summary> /// <param name="version"></param> public TPatchFileVersionInfo(TFileVersionInfo version) : base(version) { }
private void ImportJob(TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { Boolean ImportJobAssignment = true; PmJobAssignmentRow JobAssignmentRow = FMainDS.PmJobAssignment.NewRowTyped(); JobAssignmentRow.PartnerKey = FPartnerKey; JobAssignmentRow.FromDate = ReadDate(); JobAssignmentRow.ToDate = ReadNullableDate(); JobAssignmentRow.PositionName = ReadString(); JobAssignmentRow.PositionScope = ReadString(); JobAssignmentRow.AssistantTo = ReadBoolean(); ReadInt64(); // JobAssignmentRow.JobKey: not to be imported ReadInt64(); // JobAssignmentRow.JobAssignmentKey: not to be imported JobAssignmentRow.UnitKey = ReadInt64(); // do not import job record if unit does not exist if (!PUnitAccess.Exists(JobAssignmentRow.UnitKey, ATransaction)) { AddVerificationResult( "Error - Job Assignment Unit Key " + JobAssignmentRow.UnitKey.ToString("0000000000") + " for Partner " + FPartnerKey.ToString("0000000000") + " does not exist in database. Job Assignment Record will not be imported."); ImportJobAssignment = false; } JobAssignmentRow.AssignmentTypeCode = CheckJobAssignmentTypeCode(ReadString(), ATransaction); if (APetraVersion.Compare(new TFileVersionInfo("3.0.0")) < 0) { ReadString(); // used to be JobAssignmentRow.LeavingCode ReadNullableDate(); // used to be JobAssignmentRow.LeavingCodeUpdatedDate } if (!FIgnorePartner && ImportJobAssignment) { // find job assignment (ignoring job key and job assignment key) PmJobAssignmentRow TmpJobAssignmentRow = FMainDS.PmJobAssignment.NewRowTyped(false); TmpJobAssignmentRow.PartnerKey = FPartnerKey; TmpJobAssignmentRow.UnitKey = JobAssignmentRow.UnitKey; TmpJobAssignmentRow.PositionName = JobAssignmentRow.PositionName; TmpJobAssignmentRow.PositionScope = JobAssignmentRow.PositionScope; PmJobAssignmentTable ExistingJobAssignmentTable = PmJobAssignmentAccess.LoadUsingTemplate(TmpJobAssignmentRow, null, ATransaction); if (ExistingJobAssignmentTable.Count == 0) { // if job assignment does not exist: find job UmJobRow TmpJobRow = FMainDS.UmJob.NewRowTyped(false); TmpJobRow.UnitKey = JobAssignmentRow.UnitKey; TmpJobRow.PositionName = JobAssignmentRow.PositionName; TmpJobRow.PositionScope = JobAssignmentRow.PositionScope; UmJobTable ExistingJobTable = UmJobAccess.LoadUsingTemplate(TmpJobRow, null, ATransaction); if (ExistingJobTable.Count == 0) { // if job does not exist: create job with default values UmJobRow JobRow = FMainDS.UmJob.NewRowTyped(true); JobRow.UnitKey = TmpJobRow.UnitKey; JobRow.PositionName = TmpJobRow.PositionName; JobRow.PositionScope = TmpJobRow.PositionScope; JobRow.JobKey = (Int32)MCommon.WebConnectors.TSequenceWebConnector.GetNextSequence(TSequenceNames.seq_job); JobRow.JobType = "Long Term"; JobRow.FromDate = JobAssignmentRow.FromDate; JobRow.ToDate = JobAssignmentRow.ToDate; JobRow.CommitmentPeriod = "None"; JobRow.TrainingPeriod = "None"; JobRow.Present = 1; UmJobAccess.AddOrModifyRecord(JobRow.UnitKey, JobRow.PositionName, JobRow.PositionScope, JobRow.JobKey, FMainDS.UmJob, JobRow, FDoNotOverwrite, ATransaction); JobAssignmentRow.JobKey = JobRow.JobKey; } else { JobAssignmentRow.JobKey = ((UmJobRow)ExistingJobTable.Rows[0]).JobKey; } JobAssignmentRow.JobAssignmentKey = (Int32)MCommon.WebConnectors.TSequenceWebConnector.GetNextSequence( TSequenceNames.seq_job_assignment); } else { // job assignment already exists: update record in database JobAssignmentRow.JobKey = ((PmJobAssignmentRow)ExistingJobAssignmentTable.Rows[0]).JobKey; JobAssignmentRow.JobAssignmentKey = ((PmJobAssignmentRow)ExistingJobAssignmentTable.Rows[0]).JobAssignmentKey; } // now add or modify job assignment record PmJobAssignmentAccess.AddOrModifyRecord(JobAssignmentRow.PartnerKey, JobAssignmentRow.UnitKey, JobAssignmentRow.PositionName, JobAssignmentRow.PositionScope, JobAssignmentRow.JobKey, JobAssignmentRow.JobAssignmentKey, FMainDS.PmJobAssignment, JobAssignmentRow, FDoNotOverwrite, ATransaction); } }
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; }
/// <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; } } }
private void ImportOptionalDetails(PPartnerRow APartnerRow, TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { string KeyWord = ReadString(); while (KeyWord != "END") { if (KeyWord == "ABILITY") { ImportAbility(ATransaction); } else if (KeyWord == "ADDRESS") { ImportLocation(ATransaction); } else if (KeyWord == "APPLCTN") { ImportApplication(APetraVersion, ATransaction); } else if (KeyWord == "COMMENT") { ImportComment(APartnerRow); } else if (KeyWord == "COMMENTSEQ") { ImportCommentSeq(); } else if (KeyWord == "COMMIT") { ImportStaffData(ATransaction); } else if (KeyWord == "JOB") { ImportJob(APetraVersion, ATransaction); } else if (KeyWord == "LANGUAGE") { ImportLanguage(APetraVersion, ATransaction); } else if (KeyWord == "PREVEXP") { ImportPreviousExperience(APetraVersion, ATransaction); } else if (KeyWord == "PASSPORT") { ImportPassport(APetraVersion, ATransaction); } else if (KeyWord == "PERSDOCUMENT") { ImportPersonalDocument(ATransaction); } else if (KeyWord == "PERSONAL") { ImportPersonalData(APetraVersion, ATransaction); } else if (KeyWord == "PROFESN") { ImportProfessionalData(ATransaction); } else if (KeyWord == "PROGREP") { ImportPersonEvaluation(ATransaction); } else if (KeyWord == "SPECNEED") { ImportSpecialNeeds(APetraVersion, ATransaction); } else if (KeyWord == "TYPE") { ImportPartnerType(ATransaction); } else if (KeyWord == "PARTNERATTRIBUTE") { ImportPartnerAttribute(ATransaction); FParsingOfPartnerLocationsForContactDetailsNecessary = false; } else if (KeyWord == "INTEREST") { ImportInterest(ATransaction); } else if (KeyWord == "GIFTDESTINATION") { ImportGiftDestination(ATransaction); } else if (KeyWord == "U-ABILITY") { ImportUnitAbility(ATransaction); } else if (KeyWord == "U-COSTS") { ImportUnitCosts(ATransaction); } else if (KeyWord == "U-JOB") { ImportUnitJob(); } else if (KeyWord == "UJ-ABIL") { ImportUnitJobAbility(); } else if (KeyWord == "UJ-LANG") { ImportUnitJobLanguage(); } else if (KeyWord == "UJ-QUAL") { ImportUnitJobQualification(); } else if (KeyWord == "UJ-VISION") { ImportUnitJobVision(); } else if (KeyWord == "U-LANG") { ImportUnitLanguage(ATransaction); } else if (KeyWord == "U-STRUCT") { ImportUnitStructure(ATransaction); } else if (KeyWord == "U-VISION") { ImportUnitVision(ATransaction); } else if (KeyWord == "V-BUILDING") { ImportBuilding(ATransaction); } else if (KeyWord == "V-ROOM") { ImportRoom(ATransaction); } else if (KeyWord == "VISION") { ImportVision(ATransaction); } else { throw new Exception("Found unknown option " + KeyWord); } KeyWord = ReadString(); } }
/// <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(); }
/// <summary> /// Import all data of a partner from a text file, using a format used by Petra 2.x. /// Containing: partner, person/family/church/etc record, valid locations, contact details, special types, /// interests, personnel data, commitments, applications, etc. /// For UNITs there is more specific data, used eg. for the events file. /// </summary> /// <param name="ALinesToImport"></param> /// <param name="ALimitToOption">if this is not an empty string, only the applications for this conference will be imported, historic applications will be ignored</param> /// <param name="ADoNotOverwrite">do not modify records that already exist in the database</param> /// <param name="AResultList">verification results. can contain critical errors and messages for the user</param> /// <returns>nothing - an empty TDS</returns> public PartnerImportExportTDS ImportAllData(string[] ALinesToImport, string ALimitToOption, bool ADoNotOverwrite, out TVerificationResultCollection AResultList) { FResultList = new TVerificationResultCollection(); FCountLocationKeys = -1; FLimitToOption = ALimitToOption; FDoNotOverwrite = ADoNotOverwrite; FMainDS = new PartnerImportExportTDS(); InitReading(ALinesToImport); TFileVersionInfo PetraVersion = new TFileVersionInfo(ReadString()); ReadInt64(); // SiteKey ReadInt32(); // SubVersion if ((PetraVersion.FileMajorPart < 3) && (PetraVersion.FileMinorPart < 2)) { AddVerificationResult( "EXT import not supported from old file type: " + PetraVersion.ToString(), TResultSeverity.Resv_Critical); } else { TDBTransaction Transaction = null; bool SubmissionOK = false; DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK, delegate { try { while (CheckForKeyword("PARTNER")) { PPartnerRow PartnerRow = ImportPartner(Transaction); ImportPartnerClassSpecific(PartnerRow.PartnerClass, PetraVersion, Transaction); ImportLocation(Transaction); ImportOptionalDetails(PartnerRow, PetraVersion, Transaction); } ImportContext = "Checking data references"; CheckRequiredUnits(Transaction); // AddRequiredUnits(FRequiredOfficeKeys, "F", 1000000, "Office", Transaction); // AddRequiredUnits(FRequiredOptionKeys, "CONF", 1000000, "Conference", Transaction); if (FParsingOfPartnerLocationsForContactDetailsNecessary) { TPartnerContactDetails_LocationConversionHelper.PartnerAttributeLoadUsingTemplate = PPartnerAttributeAccess.LoadUsingTemplate; TPartnerContactDetails_LocationConversionHelper.SequenceGetter = MCommon.WebConnectors.TSequenceWebConnector.GetNextSequence; TPartnerContactDetails_LocationConversionHelper.ParsePartnerLocationsForContactDetails(FMainDS, Transaction); } } catch (Exception e) { TLogging.Log(e.GetType().ToString() + ": " + e.Message + " in line " + (CurrentLineCounter + 1).ToString()); TLogging.Log(CurrentLine); TLogging.Log(e.StackTrace); throw; } SubmissionOK = true; }); } AResultList = FResultList; if (!TVerificationHelper.IsNullOrOnlyNonCritical(AResultList)) { return new PartnerImportExportTDS(); } return FMainDS; }
/// <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; } }
/// <summary> /// If I'm importing an unknown Language level, use 99 instead /// </summary> /// <param name="ALanguageLevel"></param> /// <param name="APetraVersion"></param> /// <param name="ATransaction"></param> /// <returns></returns> private int CheckLanguageLevel(int ALanguageLevel, TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { if (APetraVersion.FileMajorPart < 3) { // cover data conversion from 2.x to 3.x if ((ALanguageLevel >= 0) && (ALanguageLevel <= 3)) { return 1; } else if ((ALanguageLevel >= 4) && (ALanguageLevel <= 7)) { return 2; } else if ((ALanguageLevel >= 8) && (ALanguageLevel != 99)) { return 3; } else if (ALanguageLevel == 99) { return ALanguageLevel; } else { AddVerificationResult("Unknown Language Level " + ALanguageLevel); return 99; // "Unknown" code } } else { // this applies to all imports from OpenPetra versions if (PtLanguageLevelAccess.Exists(ALanguageLevel, ATransaction)) { return ALanguageLevel; } else { AddVerificationResult("Unknown Language Level " + ALanguageLevel); return 99; // "Unknown" code } } }
/// <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; }
private void ImportPartnerClassSpecific(string APartnerClass, TFileVersionInfo APetraVersion, TDBTransaction ATransaction) { if (APartnerClass == MPartnerConstants.PARTNERCLASS_CHURCH) { PChurchRow ChurchRow = FMainDS.PChurch.NewRowTyped(); ChurchRow.PartnerKey = FPartnerKey; ChurchRow.ChurchName = ReadString(); ChurchRow.DenominationCode = ReadString(); ChurchRow.Accomodation = ReadBoolean(); ChurchRow.AccomodationSize = ReadInt32(); ChurchRow.AccomodationType = ReadString(); ChurchRow.ApproximateSize = ReadInt32(); if (!FIgnorePartner) { PChurchAccess.AddOrModifyRecord(ChurchRow.PartnerKey, FMainDS.PChurch, ChurchRow, FDoNotOverwrite, ATransaction); } } else if (APartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY) { PFamilyRow FamilyRow = FMainDS.PFamily.NewRowTyped(); FamilyRow.PartnerKey = FPartnerKey; FamilyRow.FamilyName = ReadString(); FamilyRow.FirstName = ReadString(); FamilyRow.Title = ReadString(); if (APetraVersion.FileMajorPart < 3) { ReadNullableInt64(); // field removed: FamilyRow.FieldKey } FamilyRow.MaritalStatus = ReadString(); FamilyRow.MaritalStatusSince = ReadNullableDate(); FamilyRow.MaritalStatusComment = ReadString(); // // The EXT file can have the same family record more than once (where several Partners share a family) // I need to check I've not added it already. // if (!FIgnorePartner) { PFamilyAccess.AddOrModifyRecord(FamilyRow.PartnerKey, FMainDS.PFamily, FamilyRow, FDoNotOverwrite, ATransaction); } } else if (APartnerClass == MPartnerConstants.PARTNERCLASS_PERSON) { PPersonRow PersonRow = FMainDS.PPerson.NewRowTyped(); PersonRow.PartnerKey = FPartnerKey; PersonRow.FamilyName = ReadString(); PersonRow.FirstName = ReadString(); PersonRow.MiddleName1 = ReadString(); PersonRow.Title = ReadString(); PersonRow.Decorations = ReadString(); PersonRow.PreferedName = ReadString(); PersonRow.DateOfBirth = ReadNullableDate(); PersonRow.Gender = ReadString(); PersonRow.MaritalStatus = ReadString(); PersonRow.MaritalStatusSince = ReadNullableDate(); PersonRow.MaritalStatusComment = ReadString(); if (APetraVersion.FileMajorPart < 3) { // used to be BelieverSinceYear and BelieverSinceComment before 3.0 ReadNullableInt32(); ReadString(); } PersonRow.OccupationCode = ReadString(); if (APetraVersion.FileMajorPart < 3) { ReadNullableInt64(); // field removed: PersonRow.FieldKey } PersonRow.FamilyKey = ReadInt64(); PersonRow.FamilyId = ReadInt32(); if (TAppSettingsManager.GetValue("AllowCreationPersonRecords", "true", false).ToLower() != "true") { throw new Exception( "Import of PERSON records is currently not supported. " + "Add configuration parameter AllowCreationPersonRecords with value true to use PERSON records."); } if (!FIgnorePartner) { PPersonAccess.AddOrModifyRecord(PersonRow.PartnerKey, FMainDS.PPerson, PersonRow, FDoNotOverwrite, ATransaction); } } else if (APartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION) { POrganisationRow OrganisationRow = FMainDS.POrganisation.NewRowTyped(); OrganisationRow.PartnerKey = FPartnerKey; OrganisationRow.OrganisationName = ReadString(); OrganisationRow.BusinessCode = ReadString(); OrganisationRow.Religious = ReadBoolean(); OrganisationRow.Foundation = ReadBoolean(); if (!FIgnorePartner) { POrganisationAccess.AddOrModifyRecord(OrganisationRow.PartnerKey, FMainDS.POrganisation, OrganisationRow, FDoNotOverwrite, ATransaction); } } else if (APartnerClass == MPartnerConstants.PARTNERCLASS_UNIT) { PUnitRow UnitRow = FMainDS.PUnit.NewRowTyped(); UnitRow.PartnerKey = FPartnerKey; UnitRow.UnitName = ReadString(); ReadString(); // was omss code UnitRow.OutreachCode = ReadString(); UnitRow.Description = ReadString(); ReadInt32(); // was um_default_entry_conf_key_n UnitRow.UnitTypeCode = ReadString(); UnitRow.CountryCode = CheckCountryCode(ReadString(), ATransaction); UnitRow.OutreachCost = ReadDecimal(); UnitRow.OutreachCostCurrencyCode = CheckCurrencyCode(ReadString(), ATransaction); UnitRow.PrimaryOffice = ReadInt64(); if (!FIgnorePartner) { PUnitAccess.AddOrModifyRecord(UnitRow.PartnerKey, FMainDS.PUnit, UnitRow, FDoNotOverwrite, ATransaction); } } else if (APartnerClass == MPartnerConstants.PARTNERCLASS_VENUE) { PVenueRow VenueRow = FMainDS.PVenue.NewRowTyped(); VenueRow.PartnerKey = FPartnerKey; VenueRow.VenueName = ReadString(); VenueRow.VenueCode = ReadString(); VenueRow.CurrencyCode = CheckCurrencyCode(ReadString(), ATransaction); VenueRow.ContactPartnerKey = ReadInt64(); if (!PPartnerAccess.Exists(VenueRow.ContactPartnerKey, ATransaction)) { // make sure that contact partner key exists in the database already, otherwise reset to take // care of referential integrity AddVerificationResult("Contact Partner for Venue " + FPartnerKey.ToString("0000000000") + " not set" + " as Partner Key " + VenueRow.ContactPartnerKey.ToString("0000000000") + " does not exist in database."); VenueRow.SetContactPartnerKeyNull(); } if (!FIgnorePartner) { PVenueAccess.AddOrModifyRecord(VenueRow.PartnerKey, FMainDS.PVenue, VenueRow, FDoNotOverwrite, ATransaction); } } else if (APartnerClass == MPartnerConstants.PARTNERCLASS_BANK) { PBankRow BankRow = FMainDS.PBank.NewRowTyped(); BankRow.PartnerKey = FPartnerKey; if (!FIgnorePartner) { PBankAccess.AddOrModifyRecord(BankRow.PartnerKey, FMainDS.PBank, BankRow, FDoNotOverwrite, ATransaction); } } }
/// <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; }
private void ReadShortApplicationForm(TFileVersionInfo APetraVersion, PmGeneralApplicationRow AGeneralApplicationRow, TDBTransaction ATransaction, out Boolean ARecordAddedOrModified) { ARecordAddedOrModified = false; PmShortTermApplicationRow ShortTermApplicationRow = FMainDS.PmShortTermApplication.NewRowTyped(); ShortTermApplicationRow.PartnerKey = FPartnerKey; ShortTermApplicationRow.ApplicationKey = AGeneralApplicationRow.ApplicationKey; ShortTermApplicationRow.RegistrationOffice = AGeneralApplicationRow.RegistrationOffice; ShortTermApplicationRow.StAppDate = AGeneralApplicationRow.GenAppDate; ShortTermApplicationRow.StApplicationType = AGeneralApplicationRow.AppTypeName; ShortTermApplicationRow.StBasicOutreachId = AGeneralApplicationRow.OldLink; ShortTermApplicationRow.ConfirmedOptionCode = ReadString(); if ((FLimitToOption.Length > 0) && (ShortTermApplicationRow.ConfirmedOptionCode != FLimitToOption)) { FIgnoreApplication = true; } if (APetraVersion.FileMajorPart < 3) { ReadString(); // field removed: ShortTermApplicationRow.Option1Code ReadString(); // field removed: ShortTermApplicationRow.Option2Code } ShortTermApplicationRow.FromCongTravelInfo = ReadString(); ShortTermApplicationRow.Arrival = ReadNullableDate(); ShortTermApplicationRow.ArrivalHour = ReadInt32(); ShortTermApplicationRow.ArrivalMinute = ReadInt32(); ShortTermApplicationRow.Departure = ReadNullableDate(); ShortTermApplicationRow.DepartureHour = ReadInt32(); ShortTermApplicationRow.DepartureMinute = ReadInt32(); ShortTermApplicationRow.StApplicationHoldReason = ReadString(); ShortTermApplicationRow.StApplicationOnHold = ReadBoolean(); ShortTermApplicationRow.StBasicDeleteFlag = ReadBoolean(); if (APetraVersion.FileMajorPart < 3) { ReadBoolean(); // field removed: ShortTermApplicationRow.StBookingFeeReceived } ShortTermApplicationRow.StOutreachOnlyFlag = ReadBoolean(); ShortTermApplicationRow.StOutreachSpecialCost = ReadInt32(); ShortTermApplicationRow.StCngrssSpecialCost = ReadInt32(); if (APetraVersion.FileMajorPart < 3) { ReadString(); // field removed: ShortTermApplicationRow.StComment } Int64 Option = ReadInt64(); if (Option > 0) { ShortTermApplicationRow.StConfirmedOption = Option; if (!FIgnoreApplication) { // only process application if no other application for this option (event) exists in data import file if (!FExistingPartnerOptions.Contains(Option)) { if (PUnitAccess.Exists(Option, ATransaction)) { AddUnitOption(Option); FExistingPartnerOptions.Add(Option); } else { // if unit does not exist in system then don't add this application AddVerificationResult("Unknown Event in Application: " + Option + ". Application will not be imported!"); FIgnoreApplication = true; } } else { // if there is already an application for this option (event) then don't import this one AddVerificationResult("More than one Application for Event: " + Option + ". Only first application will be imported!"); FIgnoreApplication = true; } } } ShortTermApplicationRow.StCongressCode = CheckCongressCode(ReadString(), ATransaction); ShortTermApplicationRow.StCongressLanguage = ReadString(); if (APetraVersion.FileMajorPart < 3) { ReadString(); // field removed: ShortTermApplicationRow.StCountryPref } Int64? StCurrentField = ReadNullableInt64(); if (!FIgnoreApplication && StCurrentField.HasValue && (StCurrentField.Value != 0)) { ShortTermApplicationRow.StCurrentField = StCurrentField.Value; AddRequiredOffice(ShortTermApplicationRow.StCurrentField); } ShortTermApplicationRow.OutreachRole = CheckCongressCode(ReadString(), ATransaction); ShortTermApplicationRow.StFgCode = ReadString(); ShortTermApplicationRow.StFgLeader = ReadBoolean(); ShortTermApplicationRow.StFieldCharged = ReadInt64(); if (!FIgnoreApplication) { AddRequiredOffice(ShortTermApplicationRow.StFieldCharged); } if (APetraVersion.FileMajorPart < 3) { ReadString(); // field removed: ShortTermApplicationRow.StLeadershipRating ReadNullableInt64(); // field removed: StOption1 ReadNullableInt64(); // field removed: StOption2 ReadInt64(); // field removed: ShortTermApplicationRow.StPartyContact ReadString(); // field removed: ShortTermApplicationRow.StPartyTogether } ShortTermApplicationRow.StPreCongressCode = CheckCongressCode(ReadString(), ATransaction); if (APetraVersion.FileMajorPart < 3) { ReadBoolean(); // field removed: ShortTermApplicationRow.StProgramFeeReceived ReadString(); // field removed: ShortTermApplicationRow.StRecruitEfforts ReadDecimal(); // field removed: ShortTermApplicationRow.StScholarshipAmount ReadString(); // field removed: ShortTermApplicationRow.StScholarshipApprovedBy ReadString(); // field removed: ShortTermApplicationRow.StScholarshipPeriod ReadNullableDate(); // field removed: ShortTermApplicationRow.StScholarshipReviewDate } ShortTermApplicationRow.StSpecialApplicant = ReadString(); if (APetraVersion.FileMajorPart < 3) { ReadString(); // field removed: ShortTermApplicationRow.StActivityPref } ShortTermApplicationRow.ToCongTravelInfo = ReadString(); ShortTermApplicationRow.ArrivalPointCode = ReadString(); ShortTermApplicationRow.DeparturePointCode = ReadString(); ShortTermApplicationRow.TravelTypeFromCongCode = ReadString(); ShortTermApplicationRow.TravelTypeToCongCode = ReadString(); if (APetraVersion.FileMajorPart < 3) { ReadString(); // field removed: ShortTermApplicationRow.ContactNumber } ShortTermApplicationRow.ArrivalDetailsStatus = ReadString(); ShortTermApplicationRow.ArrivalTransportNeeded = ReadBoolean(); if (FArrivalPointTable == null) { FArrivalPointTable = PtArrivalPointAccess.LoadAll(StringHelper.StrSplit(PtArrivalPointTable.GetCodeDBName(), ","), ATransaction); } // clear unknown arrival points if (FArrivalPointTable.Rows.Find(ShortTermApplicationRow.ArrivalPointCode) == null) { ShortTermApplicationRow.SetArrivalPointCodeNull(); } if (FArrivalPointTable.Rows.Find(ShortTermApplicationRow.DeparturePointCode) == null) { ShortTermApplicationRow.SetDeparturePointCodeNull(); } if (APetraVersion.FileMajorPart < 3) { ReadNullableDate(); // field removed: ShortTermApplicationRow.ArrivalExp ReadInt32(); // field removed: ShortTermApplicationRow.ArrivalExpHour ReadInt32(); // field removed: ShortTermApplicationRow.ArrivalExpMinute } ShortTermApplicationRow.ArrivalComments = ReadString(); ShortTermApplicationRow.TransportInterest = ReadBoolean(); ShortTermApplicationRow.DepartureDetailsStatus = ReadString(); ShortTermApplicationRow.DepartureTransportNeeded = ReadBoolean(); if (APetraVersion.FileMajorPart < 3) { ReadNullableDate(); // field removed: ShortTermApplicationRow.DepartureExp ReadInt32(); // field removed: ShortTermApplicationRow.DepartureExpHour ReadInt32(); // field removed: ShortTermApplicationRow.DepartureExpMinute } ShortTermApplicationRow.DepartureComments = ReadString(); /* * I don't think that this should be done - In "old Petra" we could have 0 in StFieldCharged, * but in OpenPetra that's not a legal value. * (Tim Ingham, Oct 2011) */ if (ShortTermApplicationRow.StFieldCharged == 0) { // We cannot import a partner that has no field charged - this would be an invalid application. // we assume that the registration office will be charged. ShortTermApplicationRow.StFieldCharged = ShortTermApplicationRow.RegistrationOffice; } if (!FIgnoreApplication && !(ShortTermApplicationRow.IsStConfirmedOptionNull() || (ShortTermApplicationRow.StConfirmedOption == 0))) { PmShortTermApplicationAccess.AddOrModifyRecord( ShortTermApplicationRow.PartnerKey, ShortTermApplicationRow.ApplicationKey, ShortTermApplicationRow.RegistrationOffice, FMainDS.PmShortTermApplication, ShortTermApplicationRow, FDoNotOverwrite, ATransaction); ARecordAddedOrModified = true; } }