/// <summary> /// Gets called in regular intervals from a Timer in Class TTimedProcessing. /// </summary> /// <param name="ADBAccessObj">Instantiated DB Access object with opened DB connection.</param> /// <param name="ARunManually">this is true if the process was called manually from the server admin console</param> public static void Process(TDataBase ADBAccessObj, bool ARunManually) { // only check once a day (or as specified in config file), if not manually called if (!ARunManually) { DateTime LastRun = TVariant.DecodeFromString( TSystemDefaults.GetSystemDefault( PROCESSDATACHECK_LAST_RUN, new TVariant(DateTime.MinValue).EncodeToString())).ToDate(); if (LastRun.AddDays(TAppSettingsManager.GetInt16("DataChecks.RunEveryXDays", 1)) > DateTime.Now) { // do not run the data check more than once a day or a week (depending on configuration setting), too many emails TLogging.LogAtLevel(1, "TProcessDataChecks.Process: not running, since last run was at " + LastRun.ToString()); return; } } Errors_SinceDate = DateTime.Today.AddDays(-1 * SENDREPORTFORDAYS_TOUSERS); TLogging.LogAtLevel(1, "TProcessDataChecks.Process: Checking Modules"); CheckModule(ADBAccessObj, "DataCheck.MPartner."); TSystemDefaults.SetSystemDefault(PROCESSDATACHECK_LAST_RUN, new TVariant(DateTime.Now).EncodeToString()); }
public void Init() { new TLogging("../../log/test.log"); new TAppSettingsManager("../../etc/TestClient.config"); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Client.DebugLevel", 0); PathToTestData = "../../csharp/ICT/Testing/lib/Common/IO/TestData/".Replace("/", System.IO.Path.DirectorySeparatorChar.ToString()); }
/// <summary> /// Creates a new static instance of TSrvSetting for this AppDomain and takes /// over all settings from the static TSrvSetting object in the Default /// AppDomain. /// /// @comment WARNING: If you need to rename this procedure or change its parameters, /// you also need to change the String with its name and the parameters in the /// .NET Reflection call in TClientAppDomainConnection! /// /// @comment The static TSrvSetting object in the Default AppDomain is /// inaccessible in this AppDomain! /// /// </summary> /// <returns>void</returns> public void InitAppDomain(TSrvSetting ASettings) { // Console.WriteLine('TClientDomainManager.InitAppDomain in AppDomain: ' + Thread.GetDomain().FriendlyName); new TSrvSetting(ASettings); new TAppSettingsManager(TSrvSetting.ConfigurationFile); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); }
/// Method to obtain the SMTP email server configuration settings from the configuration file public static TSmtpServerSettings GetSmtpSettingsFromAppSettings() { return(new TSmtpServerSettings( TAppSettingsManager.GetValue("SmtpHost"), TAppSettingsManager.GetInt16("SmtpPort"), TAppSettingsManager.GetBoolean("SmtpEnableSsl", true), TAppSettingsManager.GetValue("SmtpUser"), TAppSettingsManager.GetValue("SmtpPassword"), TAppSettingsManager.GetBoolean("IgnoreServerCertificateValidation", false))); }
/// <summary> /// Initialises Logging and parses Server settings from different sources. /// /// </summary> public TServerManagerBase() : base() { FNumberServerManagerInstances = 0; new TAppSettingsManager(false); new TSrvSetting(); new TLogging(TSrvSetting.ServerLogFile); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); FFirstInstance = (FNumberServerManagerInstances == 0); FNumberServerManagerInstances++; }
// establish connection to database public static bool InitDBConnection( string ADBFile, string ADBPassword) { db = DBAccess.Connect("TSQLiteConsole"); new TLogging("debug.log"); TLogging.DebugLevel = TAppSettingsManager.GetInt16("DebugLevel", 0); return(true); }
/// <summary> /// <em>Automatic Retry Handling for Co-ordinated DB Access</em>: Calls the C# Delegate that encapsulates C# code that /// should be run inside the automatic retry handling scope that this Method provides. It does this a number of times /// in case the first call didn't work out, and once a set number of retries has been tried it returns (optionally, /// an Exception can be thrown if the number of retries was exceeded - this gets enabled by setting /// <paramref name="AWhenNotSuccessfulThrowSpecialException"/> to 'true'). /// </summary> /// <param name="AContext">Context that the Method gets called in, eg. name of screen (used only for logging, so /// don't Catalog.GetString it).</param> /// <param name="AServerCallSuccessful">Controls whether a retry (when false) or no retry (when true) gets /// performed.</param> /// <param name="AEncapsulatedServerCallCode">C# Delegate that encapsulates C# code that should be run inside the /// automatic server call retry handling scope that this Method provides.</param> /// <param name="AWhenNotSuccessfulThrowSpecialException">Whether /// <see cref="EDBAutoServerCallRetriesExceededException"/> should be thrown when the maximum number of retries /// has been exceeded, or not (Default=false). Should only be set to true in specific circumstances - the caller should /// normally just inspect its Variable that gets passed in into <paramref name="AServerCallSuccessful"/> to evaluate /// whether the call to this Method was within the retry attempts, or not.</param> /// <param name="AExceptionMessage">Optional message that the an <see cref="EDBAutoServerCallRetriesExceededException"/> /// Exception gets raised with. (Default = "").</param> public static void CoordinatedAutoRetryCall(string AContext, ref bool AServerCallSuccessful, Action AEncapsulatedServerCallCode, bool AWhenNotSuccessfulThrowSpecialException = false, string AExceptionMessage = null) { int MaxRetries = TAppSettingsManager.GetInt16("CoordinatedAutoRetryCallMaxRetries", 3); int ServerCallRetries = 0; do { try { // Execute the 'encapsulated C# code section' that the caller 'sends us' in the AEncapsulatedServerCallCode // Action delegate (0..n lines of code!) AEncapsulatedServerCallCode(); } catch (EDBTransactionBusyException) { ServerCallRetries++; if (TLogging.DebugLevel >= TLogging.DEBUGLEVEL_COORDINATED_DB_ACCESS) { TLogging.Log(TLogging.LOG_PREFIX_INFO + AContext + String.Format(": Server is busy, retrying acquisition of DB Transaction... (Retry #{0} of {1})", ServerCallRetries, MaxRetries)); } } catch (EDBCoordinatedDBAccessWaitingTimeExceededException) { ServerCallRetries++; if (TLogging.DebugLevel >= TLogging.DEBUGLEVEL_COORDINATED_DB_ACCESS) { TLogging.Log(TLogging.LOG_PREFIX_INFO + AContext + String.Format(": Server is busy, retrying... (Retry #{0} of {1})", ServerCallRetries, MaxRetries)); } } } while ((ServerCallRetries < MaxRetries) && (!(AServerCallSuccessful))); if (!AServerCallSuccessful) { if (TLogging.DebugLevel >= TLogging.DEBUGLEVEL_COORDINATED_DB_ACCESS) { TLogging.Log(TLogging.LOG_PREFIX_INFO + AContext + String.Format(": Server was too busy to service the request; the maximum number of retry attempts ({0}) were exhausted.", MaxRetries)); } if (AWhenNotSuccessfulThrowSpecialException) { throw new EDBAutoServerCallRetriesExceededException(AExceptionMessage ?? String.Empty); } } }
public CommandLineArgs() { _physicalPath = TAppSettingsManager.GetValue("physicalPath", string.Empty, false); // nant sets this _virtualPath = TAppSettingsManager.GetValue("virtualPath", string.Empty, false); _defaultPage = TAppSettingsManager.GetValue("defaultPage", string.Empty, false); _port = TAppSettingsManager.GetInt16("port", 0); // nant sets this _acceptRemoteConnection = TAppSettingsManager.GetBoolean("acceptRemoteConnection", false); _suppressStartUpMessages = TAppSettingsManager.GetBoolean("quiet", false); // nant usually sets this property to true _maxRuntimeInMinutes = TAppSettingsManager.GetInt16("maxRuntimeInMinutes", 0); _logPageRequests = TAppSettingsManager.GetBoolean("logPageRequests", true); // you can use the config to turn loggin OFF _useFullUI = TAppSettingsManager.GetBoolean("useFullUI", false); // we will only use the full UI if specified or if no port or path _logfilePath = TAppSettingsManager.GetValue("logfilePath", string.Empty, false); // we will use default location }
/// <summary> /// modified version taken from Ict.Petra.Server.App.Main::TServerManager /// </summary> private TDataBase EstablishDBConnectionAndReturnIt(string AConnectionName = null, bool ALogNumberOfConnections = false) { TDataBase ReturnValue; if (ALogNumberOfConnections) { if (FDBType == TDBType.PostgreSQL) { TLogging.Log(" EstablishDBConnectionAndReturnIt: Number of open DB Connections on PostgreSQL BEFORE Connecting to Database: " + TDataBase.GetNumberOfDBConnections(FDBType) + TDataBase.GetDBConnectionName(AConnectionName)); } } TLogging.Log(" EstablishDBConnectionAndReturnIt: Establishing connection to Database..." + TDataBase.GetDBConnectionName(AConnectionName)); ReturnValue = new TDataBase(); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 10); try { ReturnValue.EstablishDBConnection(FDBType, TAppSettingsManager.GetValue("Server.DBHostOrFile"), TAppSettingsManager.GetValue("Server.DBPort"), TAppSettingsManager.GetValue("Server.DBName"), TAppSettingsManager.GetValue("Server.DBUserName"), TAppSettingsManager.GetValue("Server.DBPassword"), "", AConnectionName); } catch (Exception Exc) { TLogging.Log(" EstablishDBConnectionAndReturnIt: Encountered Exception while trying to establish connection to Database " + TDataBase.GetDBConnectionName(AConnectionName) + Environment.NewLine + Exc.ToString()); throw; } TLogging.Log(" EstablishDBConnectionAndReturnIt: Connected to Database." + ReturnValue.GetDBConnectionIdentifier()); if (ALogNumberOfConnections) { if (FDBType == TDBType.PostgreSQL) { TLogging.Log(" EstablishDBConnectionAndReturnIt: Number of open DB Connections on PostgreSQL AFTER Connecting to Database: " + TDataBase.GetNumberOfDBConnections(FDBType) + ReturnValue.GetDBConnectionIdentifier()); } } return(ReturnValue); }
/// <summary> /// setup the smtp client from the config file or command line parameters /// </summary> public TSmtpSender() { //Set up SMTP client String EmailDirectory = ""; if (TAppSettingsManager.HasValue("OutputEMLToDirectory")) { EmailDirectory = TAppSettingsManager.GetValue("OutputEMLToDirectory"); } Initialise( TAppSettingsManager.GetValue("SmtpHost"), TAppSettingsManager.GetInt16("SmtpPort", 25), TAppSettingsManager.GetBoolean("SmtpEnableSsl", false), TAppSettingsManager.GetValue("SmtpUser", ""), TAppSettingsManager.GetValue("SmtpPassword", ""), EmailDirectory); }
// establish connection to database public static bool InitDBConnection( string ADBFile, string ADBPassword) { db = new TDataBase(); new TLogging("debug.log"); TLogging.DebugLevel = TAppSettingsManager.GetInt16("DebugLevel", 0); db.EstablishDBConnection(TDBType.SQLite, ADBFile, "", "", "", ADBPassword, ""); DBAccess.GDBAccessObj = db; return(true); }
/// <summary> /// initialise the server once for everyone /// </summary> public static bool Init() { if (TheServerManager == null) { // make sure the correct config file is used new TAppSettingsManager(AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "web.config"); new TSrvSetting(); new TLogging(TSrvSetting.ServerLogFile); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); Catalog.Init(); TheServerManager = "test"; TLogging.Log("Server has been initialised"); return(true); } return(false); }
/// <summary> /// modified version taken from Ict.Petra.Server.App.Main::TServerManager /// </summary> private void EstablishDBConnection() { TLogging.Log(" Connecting to Database..."); DBAccess.GDBAccessObj = new TDataBase(); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 10); try { 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"), ""); } catch (Exception) { throw; } TLogging.Log(" Connected to Database."); }
/// <summary> /// If the Email preferences are not already in UserDefaults, this loads them. /// </summary> public static void LoadEmailDefaults() { if (!TUserDefaults.HasDefault("SmtpHost")) { TUserDefaults.SetDefault("SmtpHost", TAppSettingsManager.GetValue("SmtpHost", "")); } if (!TUserDefaults.HasDefault("SmtpPort")) { TUserDefaults.SetDefault("SmtpPort", TAppSettingsManager.GetInt16("SmtpPort", -1)); } if (!TUserDefaults.HasDefault("SmtpUseSsl")) { TUserDefaults.SetDefault("SmtpUseSsl", TAppSettingsManager.GetValue("SmtpEnableSsl", false)); } if (!TUserDefaults.HasDefault("SmtpUser")) { TUserDefaults.SetDefault("SmtpUser", TAppSettingsManager.GetValue("SmtpUser", "")); } if (!TUserDefaults.HasDefault("SmtpPassword")) { TUserDefaults.SetDefault("SmtpPassword", TAppSettingsManager.GetValue("SmtpPassword", "")); } if (!TUserDefaults.HasDefault("SmtpEnableSsl")) { TUserDefaults.SetDefault("SmtpEnableSsl", TAppSettingsManager.GetBoolean("SmtpEnableSsl", false)); } if (!TUserDefaults.HasDefault("SmtpFromAccount")) { TUserDefaults.SetDefault("SmtpFromAccount", TAppSettingsManager.GetValue("SmtpFromAccount", "")); } if (!TUserDefaults.HasDefault("SmtpDisplayName")) { TUserDefaults.SetDefault("SmtpDisplayName", TAppSettingsManager.GetValue("SmtpDisplayName", "")); } if (!TUserDefaults.HasDefault("SmtpReplyTo")) { TUserDefaults.SetDefault("SmtpReplyTo", TAppSettingsManager.GetValue("SmtpReplyTo", "")); } if (!TUserDefaults.HasDefault("SmtpCcTo")) { TUserDefaults.SetDefault("SmtpCcTo", TAppSettingsManager.GetValue("SmtpCcTo", "")); } if (!TUserDefaults.HasDefault("SmtpEmailBody")) { TUserDefaults.SetDefault("SmtpEmailBody", TAppSettingsManager.GetValue("SmtpEmailBody", "")); } if (!TUserDefaults.HasDefault("SmtpSendAsAttachment")) { TUserDefaults.SetDefault("SmtpSendAsAttachment", TAppSettingsManager.GetValue("SmtpSendAsAttachment", "")); } }
/// <summary> /// initialise the server once for everyone /// </summary> public static bool Init() { if (ConfigFileName == string.Empty) { // make sure the correct config file is used if (Environment.CommandLine.Contains("/appconfigfile=")) { // this happens when we use fastcgi-mono-server4 ConfigFileName = Environment.CommandLine.Substring( Environment.CommandLine.IndexOf("/appconfigfile=") + "/appconfigfile=".Length); if (ConfigFileName.IndexOf(" ") != -1) { ConfigFileName = ConfigFileName.Substring(0, ConfigFileName.IndexOf(" ")); } } else { // this is the normal behaviour when running with local http server ConfigFileName = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "web.config"; } } new TAppSettingsManager(ConfigFileName); new TLogging(TSrvSetting.ServerLogFile); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); TSession.InitThread(); if (TLogging.DebugLevel >= 4) { TLogging.Log("TOpenPetraOrgSessionManager.Init"); TLogging.Log(HttpContext.Current.Request.PathInfo); } if (HttpContext.Current != null) { HttpContext.Current.Server.ScriptTimeout = Convert.ToInt32( TimeSpan.FromMinutes(TAppSettingsManager.GetInt32("WebRequestTimeOutInMinutes", 15)). TotalSeconds); } // if the Login Method is called: reset cookie, ignore any old session if ((HttpContext.Current != null) && (HttpContext.Current.Request.PathInfo == "/Login")) { TSession.CloseSession(); TSession.InitThread(); } if (TServerManager.TheServerManager == null) { Catalog.Init(); TServerManager.TheServerManager = new TServerManager(); try { // initialise the cached tables TSetupDelegates.Init(); } catch (Exception e) { TLogging.Log(e.Message); TLogging.Log(e.StackTrace); throw; } TLogging.Log("Server has been initialised"); return(true); } if (DomainManager.CurrentClient != null) { if (DomainManager.CurrentClient.FAppDomainStatus == TSessionStatus.adsStopped) { TLogging.Log("There is an attempt to reconnect to stopped session: " + DomainManager.CurrentClient.ClientName); if (HttpContext.Current.Request.PathInfo == "/IsUserLoggedIn") { // we want a clean json response saying the user is not logged in TSession.CloseSession(); return(true); } Dictionary <string, object> result = new Dictionary <string, object>(); result.Add("resultcode", "error"); result.Add("error", THTTPUtils.SESSION_ALREADY_CLOSED); HttpContext.Current.Response.Status = "403 " + THTTPUtils.SESSION_ALREADY_CLOSED; HttpContext.Current.Response.Write(JsonConvert.SerializeObject(result)); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close(); HttpContext.Current.Response.End(); return(false); } // TLogging.Log("Init(): WebService Method name that got called: " + HttpContext.Current.Request.PathInfo); if (HttpContext.Current.Request.PathInfo != "/PollClientTasks") { DomainManager.CurrentClient.UpdateLastAccessTime(); } } return(false); }
/// <summary> /// main function /// </summary> /// <param name="args"></param> public static void Main(string[] args) { new TAppSettingsManager(false); new TLogging("Ict.Tools.DataDumpPetra2.log"); if (!TAppSettingsManager.HasValue("debuglevel")) { Console.Error.WriteLine("dumps one single table or all tables from Progress Petra 2.3 into Postgresql SQL load format"); Console.Error.WriteLine( "usage: Ict.Tools.DataDumpPetra2 -debuglevel:<0..10> -table:<single table or all> -oldpetraxml:<path and filename of old petra.xml> -newpetraxml:<path and filename of petra.xml>"); Console.Error.WriteLine("will default to processing all tables, and using petra23.xml and petra.xml from the current directory"); Console.Error.WriteLine( "usage for creating fulldump23.p: Ict.Tools.DataDumpPetra2 -operation:createProgressCode"); Console.Error.WriteLine(""); } try { TLogging.DebugLevel = TAppSettingsManager.GetInt16("debuglevel", 0); if (TAppSettingsManager.GetValue("operation", false) == "createProgressCode") { TCreateFulldumpProgressCode createProgressCode = new TCreateFulldumpProgressCode(); createProgressCode.GenerateFulldumpCode(); return; } if (TAppSettingsManager.GetValue("clean", "false") == "true") { TLogging.Log("deleting all resulting files..."); // delete sql.gz files, also _*.txt string[] FilesToDelete = Directory.GetFiles(TAppSettingsManager.GetValue("fulldumpPath", "fulldump"), "*.sql.gz"); foreach (string file in FilesToDelete) { File.Delete(file); } FilesToDelete = Directory.GetFiles(TAppSettingsManager.GetValue("fulldumpPath", "fulldump"), "_*.txt"); foreach (string file in FilesToDelete) { File.Delete(file); } } StringCollection tables = StringHelper.StrSplit(TAppSettingsManager.GetValue("table", ""), ","); // the upgrade process is split into two steps, to make testing quicker // Step 1: dump from Progress Petra 2.3 to CSV files, write gz files to keep size of fulldump small // this takes about 7 minutes for the german database // use the generated fulldump23.p if ((TAppSettingsManager.GetValue("operation", "dump23") == "dump23") && File.Exists("fulldump23.r")) { TDumpProgressToPostgresql dumper = new TDumpProgressToPostgresql(); if (tables.Count == 0) { dumper.DumpTablesToCSV(String.Empty); } else { foreach (var ProcessTable in tables) { dumper.DumpTablesToCSV(ProcessTable); } } } // Step 2: produce one or several sql load files for PostgreSQL // can be called independant from first step: for all tables or just one table // for tables merged into one: append to previous file // this takes 50 minutes on my virtual machine on the german server for all tables. on a faster machine, it is only 25 minutes if (TAppSettingsManager.GetValue("operation", "load30") == "load30") { TDumpProgressToPostgresql dumper = new TDumpProgressToPostgresql(); if (tables.Count == 0) { dumper.LoadTablesToPostgresql(String.Empty); } else { foreach (var ProcessTable in tables) { dumper.LoadTablesToPostgresql(ProcessTable); } } } // Step 3: concatenate all existing sql.gz files into one load sql file, gzipped. in the correct order if (TAppSettingsManager.GetValue("operation", "createSQL") == "createSQL") { TDumpProgressToPostgresql dumper = new TDumpProgressToPostgresql(); if (tables.Count == 0) { dumper.CreateNewSQLFile(String.Empty); } else { foreach (var ProcessTable in tables) { dumper.CreateNewSQLFile(ProcessTable); } } } // TODO: also anonymize the names of the partners (use random names from external list of names)? what about amounts? } catch (Exception e) { TLogging.Log(e.Message); if (e.InnerException != null) { TLogging.Log(e.InnerException.Message); } TLogging.Log(e.StackTrace); } }
public void Init() { new TLogging("../../log/test.log"); new TAppSettingsManager("../../etc/TestServer.config"); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Client.DebugLevel", 0); }
/// <summary> /// Loads settings from .NET Configuration File and Command Line. /// /// </summary> /// <returns>void</returns> public TClientSettings() : base() { // // Parse settings from the Application Configuration File // UPathLog = GetPathLog(); UDebugLevel = TAppSettingsManager.GetInt16("Client.DebugLevel", 0); TLogging.DebugLevel = UDebugLevel; UBehaviourSeveralClients = "OnlyOneWithQuestion"; if (TAppSettingsManager.HasValue("BehaviourSeveralClients")) { UBehaviourSeveralClients = TAppSettingsManager.GetValue("BehaviourSeveralClients"); } UDelayedDataLoading = TAppSettingsManager.GetBoolean("DelayedDataLoading", false); UReportingPathReportSettings = GetUserPath("Reporting.PathReportSettings", ""); UReportingPathReportUserSettings = GetUserPath("Reporting.PathReportUserSettings", ""); UServerPollIntervalInSeconds = TAppSettingsManager.GetInt32("ServerPollIntervalInSeconds", 5); UServerObjectKeepAliveIntervalInSeconds = TAppSettingsManager.GetInt32("ServerObjectKeepAliveIntervalInSeconds", 10); URemoteDataDirectory = TAppSettingsManager.GetValue("RemoteDataDirectory"); URemoteTmpDirectory = TAppSettingsManager.GetValue("RemoteTmpDirectory"); URunAsStandalone = TAppSettingsManager.GetBoolean("RunAsStandalone", false); URunAsRemote = TAppSettingsManager.GetBoolean("RunAsRemote", false); UPetra_Path_RemotePatches = ""; UPetra_Path_Dat = ""; UPetra_Path_Patches = ""; UPetraWebsite_Link = TAppSettingsManager.GetValue("OpenPetra.Website", "http://www.openpetra.org"); UPetraPatches_Link = TAppSettingsManager.GetValue("OpenPetra.Path.RemotePatches", "http://www.example.org/index.php?page=OpenPetraPatches"); UPetraSupportTeamEmail = TAppSettingsManager.GetValue("OpenPetra.SupportTeamEmail", String.Empty); if (URunAsStandalone == true) { UPetraServerAdmin_Configfile = TAppSettingsManager.GetValue("PetraServerAdmin.Configfile"); UPetraServer_Configfile = TAppSettingsManager.GetValue("PetraServer.Configfile"); UPetra_Path_Patches = Petra_Path_Bin + Path.DirectorySeparatorChar + "sa-patches"; UPostgreSql_BaseDir = TAppSettingsManager.GetValue("PostgreSQLServer.BaseDirectory"); UPostgreSql_DataDir = TAppSettingsManager.GetValue("PostgreSQLServer.DataDirectory"); } if (URunAsRemote == true) { UPetra_Path_Patches = GetUserPath("OpenPetra.Path.Patches", ""); UPetra_Path_Dat = GetUserPath("OpenPetra.Path.Dat", ""); UPetra_Path_RemotePatches = TAppSettingsManager.GetValue("OpenPetra.Path.RemotePatches"); } if ((!URunAsRemote) && (!URunAsStandalone)) { // network version UPetra_Path_Patches = Petra_Path_Bin + Path.DirectorySeparatorChar + "net-patches"; } if (TAppSettingsManager.HasValue("StartupMessage")) { UCustomStartupMessage = TAppSettingsManager.GetValue("StartupMessage"); } UHTMLHelpBaseURLLocal = TAppSettingsManager.GetValue("HTMLHelpBaseURLLocal", String.Empty); UHTMLHelpBaseURLOnInternet = TAppSettingsManager.GetValue("HTMLHelpBaseURLOnInternet", String.Empty); ULocalHTMLHelp = TAppSettingsManager.GetBoolean("LocalHTMLHelp", true); }
/// <summary> /// Set the session id for this current thread. /// Each request has its own thread. /// Threads can be reused for different users. /// </summary> public static void InitThread(string AThreadDescription, string AConfigFileName, string ASessionID = null) { TLogWriter.ResetStaticVariables(); TLogging.ResetStaticVariables(); new TAppSettingsManager(AConfigFileName); new TLogging(TSrvSetting.ServerLogFile); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); string httprequest = ""; if ((HttpContext.Current != null) && (HttpContext.Current.Request != null)) { httprequest = " for path " + HttpContext.Current.Request.PathInfo; } TLogging.LogAtLevel(4, AThreadDescription + ": Running InitThread for thread id " + Thread.CurrentThread.ManagedThreadId.ToString() + httprequest); FSessionID = ASessionID; FSessionValues = null; string sessionID; if (ASessionID == null) { sessionID = FindSessionID(); } else { sessionID = ASessionID; } TDataBase db = null; // avoid dead lock on parallel logins FDeleteSessionMutex.WaitOne(); try { db = ConnectDB("SessionInitThread"); TDBTransaction t = new TDBTransaction(); bool SubmissionOK = false; bool newSession = false; db.WriteTransaction(ref t, ref SubmissionOK, delegate { // get the session ID, or start a new session // load the session values from the database // update the session last access in the database // clean old sessions newSession = InitSession(sessionID, t); SubmissionOK = true; }); if (newSession) { // use a separate transaction to clean old sessions db.WriteTransaction(ref t, ref SubmissionOK, delegate { CleanOldSessions(t); SubmissionOK = true; }); } } finally { db.CloseDBConnection(); FDeleteSessionMutex.ReleaseMutex(); } }
public static void Main(string[] args) { try { new TAppSettingsManager(false); if (Directory.Exists("log")) { new TLogging("log/generatewinforms.log"); } else { new TLogging("generatewinforms.log"); } TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); if (!TAppSettingsManager.HasValue("op")) { Console.WriteLine("call: GenerateWinForms -op:generate -ymlfile:c:\\test.yaml -petraxml:petra.xml -localisation:en"); Console.WriteLine(" or: GenerateWinForms -op:generate -ymldir:c:\\myclient -petraxml:petra.xml -localisation:en"); Console.WriteLine(" or: GenerateWinForms -op:clean -ymldir:c:\\myclient"); Console.WriteLine(" or: GenerateWinForms -op:preview"); Console.Write("Press any key to continue . . . "); Console.ReadLine(); Environment.Exit(-1); return; } // calculate ICTPath from ymlfile path string fullYmlfilePath = Path.GetFullPath(TAppSettingsManager.GetValue("ymlfile", TAppSettingsManager.GetValue("ymldir", false))).Replace( "\\", "/"); if (!fullYmlfilePath.Contains("csharp/ICT")) { Console.WriteLine("ymlfile must be below the csharp/ICT directory"); } CSParser.ICTPath = fullYmlfilePath.Substring(0, fullYmlfilePath.IndexOf("csharp/ICT") + "csharp/ICT".Length); if (TAppSettingsManager.GetValue("op") == "clean") { if (!Directory.Exists(fullYmlfilePath)) { throw new Exception("invalid directory " + fullYmlfilePath); } // delete all generated files in the directory foreach (string file in System.IO.Directory.GetFiles(fullYmlfilePath, "*.yaml", SearchOption.AllDirectories)) { DeleteGeneratedFile(file, "-generated.cs"); DeleteGeneratedFile(file, "-generated.Designer.cs"); DeleteGeneratedFile(file, "-generated.resx"); } } else if (TAppSettingsManager.GetValue("op") == "preview") { string SelectedLocalisation = null; // none selected by default; winforms autosize works quite well if (TAppSettingsManager.HasValue("localisation")) { SelectedLocalisation = TAppSettingsManager.GetValue("localisation"); } TDataBinding.FPetraXMLStore = new TDataDefinitionStore(); Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true)); TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true)); parser.ParseDocument(ref TDataBinding.FPetraXMLStore, true, true); TFrmYamlPreview PreviewWindow = new TFrmYamlPreview( TAppSettingsManager.GetValue("ymlfile"), SelectedLocalisation); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); Application.ThreadException += new ThreadExceptionEventHandler(UnhandledThreadExceptionHandler); PreviewWindow.ShowDialog(); return; } else if (TAppSettingsManager.GetValue("op") == "generate") { string SelectedLocalisation = null; // none selected by default; winforms autosize works quite well if (TAppSettingsManager.HasValue("localisation")) { SelectedLocalisation = TAppSettingsManager.GetValue("localisation"); } TDataBinding.FPetraXMLStore = new TDataDefinitionStore(); Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true)); TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true)); parser.ParseDocument(ref TDataBinding.FPetraXMLStore, true, true); string ymlfileParam = TAppSettingsManager.GetValue("ymlfile", TAppSettingsManager.GetValue("ymldir", false)); if (ymlfileParam.Contains(",")) { StringCollection collection = StringHelper.StrSplit(ymlfileParam, ","); foreach (string file in collection) { ProcessFile(file, SelectedLocalisation); } } else if (System.IO.Directory.Exists(ymlfileParam)) { string[] yamlfiles = System.IO.Directory.GetFiles(ymlfileParam, "*.yaml", SearchOption.AllDirectories); // sort the files so that the deepest files are first processed, // since the files higher up are depending on them // eg. FinanceMain.yaml needs to check for GLBatch-generated.cs List <string> yamlFilesSorted = new List <string>(yamlfiles.Length); foreach (string file in yamlfiles) { yamlFilesSorted.Add(file); } yamlFilesSorted.Sort(new YamlFileOrderComparer()); foreach (string file in yamlFilesSorted) { // only look for main files, not language specific files (*.xy-XY.yaml or *.xy.yaml) if (TProcessYAMLForms.IgnoreLanguageSpecificYamlFile(file)) { continue; } Console.WriteLine("working on " + file); ProcessFile(file, SelectedLocalisation); } } else { ProcessFile(ymlfileParam, SelectedLocalisation); } } } catch (Exception e) { string commandline = ""; foreach (string s in args) { commandline += s + " "; } Console.WriteLine("Problem while processing " + commandline); Console.WriteLine(e.GetType().ToString() + ": " + e.Message); if (e.InnerException != null) { Console.WriteLine(e.InnerException.GetType().ToString() + ": " + e.InnerException.Message); } // do not print a stacktrace for custom generated exception, eg. by the YML parser if ((e.GetType() != typeof(System.Exception)) || (TLogging.DebugLevel > 0)) { Console.WriteLine(e.StackTrace); } Environment.Exit(-1); } }
/// <summary> /// Executes the tests (main method of this executable!). /// </summary> public static void RunTest() { XmlNode startNode; XmlNode curGroup; Thread groupThread; TestGroup myGroup; String testcase; new TAppSettingsManager(true); testcase = TAppSettingsManager.GetValue("testcase"); Global.StartClientID = TAppSettingsManager.GetInt16("startclientid"); rnd = new System.Random(DateTime.Now.Millisecond); // Init try { parser = new TXMLParser(TAppSettingsManager.GetValue("testscript"), false); startNode = parser.GetDocument().DocumentElement; } catch (Exception E) { System.Console.WriteLine("{0}: trouble in RunTest", DateTime.Now.ToLongTimeString()); System.Console.WriteLine("{0}: {1}", DateTime.Now.ToLongTimeString(), E.Message); return; } new TLogging(@"..\..\log\PetraMultiStart.log"); TheConnector = new Ict.Petra.ServerAdmin.App.Core.TConnector(); TheConnector.GetServerConnection(TAppSettingsManager.ConfigFileName, out TRemote); CreateTestUsers(); if (startNode.Name.ToLower() == "tests") { startNode = startNode.FirstChild; while ((startNode != null) && (startNode.Name.ToLower() == "test") && (TXMLParser.GetAttribute(startNode, "name") != testcase)) { startNode = startNode.NextSibling; } } if (startNode == null) { Console.WriteLine("{0}: cannot find testcase {1}", DateTime.Now.ToLongTimeString(), testcase); return; } while (true) { // restart the whole test scenario if (startNode.Name.ToLower() == "test") { Global.Filename = TXMLParser.GetAttribute(startNode, "app"); // kill instances of previous test KillAllProcesses(Global.Filename.Substring(0, Global.Filename.IndexOf('.'))); Global.Configfile = TXMLParser.GetAttribute(startNode, "config"); curGroup = startNode.FirstChild; while ((curGroup != null) && (curGroup.Name == "clientgroup")) { if (TXMLParser.GetBoolAttribute(curGroup, "active", true) != false) { myGroup = new TestGroup(curGroup); groupThread = new Thread(myGroup.Run); groupThread.Start(); } curGroup = curGroup.NextSibling; } } Thread.CurrentThread.Join(); System.Console.WriteLine("{0}: All threads have stopped", DateTime.Now.ToLongTimeString()); if (TXMLParser.GetBoolAttribute(startNode, "loop", true) == false) { return; } Thread.Sleep(5 * 60 * 1000); // wait for 5 minutes before restarting } }
/// <summary> /// initialise the server for each Web Request /// </summary> private static bool Init() { string ConfigFileName = string.Empty; // make sure the correct config file is used string Instance = HttpContext.Current.Request.Url.ToString().Replace("http://", "").Replace("https://", ""); Instance = Instance.Substring(0, Instance.IndexOf(".")).Replace("op_", "op").Replace("op", "op_"); // for demo etc if (!Instance.StartsWith("op_")) { Instance = "op_" + Instance; } ConfigFileName = "/home/" + Instance + "/etc/PetraServerConsole.config"; if (File.Exists(ConfigFileName)) { // we are in a multi tenant hosting scenario } else if (Environment.CommandLine.Contains("/appconfigfile=")) { // this happens when we use fastcgi-mono-server4 ConfigFileName = Environment.CommandLine.Substring( Environment.CommandLine.IndexOf("/appconfigfile=") + "/appconfigfile=".Length); if (ConfigFileName.IndexOf(" ") != -1) { ConfigFileName = ConfigFileName.Substring(0, ConfigFileName.IndexOf(" ")); } } else { // this is the normal behaviour when running with local http server ConfigFileName = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "web.config"; } TLogWriter.ResetStaticVariables(); TLogging.ResetStaticVariables(); TTypedDataTable.ResetStaticVariables(); TPdfPrinter.ResetStaticVariables(); THTTPUtils.ResetStaticVariables(); TSharedDataCache.TMPartner.ResetStaticVariables(); TServerManagerBase.ResetStaticVariables(); TClientManager.ResetStaticVariables(); new TAppSettingsManager(ConfigFileName); new TLogging(TSrvSetting.ServerLogFile); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); TSession.InitThread(); if (TLogging.DebugLevel >= 4) { TLogging.Log("TOpenPetraOrgSessionManager.Init"); TLogging.Log(HttpContext.Current.Request.PathInfo); } if (HttpContext.Current != null) { HttpContext.Current.Server.ScriptTimeout = Convert.ToInt32( TimeSpan.FromMinutes(TAppSettingsManager.GetInt32("WebRequestTimeOutInMinutes", 15)). TotalSeconds); } // if the Login Method is called: reset cookie, ignore any old session if ((HttpContext.Current != null) && (HttpContext.Current.Request.PathInfo == "/Login")) { TSession.CloseSession(); TSession.InitThread(); } Catalog.Init(); ErrorCodeInventory.Init(); ErrorCodeInventory.BuildErrorCodeInventory(typeof(Ict.Petra.Shared.PetraErrorCodes)); ErrorCodeInventory.BuildErrorCodeInventory(typeof(Ict.Common.Verification.TStringChecks)); TServerManager.TheServerManager = new TServerManager(); // initialise the cached tables and the delegates TSetupDelegates.Init(); TLogging.LogAtLevel(4, "Server has been initialised"); return(true); }
/// <summary> /// Initialises Logging and parses Server settings from different sources. /// /// </summary> public TServerManagerBase() : base() { new TAppSettingsManager(false); new TLogging(TAppSettingsManager.GetValue("Server.LogFile", false)); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); }
public static void Main(string[] args) { try { new TAppSettingsManager(false); if (Directory.Exists(TAppSettingsManager.GetValue("logPath"))) { new TLogging(TAppSettingsManager.GetValue("logPath") + "/generateextjsforms.log"); } else { new TLogging("generateextjsforms.log"); } TLogging.DebugLevel = TAppSettingsManager.GetInt16("DebugLevel", 0); if (!TAppSettingsManager.HasValue("ymlfile")) { Console.WriteLine("call: GenerateExtJsForms -ymlfile:c:\\test.yaml -petraxml:petra.xml -localisation:en"); Console.Write("Press any key to continue . . . "); Console.ReadLine(); Environment.Exit(-1); return; } // calculate ICTPath from ymlfile path string fullYmlfilePath = Path.GetFullPath(TAppSettingsManager.GetValue("ymlfile")).Replace("\\", "/"); string SelectedLocalisation = null; // none selected by default if (TAppSettingsManager.HasValue("localisation")) { SelectedLocalisation = TAppSettingsManager.GetValue("localisation"); } CSParser.ICTPath = fullYmlfilePath.Substring(0, fullYmlfilePath.IndexOf("csharp/ICT") + "csharp/ICT".Length); TDataBinding.FPetraXMLStore = new TDataDefinitionStore(); Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true)); TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true)); parser.ParseDocument(ref TDataBinding.FPetraXMLStore, true, true); string ymlfileParam = TAppSettingsManager.GetValue("ymlfile", true); if (ymlfileParam.Contains(",")) { StringCollection collection = StringHelper.StrSplit(ymlfileParam, ","); foreach (string file in collection) { ProcessFile(file, SelectedLocalisation); } } else if (System.IO.Directory.Exists(ymlfileParam)) { ProcessDirectory(ymlfileParam, SelectedLocalisation); } else { ProcessFile(ymlfileParam, SelectedLocalisation); } // TODO: generate localised versions // TODO: generate minified version. either using YUICompressor, or simple string operation? // Or should the xsp server do that? generate js files on the fly? figure out the language of the client? cache files? } catch (Exception e) { string commandline = ""; foreach (string s in args) { commandline += s + " "; } Console.WriteLine("Problem while processing " + commandline); Console.WriteLine(e.GetType().ToString() + ": " + e.Message); if (e.InnerException != null) { Console.WriteLine(e.InnerException.GetType().ToString() + ": " + e.InnerException.Message); } // do not print a stacktrace for custom generated exception, eg. by the YML parser if ((e.GetType() != typeof(System.Exception)) || (TLogging.DebugLevel > 0)) { Console.WriteLine(e.StackTrace); } Environment.Exit(-1); } }
/// <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> /// initialise the server once for everyone /// </summary> public static bool Init() { if (ConfigFileName == string.Empty) { // make sure the correct config file is used if (Environment.CommandLine.Contains("/appconfigfile=")) { // this happens when we use fastcgi-mono-server4 ConfigFileName = Environment.CommandLine.Substring( Environment.CommandLine.IndexOf("/appconfigfile=") + "/appconfigfile=".Length); if (ConfigFileName.IndexOf(" ") != -1) { ConfigFileName = ConfigFileName.Substring(0, ConfigFileName.IndexOf(" ")); } } else { // this is the normal behaviour when running with local http server ConfigFileName = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "web.config"; } } new TAppSettingsManager(ConfigFileName); new TSrvSetting(); new TLogging(TSrvSetting.ServerLogFile); TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0); if (HttpContext.Current != null) { HttpContext.Current.Server.ScriptTimeout = Convert.ToInt32( TimeSpan.FromMinutes(TAppSettingsManager.GetInt32("WebRequestTimeOutInMinutes", 15)). TotalSeconds); } // if the Login Method is called: reset cookie, ignore any old session if ((HttpContext.Current != null) && (HttpContext.Current.Request.PathInfo == "/Login")) { TSession.Clear(); } if (TServerManager.TheServerManager == null) { Catalog.Init(); TServerManager.TheServerManager = new TServerManager(); try { TServerManager.TheCastedServerManager.EstablishDBConnection(); TSystemDefaultsCache.GSystemDefaultsCache = new TSystemDefaultsCache(); DomainManager.GetSiteKeyFromSystemDefaultsCacheDelegate = @TSystemDefaultsCache.GSystemDefaultsCache.GetSiteKeyDefault; TLanguageCulture.Init(); // initialise the cached tables TSetupDelegates.Init(); TUserDefaults.InitializeUnit(); } catch (Exception e) { TLogging.Log(e.Message); TLogging.Log(e.StackTrace); throw; } TLogging.Log("Server has been initialised"); return(true); } if (DomainManager.CurrentClient != null) { if (DomainManager.CurrentClient.FAppDomainStatus == TSessionStatus.adsStopped) { TLogging.Log("There is an attempt to reconnect to stopped session: " + DomainManager.CurrentClient.ClientName); HttpContext.Current.Response.Status = "404 " + THTTPUtils.SESSION_ALREADY_CLOSED; HttpContext.Current.Response.End(); } // TLogging.Log("Init(): WebService Method name that got called: " + HttpContext.Current.Request.PathInfo); if (HttpContext.Current.Request.PathInfo != "/PollClientTasks") { DomainManager.CurrentClient.UpdateLastAccessTime(); } } return(false); }