Ejemplo n.º 1
0
            protected override WebRequest GetWebRequest(Uri address)
            {
                TLogging.LogAtLevel(1, "GetWebRequest: got called for URI: " + address.ToString());
                HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);

                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; OpenPetraFatClient)";

                request.Timeout = Convert.ToInt32(
                    TimeSpan.FromMinutes(TAppSettingsManager.GetInt32("WebRequestTimeOutInMinutes", 15)).
                    TotalMilliseconds);

                // TODO Set HttpWebRequest.KeepAlive property to false to avoid  'The request was aborted: The request was canceled.' when multiple Threads run on one TCP Session ?????
                // see http://www.jaxidian.org/update/2007/05/05/8/

                var castRequest = request as HttpWebRequest;

                if (castRequest != null)
                {
                    castRequest.CookieContainer = this.CookieContainer;

                    foreach (Cookie IndivCookie in castRequest.CookieContainer.GetCookies(address))
                    {
                        TLogging.LogAtLevel(1, "GetWebRequest: castRequest.CookieContainer cookie\r\n" +
                                            "Name: " + IndivCookie.Name + "\r\n" +
                                            "Value: " + IndivCookie.Value + "\r\n" +
                                            "Path: " + IndivCookie.Path + "\r\n" +
                                            "Domain: " + IndivCookie.Domain);
                    }
                }

                return(request);
            }
Ejemplo n.º 2
0
        public static void GetServerSmtpSettings(out string ASMTPHost,
                                                 out int ASMTPPort,
                                                 out bool AEnableSsl,
                                                 out string ALoginUsername,
                                                 out string ALoginPassword)
        {
            ASMTPHost      = TAppSettingsManager.GetValue("SmtpHost", "");
            ASMTPPort      = TAppSettingsManager.GetInt32("SmtpPort", 25);
            AEnableSsl     = TAppSettingsManager.GetBoolean("SmtpEnableSsl", false);
            ALoginUsername = null;
            ALoginPassword = null;

            // Validate the host name.  It should not be the content of an unmodified config file.
            if (ASMTPHost.Contains("example.org"))
            {
                ASMTPHost = string.Empty;
                return;
            }

            if (TAppSettingsManager.GetBoolean("SmtpRequireCredentials", false) == true)
            {
                // We give the client the details of the OP Email user.
                // The password is converted from a byte array (rather than being compiled into this DLL as plain text).
                // The username and password are stored in different server DLL's.
                ALoginUsername = MSysManConstants.EMAIL_USER_LOGIN_NAME;
                ALoginPassword = Encoding.ASCII.GetString(EmailUserPassword);
            }
        }
Ejemplo n.º 3
0
            /// <summary>
            /// Constructor for passing in parameters.
            /// </summary>
            public TClientStillAliveCheck(TConnectedClient AConnectedClient,
                                          TClientServerConnectionType AClientServerConnectionType,
                                          TDelegateTearDownAppDomain ATearDownAppDomain,
                                          string AUser = "")
            {
                FClientObject = AConnectedClient;
                ClientName    = FClientObject.ClientName;

                // Note: calls to TLogging here only go to the console. The log file doesn't get initialised in TLogging until TClientDomainManager.EstablishDBConnection()
                TLogging.LogAtLevel(10, "TClientStillAliveCheck (for ClientName '" + ClientName + "'') created");

                Int32 ClientStillAliveTimeout = TAppSettingsManager.GetInt32("Server.ClientKeepAliveTimeoutAfterXSeconds_LAN", 60);

                UClientStillAliveTimeout       = ClientStillAliveTimeout;
                UClientStillAliveCheckInterval = TAppSettingsManager.GetInt32("Server.ClientKeepAliveCheckIntervalInSeconds", 60);
                UTearDownAppDomain             = ATearDownAppDomain;
//                UTearDownAppDomainToken = ATearDownAppDomainToken;


                TLogging.LogAtLevel(2, "ClientStillAliveTimeout: " + ClientStillAliveTimeout.ToString() + "; " +
                                    "ClientKeepAliveCheckIntervalInSeconds: " + UClientStillAliveCheckInterval.ToString());

                // Start ClientStillAliveCheckThread
                UKeepServerAliveCheck                     = true;
                UClientStillAliveCheckThread              = new Thread(new ThreadStart(ClientStillAliveCheckThread));
                UClientStillAliveCheckThread.Name         = "ClientStillAliveCheckThread" + Guid.NewGuid().ToString();
                UClientStillAliveCheckThread.IsBackground = true;
                UClientStillAliveCheckThread.Start();

                TLogging.LogAtLevel(10, "TClientStillAliveCheck (for ClientName '" + ClientName + "'): started " + UClientStillAliveCheckThread.Name);
            }
Ejemplo n.º 4
0
        public static void Main(string[] args)
        {
            TCmdOpts cmd = new TCmdOpts();

            new TAppSettingsManager(false);

            TLogging.DebugLevel = TAppSettingsManager.GetInt32("debuglevel", 0);

            if (!cmd.IsFlagSet("formsdir"))
            {
                Console.WriteLine("call: " + sampleCall);
                return;
            }

            String FormsDir = cmd.GetOptValue("formsdir");

            try
            {
                CheckHTML(FormsDir);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(-1);
            }
        }
Ejemplo n.º 5
0
 public void Init()
 {
     //new TLogging("TestServer.log");
     TPetraServerConnector.Connect("../../etc/TestServer.config");
     FLedgerNumber = TAppSettingsManager.GetInt32("LedgerNumber", 43);
     TLogging.Log("Ledger Number = " + FLedgerNumber);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// post a request to a website. used for Connectors
        /// </summary>
        public static string PostRequest(string url, NameValueCollection parameters)
        {
            if (TLogging.DebugLevel > 0)
            {
                LogRequest(url, parameters);
            }

            try
            {
                // config parameter value for how many times a connection should be attempted until the web call fails
                return(WebClientUploadValues(url, parameters, TAppSettingsManager.GetInt32("HTTPUtils.PostRequests", 10)));
            }
            catch (System.Net.WebException e)
            {
                TLogging.Log("Trying to download: ");
                LogRequest(url, parameters);
                TLogging.Log(e.Message);
                TLogging.Log("Error message from server:");
                TLogging.Log(e.ToString());

                if (e.Response != null)
                {
                    StreamReader sr = new StreamReader(e.Response.GetResponseStream());
                    TLogging.Log(sr.ReadToEnd());
                    sr.Close();
                }
            }

            return(String.Empty);
        }
Ejemplo n.º 7
0
        /// main method
        public static void Main(string[] args)
        {
            new TAppSettingsManager();
            new TLogging();

            if (!TAppSettingsManager.HasValue("YmlGzFile") || !TAppSettingsManager.HasValue("Action"))
            {
                TLogging.Log("sample call: -C:../../etc/TestServer.config -Action:dump -YmlGzFile:test.yml.gz");
                TLogging.Log("sample call: -C:../../etc/TestServer.config -Action:load -YmlGzFile:test.yml.gz");
                Environment.Exit(-1);
            }

            string YmlFile = TAppSettingsManager.GetValue("YmlGzFile");
            string Action  = TAppSettingsManager.GetValue("Action");

            TLogging.DebugLevel = TAppSettingsManager.GetInt32("Server.DebugLevel", 0);
            TSession.InitThread();

            TServerManager.TheServerManager = new TServerManager();

            bool ExitWithError = false;

            try
            {
                if (Action == "dump")
                {
                    if (!DumpYmlGz(YmlFile))
                    {
                        ExitWithError = true;
                    }
                }
                else if (Action == "load")
                {
                    if (!LoadYmlGz(YmlFile))
                    {
                        ExitWithError = true;
                    }
                }
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                ExitWithError = true;
            }

            TServerManager.TheServerManager.StopServer();

            if (TAppSettingsManager.GetValue("interactive", "true") == "true")
            {
                Console.WriteLine("Please press Enter to continue...");
                Console.ReadLine();
            }

            if (ExitWithError)
            {
                Environment.Exit(-1);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Creates a PostgreSQL connection using the 'Npgsql' .NET Data Provider.
        /// This works on Windows and on Linux.
        /// </summary>
        /// <param name="AServer">Database Server.</param>
        /// <param name="APort">Port that the DB server is running on.</param>
        /// <param name="ADatabaseName">Name of the database that we want to connect to.</param>
        /// <param name="AUsername">Username for opening the PostgreSQL connection.</param>
        /// <param name="APassword">Password for opening the PostgreSQL connection.</param>
        /// <param name="AConnectionString">Connection string; if it is not empty, it will
        /// overrule the previous parameters.</param>
        /// <param name="AStateChangeEventHandler">Event Handler for connection state changes
        /// (NOTE: This doesn't work yet with the Npgsql driver - see code comments in this Methods'
        /// source code)!</param>
        /// <returns>
        /// Instantiated NpgsqlConnection, but not opened yet (null if connection could not be established).
        /// </returns>
        public DbConnection GetConnection(String AServer, String APort,
                                          String ADatabaseName,
                                          String AUsername, ref String APassword,
                                          ref String AConnectionString,
                                          StateChangeEventHandler AStateChangeEventHandler)
        {
            ArrayList        ExceptionList;
            NpgsqlConnection TheConnection = null;

#if EXTREME_DEBUGGING
            NpgsqlEventLog.Level        = LogLevel.Debug;
            NpgsqlEventLog.LogName      = "NpgsqlTests.LogFile";
            NpgsqlEventLog.EchoMessages = false;
#endif

            if (String.IsNullOrEmpty(AConnectionString))
            {
                if (String.IsNullOrEmpty(AUsername))
                {
                    throw new ArgumentException("AUsername", "AUsername must not be null or an empty string!");
                }

                if (String.IsNullOrEmpty(APassword))
                {
                    throw new ArgumentException("APassword", "APassword must not be null or an empty string!");
                }

                AConnectionString = String.Format(
                    "Server={0};Port={1};User Id={2};Database={3};Timeout={4};ConnectionIdleLifeTime={5};CommandTimeout={6}" +
                    ";Password="******"Server.DBConnectionTimeout", 10),
                    TAppSettingsManager.GetInt32("Server.DBConnectionLifeTime", 300),
                    TAppSettingsManager.GetInt32("Server.DBCommandTimeout", 3600));
                // Note: We must use TAppSettingsManager above and not TSrvSetting because if we would be using the latter
                // somehow some NUnit Tests fail with extremely weird timeouts...
            }

            try
            {
                // TLogging.Log('Full ConnectionString (with Password!): ''' + ConnectionString + '''');
                // TLogging.Log('Full ConnectionString (with Password!): ''' + ConnectionString + '''');
                // TLogging.Log('ConnectionStringBuilder.ToString (with Password!): ''' + ConnectionStringBuilder.ToString + '''');

                // Now try to connect to the DB
                TheConnection = new NpgsqlConnection();
                TheConnection.ConnectionString = AConnectionString + APassword + ";";
            }
            catch (Exception exp)
            {
                ExceptionList = new ArrayList();
                ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine));
                ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine));
                TLogging.Log(ExceptionList, true);
            }

            return(TheConnection);
        }
Ejemplo n.º 9
0
        public static void Main(string[] args)
        {
            TCmdOpts cmd = new TCmdOpts();

            new TAppSettingsManager(false);

            TLogging.DebugLevel = TAppSettingsManager.GetInt32("debuglevel", 0);

            String OutputDir;

            if (!cmd.IsFlagSet("TemplateDir"))
            {
                Console.WriteLine("call: " + sampleCall);
                return;
            }

            if (cmd.IsFlagSet("plugin"))
            {
                OutputDir = cmd.GetOptValue("plugindir");

                // calculate ICTPath from outputdir
                string fullOutputPath = Path.GetFullPath(OutputDir).Replace("\\", "/");

                if (!fullOutputPath.Contains("csharp/ICT"))
                {
                    Console.WriteLine("Output path must be below the csharp/ICT directory");
                }

                CSParser.ICTPath = fullOutputPath.Substring(0, fullOutputPath.IndexOf("csharp/ICT") + "csharp/ICT".Length);
                GenerateGlueForPlugin(cmd, OutputDir);
            }
            else if (cmd.IsFlagSet("outputdir"))
            {
                OutputDir = cmd.GetOptValue("outputdir");

                // calculate ICTPath from outputdir
                string fullOutputPath = Path.GetFullPath(OutputDir).Replace("\\", "/");

                if (!fullOutputPath.Contains("csharp/ICT"))
                {
                    Console.WriteLine("Output path must be below the csharp/ICT directory");
                }

                CSParser.ICTPath = fullOutputPath.Substring(0, fullOutputPath.IndexOf("csharp/ICT") + "csharp/ICT".Length);

                GenerateGlueForOpenPetraCore(cmd, OutputDir);
            }
            else
            {
                Console.WriteLine("call: " + sampleCall);
                return;
            }
        }
        private void FBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorkerArgument args = (BackgroundWorkerArgument)e.Argument;
            int countFiles = args.Files.GetLength(0);
            int countDone  = 0;

            // Get the print delay from client config.  The default is 2000 ms.
            // A value can be specified for a specific printer or as a general value
            int printDelay = TAppSettingsManager.GetInt32(string.Format("{0}.PrintQueueDelay", args.PrinterName), 0);

            if (printDelay <= 0)
            {
                // There was no printer-specific delay, so check the blanket value.  Default is 2000 ms.
                printDelay = TAppSettingsManager.GetInt32("PrintQueueDelay", 2000);
            }

            foreach (String FileName in args.Files)
            {
                if (FBackgroundWorker.CancellationPending)
                {
                    e.Cancel = true;
                    FBackgroundWorker.ReportProgress(0, Catalog.GetString("Printing aborted"));
                    return;
                }

                // Get a lock on this (empty) piece of code.  If it is already locked we will pause here until the lock is released (above)
                lock (FPauseObject)
                {
                }

                // The lock is released now (or never held)
                // Open Source OpenPetra: we do not use Templater here
                // TTemplaterAccess.RunPrintJob(args.PrinterName, Path.Combine(args.FolderPath, FileName));
                countDone++;
                FBackgroundWorker.ReportProgress(
                    (countDone * 100) / countFiles,
                    string.Format(Catalog.GetString("Printing {0} of {1}"), countDone, countFiles));

                // This sleep is important for two reasons...
                // 1. We need to allow some time for the pause button click event to obtain the lock before we print the next document
                // 2. The RunPrintJob method waits until the process that places the document into the print queue completes BUT ...
                //    Some print applications like Word or PDFCreator need a little more time to close down and close open dialogs.
                //    If we do not allow enough time something like PDFCreator may merge two documents into one folder or Word may leave a dialog showing
                //    for the current document.
                //    Two seconds is enough.  Less may be possible.  But 2 secs is probably ok unless the printer is VERY fast and can print documents
                //    faster than we put them into the print queue.
                System.Threading.Thread.Sleep(printDelay);
            }

            FBackgroundWorker.ReportProgress(100, Catalog.GetString("Printing complete"));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates a DbCommand object.
        /// This formats the sql query for MySQL, and transforms the parameters.
        /// </summary>
        /// <param name="ACommandText"></param>
        /// <param name="AConnection"></param>
        /// <param name="AParametersArray"></param>
        /// <param name="ATransaction"></param>
        /// <returns>Instantiated MySqlCommand.</returns>
        public DbCommand NewCommand(ref string ACommandText, DbConnection AConnection, DbParameter[] AParametersArray, TDBTransaction ATransaction)
        {
            DbCommand ObjReturn = null;

            ACommandText = FormatQueryRDBMSSpecific(ACommandText);

            if (TLogging.DL >= DBAccess.DB_DEBUGLEVEL_TRACE)
            {
                TLogging.Log("Query formatted for MySQL: " + ACommandText);
            }

            MySqlParameter[] MySQLParametersArray = null;

            if ((AParametersArray != null) &&
                (AParametersArray.Length > 0))
            {
                // Check for characters that indicate a parameter in query text
                if (ACommandText.IndexOf('?') == -1)
                {
                    foreach (DbParameter param in AParametersArray)
                    {
                        if (string.IsNullOrEmpty(param.ParameterName))
                        {
                            throw new EDBParameterisedQueryMissingParameterPlaceholdersException(
                                      "Question marks (?) must be present in query text if nameless Parameters are passed in");
                        }
                    }
                }

                if (AParametersArray != null)
                {
                    MySQLParametersArray = (MySqlParameter[])ConvertOdbcParameters(AParametersArray, ref ACommandText);
                }
            }

            ObjReturn = new MySqlCommand(ACommandText, (MySqlConnection)AConnection);

            ObjReturn.CommandTimeout = TAppSettingsManager.GetInt32("Server.DBCommandTimeout", 3600);

            if (MySQLParametersArray != null)
            {
                // add parameters
                foreach (DbParameter param in MySQLParametersArray)
                {
                    ObjReturn.Parameters.Add(param);
                }
            }

            return(ObjReturn);
        }
        /// <summary>
        /// Program entry point.
        /// </summary>
        private static void Main(string[] args)
        {
            // need to call with config file as parameter: -C:/home/USERNAME/etc/PetraServerConsole.config
            TPetraServerConnector.Connect();

            TBankStatementImport import = new TBankStatementImport();

            BankImportTDS StatementAndTransactionsDS = import.ImportBankStatementNonInteractive(
                TAppSettingsManager.GetInt32("ledger"),
                TAppSettingsManager.GetValue("bankaccount"),
                TAppSettingsManager.GetValue("file"));

            Int32 AFirstStatementKey;

            TBankImportWebConnector.StoreNewBankStatement(StatementAndTransactionsDS, out AFirstStatementKey);

            TPetraServerConnector.Disconnect();
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Connects to the PetraServer and provides a menu with a number of functions,
        /// including stopping the PetraServer.
        /// </summary>
        /// <returns>void</returns>
        public static void Start()
        {
            Ict.Petra.ServerAdmin.App.Core.TConnector TheConnector;
            IServerAdminInterface TRemote;
            String  ClientID;
            Boolean SilentSysadm;

            SilentSysadm = false;

            try
            {
                new TLogging();
                new TAppSettingsManager();
                SilentSysadm = true;

                if (TAppSettingsManager.HasValue("DebugLevel"))
                {
                    TLogging.DebugLevel = TAppSettingsManager.GetInt32("DebugLevel");
                }

                if ((!TAppSettingsManager.HasValue("Command") || (TAppSettingsManager.GetValue("Command") == "Stop")))
                {
                    SilentSysadm = false;
                }

                if (TAppSettingsManager.HasValue("ServerAdmin.LogFile"))
                {
                    new TLogging(TAppSettingsManager.GetValue("ServerAdmin.LogFile"));
                }

                if ((!SilentSysadm))
                {
                    Console.WriteLine();
                    TLogging.Log(
                        "PETRAServerADMIN " + System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString() + ' ' + "Build " +
                        System.IO.File.GetLastWriteTime(
                            Process.GetCurrentProcess().MainModule.FileName).ToString() + " (OS: " +
                        CommonTypes.ExecutingOSEnumToString(Utilities.DetermineExecutingOS()) + ')');

                    TLogging.Log(Catalog.GetString("Configuration file: " + TAppSettingsManager.ConfigFileName));

                    // System.Reflection.Assembly.GetEntryAssembly.FullName does not return the file path
                    TLogging.Log("Connecting to PETRAServer...");
                    Console.WriteLine();
                }

                // Instantiate a TServerManager object, which has all logic for Server
                // startup and shutdown
                TheConnector = new Ict.Petra.ServerAdmin.App.Core.TConnector();
                TheConnector.GetServerConnection(TAppSettingsManager.ConfigFileName, out TRemote);

                if (TAppSettingsManager.HasValue("Command"))
                {
                    if (TAppSettingsManager.GetValue("Command") == "Stop")
                    {
                        ShutDown(TRemote, false);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "StopAndCloseClients")
                    {
                        ShutDownControlled(TRemote, false);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "ConnectedClients")
                    {
                        System.Console.WriteLine(TRemote.FormatClientList(false));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "ConnectedClientsSysadm")
                    {
                        System.Console.WriteLine(TRemote.FormatClientListSysadm(false));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "DisconnectedClients")
                    {
                        System.Console.WriteLine(TRemote.FormatClientList(true));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "DisconnectClient")
                    {
                        ClientID = TAppSettingsManager.GetValue("ClientID");
                        DisconnectClient(TRemote, ClientID);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "LoadYmlGz")
                    {
                        RestoreDatabase(TRemote, TAppSettingsManager.GetValue("YmlGzFile"));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "RefreshAllCachedTables")
                    {
                        RefreshAllCachedTables(TRemote);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "AddUser")
                    {
                        AddUser(TRemote, TAppSettingsManager.GetValue("UserId"));
                    }
                }
                else
                {
                    Menu(TRemote);
                }

                // All exceptions that are raised are handled here
                // Note: ServerAdmin stops after handling these exceptions!!!
            }
            catch (RemotingException remexp)
            {
                if ((!SilentSysadm))
                {
                    Console.WriteLine("RemotingException occured while connecting/communicating to PETRAServer: " + remexp.Message);
                }

                return;
            }
            catch (Exception exp)
            {
                if ((!SilentSysadm))
                {
                    Console.WriteLine("Exception occured while connecting/communicating to PETRAServer: " + exp.ToString());
                }

                return;
            }

            // THE VERY END OF SERVERADMIN :(
        }
Ejemplo n.º 15
0
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// </summary>
        /// <returns>True if the Export succeeded and a file was created, false otherwise</returns>
        public bool ExportBatches(bool AWithInteractionOnSuccess = true)
        {
            string ExportFileName = txtFilename.Text;

            if (ExportFileName == String.Empty)
            {
                MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return(false);
            }
            else if (!ExportFileName.EndsWith(".csv",
                                              StringComparison.CurrentCultureIgnoreCase) && !ExportFileName.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase))
            {
                ExportFileName  += ".csv";
                txtFilename.Text = ExportFileName;
            }

            if (!Directory.Exists(Path.GetDirectoryName(ExportFileName)))
            {
                MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                txtFilename.Text = string.Empty;
                return(false);
            }

            if (File.Exists(ExportFileName))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                                    Catalog.GetString("Export Gifts"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    return(false);
                }

                try
                {
                    File.Delete(ExportFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(
                                        Catalog.GetString(
                                            "Failed to delete the file. Maybe it is already open in another application?  The system message was:{0}{1}"),
                                        Environment.NewLine, ex.Message),
                                    Catalog.GetString("Export Gift Batches"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return(false);
                }
            }

            if (rbtBatchNumberSelection.Checked)
            {
                if (!txtBatchNumberStart.NumberValueInt.HasValue)
                {
                    txtBatchNumberStart.NumberValueInt = 0;
                }

                if (!txtBatchNumberEnd.NumberValueInt.HasValue)
                {
                    txtBatchNumberEnd.NumberValueInt = 999999;
                }
            }
            else
            {
                if ((dtpDateFrom.Text == string.Empty) || (dtpDateTo.Text == string.Empty))
                {
                    MessageBox.Show(Catalog.GetString("Start and end dates must be provided."),
                                    Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return(false);
                }

                if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate()))  // If ValidDate fails, it displays a helpful message.
                {
                    return(false);
                }
            }

            String numberFormat = ConvertNumberFormat(cmbNumberFormat);
            String delimiter    = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

            if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == ".")))
            {
                MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return(false);
            }

            try
            {
                Hashtable requestParams = new Hashtable();
                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", delimiter);
                requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
                requestParams.Add("Summary", rbtSummary.Checked);
                requestParams.Add("IncludeUnposted", chkIncludeUnposted.Checked);
                requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
                requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
                requestParams.Add("RecipientNumber", Convert.ToInt64(txtDetailRecipientKey.Text));
                requestParams.Add("FieldNumber", Convert.ToInt64(txtDetailFieldKey.Text));
                requestParams.Add("DateForSummary", dtpDateSummary.Date);
                requestParams.Add("NumberFormat", numberFormat);
                requestParams.Add("ExtraColumns", chkExtraColumns.Checked);

                if (rbtBatchNumberSelection.Checked)
                {
                    requestParams.Add("BatchNumberStart", txtBatchNumberStart.NumberValueInt);
                    requestParams.Add("BatchNumberEnd", txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    requestParams.Add("BatchDateFrom", dtpDateFrom.Date);
                    requestParams.Add("BatchDateTo", dtpDateTo.Date);
                }

                TVerificationResultCollection AMessages = new TVerificationResultCollection();
                String exportString = null;
                Int32  BatchCount   = 0;

                Thread ExportThread = new Thread(() => ExportAllGiftBatchData(
                                                     requestParams,
                                                     out exportString,
                                                     out AMessages,
                                                     out BatchCount));

                using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
                {
                    ExportDialog.ShowDialog();
                }

                if ((AMessages != null) &&
                    (AMessages.Count > 0))
                {
                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return(false);
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                SaveUserDefaults();

                //Process BatchCount value
                if (BatchCount == 0)
                {
                    MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"),
                                    Catalog.GetString("Export"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
                    return(false);
                }
                else if (BatchCount == -1)
                {
                    MessageBox.Show(Catalog.GetString("Gift batch export cancelled"),
                                    Catalog.GetString("Export"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                    return(false);
                }
                else if (BatchCount == -2)
                {
                    MessageBox.Show(Catalog.GetString("Gift batch export failed"),
                                    Catalog.GetString("Export"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                    return(false);
                }

                StreamWriter sw1 = new StreamWriter(ExportFileName,
                                                    false,
                                                    Encoding.GetEncoding(TAppSettingsManager.GetInt32("ExportGiftBatchEncoding", 1252)));
                sw1.Write(exportString);
                sw1.Close();
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }

            bool ShowExportedFileInExplorer = false;

            if (AWithInteractionOnSuccess)
            {
                if (MessageBox.Show(Catalog.GetString(
                                        "Gift Batches Exported successfully. Would you like to open the file in your default application?"),
                                    Catalog.GetString("Gift Batch Export"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information,
                                    MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    try
                    {
                        ProcessStartInfo si = new ProcessStartInfo(ExportFileName);
                        si.UseShellExecute = true;
                        si.Verb            = "open";

                        Process p = new Process();
                        p.StartInfo = si;
                        p.Start();
                    }
                    catch
                    {
                        MessageBox.Show(Catalog.GetString(
                                            "Unable to launch the default application to open: '") + ExportFileName + "'!", Catalog.GetString(
                                            "Gift Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                        ShowExportedFileInExplorer = true;
                    }
                }
            }
            else
            {
                ShowExportedFileInExplorer = true;
            }

            if (ShowExportedFileInExplorer)
            {
                //If windows start Windows File Explorer
                TExecutingOSEnum osVersion = Utilities.DetermineExecutingOS();

                if ((osVersion >= TExecutingOSEnum.eosWinXP) &&
                    (osVersion < TExecutingOSEnum.oesUnsupportedPlatform))
                {
                    try
                    {
                        Process.Start("explorer.exe", string.Format("/select,\"{0}\"", ExportFileName));
                    }
                    catch
                    {
                        MessageBox.Show(Catalog.GetString(
                                            "Unable to launch Windows File Explorer to open: '") + ExportFileName + "'!", Catalog.GetString(
                                            "Gift Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates Sample Data using the raw data provided and exports this to the Petra Server
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            TLogging.Log("Running Sample Data Constructor");

            try
            {
                TLogging.Log("(1) Initialize (check availability of resources, start the server)");

                TLogging.Log("\tStarting the server...");

                // use the config file defined on the command line with -C:
                TPetraServerConnector.Connect(string.Empty);

                // data directory containing the raw data files created by benerator
                string datadirectory = TAppSettingsManager.GetValue("dir.data.generated");

                string operation = TAppSettingsManager.GetValue("operation", "importPartners");

                if ((operation == "importPartners") || (operation == "all"))
                {
                    TLogging.Log("(2) Import partners");
                    SampleDataBankPartners.GenerateBanks(
                        Path.Combine(datadirectory, "banks.csv"));

                    SampleDataDonors.GenerateFamilyPartners(
                        Path.Combine(datadirectory, "people.csv"));

                    TLogging.Log("(3) Import organisations");
                    SampleDataOrganisations.GenerateOrganisationPartners(
                        Path.Combine(datadirectory, "organisations.csv"));
                }

                TLogging.Log("(4) Import recipients");

                operation = TAppSettingsManager.GetValue("operation", "importRecipients");

                if ((operation == "importRecipients") || (operation == "all"))
                {
                    // parse random data generated by benerator
                    SampleDataUnitPartners.GenerateFields(
                        Path.Combine(datadirectory, "fields.csv"));
                    SampleDataUnitPartners.GenerateKeyMinistries(
                        Path.Combine(datadirectory, "keymins.csv"));
                    SampleDataWorkers.GenerateWorkers(
                        Path.Combine(datadirectory, "workers.csv"));
                }

                operation = TAppSettingsManager.GetValue("operation", "populateFirstLedger");

                if ((operation == "populateFirstLedger") || (operation == "all"))
                {
                    SampleDataLedger.FLedgerNumber          = 43;
                    SampleDataLedger.FNumberOfClosedPeriods = TAppSettingsManager.GetInt32("NumberOfClosedPeriods", 26);
                    SampleDataLedger.InitCalendar();
                    SampleDataLedger.InitExchangeRate();
                    SampleDataLedger.PopulateData(datadirectory);
                }

                if (operation == "secondLedger")
                {
                    TLogging.Log("creating a second ledger");

                    SampleDataLedger.FLedgerNumber          = 44;
                    SampleDataLedger.FNumberOfClosedPeriods = 6;
                    SampleDataLedger.CreateNewLedger();
                    SampleDataLedger.InitExchangeRate();

                    SampleDataUnitPartners.FLedgerNumber = SampleDataLedger.FLedgerNumber;
                    SampleDataUnitPartners.GenerateFieldsFinanceOnly(
                        Path.Combine(datadirectory, "fields.csv"));

                    SampleDataLedger.PopulateData(datadirectory);
                }
                else
                {
                    TLogging.Log("Please explicitely run nant importDemodata -D:operation=secondLedger");
                }

                TLogging.Log("(9) Creating applications for conference");

                operation = TAppSettingsManager.GetValue("operation", "conferenceApplications");

                if (operation == "conferenceApplications")
                {
                    SampleDataConferenceApplicants.GenerateApplications(Path.Combine(datadirectory, "conferenceApplications.csv"));
                }
                else
                {
                    TLogging.Log("Please explicitely run nant importDemodata -D:operation=conferenceApplications");
                }

                TLogging.Log("Completed.");
            }
            catch (Exception e)
            {
                TLogging.Log(e.Message);
                TLogging.Log(e.StackTrace);
                Environment.Exit(-1);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates Sample Data using the raw data provided and exports this to the Petra Server
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            TLogging.Log("Running Sample Data Constructor");

            try
            {
                TLogging.Log("(1) Initialize (check availability of resources, start the server)");

                TLogging.Log("\tStarting the server...");

                // use the config file defined on the command line with -C:
                TPetraServerConnector.Connect(string.Empty);

                // data directory containing the raw data files created by benerator
                string datadirectory = TAppSettingsManager.GetValue("dir.data.generated");

                eOperations operation = eOperations.importPartners | eOperations.importRecipients | eOperations.ledgerOneYear;

                if (TAppSettingsManager.GetValue("operation", false) == "secondLedger")
                {
                    operation = eOperations.secondLedger;
                }
                else if (TAppSettingsManager.GetValue("operation", false) == "ledgerMultipleYears")
                {
                    operation = eOperations.importPartners | eOperations.importRecipients | eOperations.ledgerMultipleYears;
                }

                if ((int)(operation & eOperations.importPartners) > 0)
                {
                    TLogging.Log("(2) Import partners");
                    SampleDataBankPartners.GenerateBanks(
                        Path.Combine(datadirectory, "banks.csv"));

                    SampleDataDonors.GenerateFamilyPartners(
                        Path.Combine(datadirectory, "people.csv"));

                    TLogging.Log("(3) Import organisations");
                    SampleDataOrganisations.GenerateOrganisationPartners(
                        Path.Combine(datadirectory, "organisations.csv"));
                }

                TLogging.Log("(4) Import recipients");

                if ((int)(operation & eOperations.importRecipients) > 0)
                {
                    // parse random data generated by benerator
                    SampleDataUnitPartners.GenerateFields(
                        Path.Combine(datadirectory, "fields.csv"));
                    SampleDataUnitPartners.GenerateKeyMinistries(
                        Path.Combine(datadirectory, "keymins.csv"));
                    SampleDataWorkers.GenerateWorkers(
                        Path.Combine(datadirectory, "workers.csv"));
                }

                if ((int)(operation & eOperations.ledgerOneYear) > 0)
                {
                    SampleDataLedger.FLedgerNumber          = 43;
                    SampleDataLedger.FNumberOfClosedPeriods = CalculatedNumberOfClosedPeriods(0);
                    SampleDataLedger.InitCalendar();
                    SampleDataLedger.InitExchangeRate();
                    SampleDataLedger.PopulateData(datadirectory, true);
                    TLogging.Log("Please explicitely run nant importDemodata -D:operation=secondLedger");
                    TLogging.Log("   or                  nant importDemodata -D:operation=ledgerMultipleYears");
                }

                if ((int)(operation & eOperations.ledgerMultipleYears) > 0)
                {
                    SampleDataLedger.FLedgerNumber          = 43;
                    SampleDataLedger.FNumberOfClosedPeriods = TAppSettingsManager.GetInt32("NumberOfClosedPeriods", CalculatedNumberOfClosedPeriods(2));
                    SampleDataLedger.InitCalendar();
                    SampleDataLedger.InitExchangeRate();
                    SampleDataLedger.PopulateData(datadirectory, true);
                }

                if ((int)(operation & eOperations.secondLedger) > 0)
                {
                    TLogging.Log("creating a second ledger");

                    // this ledger starts in period 4
                    SampleDataLedger.FLedgerNumber          = 44;
                    SampleDataLedger.FNumberOfClosedPeriods = CalculatedNumberOfClosedPeriods(0) - 3;
                    SampleDataLedger.CreateNewLedger();
                    SampleDataLedger.InitExchangeRate();

                    SampleDataUnitPartners.FLedgerNumber = SampleDataLedger.FLedgerNumber;

                    SampleDataLedger.PopulateData(datadirectory);
                }

                TLogging.Log("Completed.");
            }
            catch (Exception e)
            {
                TLogging.Log(e.Message);
                TLogging.Log(e.StackTrace);
                Environment.Exit(-1);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Send an email message
        /// </summary>
        /// <param name="AEmail">on successful sending, the header is modified with the sent date</param>
        /// <returns>true if email was sent successfully</returns>
        public bool SendMessage(MailMessage AEmail)
        {
            if (AEmail.Headers.Get("Date-Sent") != null)
            {
                // don't send emails several times
                return(false);
            }

            FailedRecipients.Clear();

            if (FSmtpClient.Host.EndsWith("example.org"))
            {
                TLogging.Log("Not sending the email, since the configuration is just with an example server: " + FSmtpClient.Host);
                TLogging.Log("You can configure the mail settings in the config file.");
                return(false);
            }

            //Attempt to send the email
            try
            {
                AEmail.IsBodyHtml = AEmail.Body.ToLower().Contains("<html>");

                int LimitEmailsPerMinute = TAppSettingsManager.GetInt32("SmtpLimitMessagesPerMinute", 30);
                int countInLastMinute    = LimitEmailsPerMinute;

                while (countInLastMinute >= LimitEmailsPerMinute)
                {
                    countInLastMinute = 0;

                    foreach (DateTime dt in FEmailsSentInLastMinute)
                    {
                        // better check the last 2 minutes, to avoid confusion
                        if (DateTime.Compare(dt.AddMinutes(2), DateTime.Now) >= 0)
                        {
                            countInLastMinute++;
                        }
                    }

                    if (countInLastMinute == 0)
                    {
                        FEmailsSentInLastMinute.Clear();
                    }

                    if (countInLastMinute >= LimitEmailsPerMinute)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                    }
                }

                FEmailsSentInLastMinute.Add(DateTime.Now);

                FSmtpClient.Send(AEmail);

                AEmail.Headers.Add("Date-Sent", DateTime.Now.ToString());
                return(true);
            }
            catch (SmtpFailedRecipientsException frEx)  // If the SMTP server knows that the send failed because of failed recipients,
            {                                           // I can produce a list of failed recipient addresses, and return false.
                                                        // The caller can then retrieve the list and inform the user.
                TLogging.Log("SmtpEmail: Email to the following addresses did not succeed:");
                SmtpFailedRecipientException[] failureList = frEx.InnerExceptions;

                foreach (SmtpFailedRecipientException problem in failureList)
                {
                    TsmtpFailedRecipient FailureDetails = new TsmtpFailedRecipient();
                    FailureDetails.FailedAddress = problem.FailedRecipient;
                    FailureDetails.FailedMessage = problem.Message;
                    FailedRecipients.Add(FailureDetails);
                    TLogging.Log(problem.FailedRecipient + " : " + problem.Message);
                }

                return(false);
            }
            catch (Exception ex)
            {
                // SSL authentication error: RemoteCertificateNotAvailable
                // see http://mono.1490590.n4.nabble.com/SSL-authentication-error-RemoteCertificateNotAvailable-RemoteCertificateChainErrors-td1755733.html
                // and http://www.mono-project.com/FAQ:_Security#Does_SSL_works_for_SMTP.2C_like_GMail_.3F
                // on Mono command prompt:
                //    mozroots --import --ask-remove --machine
                //    mozroots --import --ask-remove
                //    certmgr -ssl smtps://tim00.hostsharing.net:443

                TLogging.Log("There has been a problem sending the email");
                TLogging.Log("server: " + FSmtpClient.Host + ":" + FSmtpClient.Port.ToString());
                TLogging.Log(ex.ToString() + " " + ex.Message);
                TLogging.Log(ex.StackTrace);

                throw;
            }
        }
Ejemplo n.º 19
0
 public void Init()
 {
     TPetraServerConnector.Connect("../../etc/TestServer.config");
     FLedgerNumber = TAppSettingsManager.GetInt32("LedgerNumber", 43);
 }
Ejemplo n.º 20
0
        /// main method
        public static void Main(string[] args)
        {
            TPetraServerConnector.Connect("../../etc/TestServer.config");

            try
            {
                string OutputPath = TAppSettingsManager.GetValue("OutputPath", "../../delivery/GDPdU/data");

                if (!Directory.Exists(OutputPath))
                {
                    Directory.CreateDirectory(OutputPath);
                }

                string SummaryCostCentres            = TAppSettingsManager.GetValue("SummaryCostCentres", "4300S");
                string IgnoreCostCentres             = TAppSettingsManager.GetValue("IgnoreCostCentres", "xyz");
                string IgnoreAccounts                = TAppSettingsManager.GetValue("IgnoreAccounts", "4300S,GIFT");
                string IncludeAccounts               = TAppSettingsManager.GetValue("IncludeAccounts", "4310");
                string FinancialYears                = TAppSettingsManager.GetValue("FinancialYearNumber", "0");
                string IgnoreTransactionsByReference = TAppSettingsManager.GetValue("IgnoreReference", "L1,L2,L3,L4,L5,L6,L7,L8,L9,L10,L11,L12");
                int    FirstFinancialYear            = TAppSettingsManager.GetInt32("FirstFinancialYear", DateTime.Now.Year);
                int    LedgerNumber = TAppSettingsManager.GetInt32("LedgerNumber", 43);
                char   CSVSeparator = TAppSettingsManager.GetValue("CSVSeparator", ";")[0];
                string NewLine      = "\r\n";
                string culture      = TAppSettingsManager.GetValue("culture", "de-DE");

                string ReportingCostCentres =
                    TFinanceReportingWebConnector.GetReportingCostCentres(LedgerNumber, SummaryCostCentres, IgnoreCostCentres);

                //TLogging.Log("cost centres " + ReportingCostCentres);
                //TLogging.Log("accounts " + IncludeAccounts);

                if (TAppSettingsManager.GetBoolean("IgnorePersonCostCentres", true))
                {
                    ReportingCostCentres = TGDPdUExportAccountsAndCostCentres.WithoutPersonCostCentres(LedgerNumber, ReportingCostCentres);
                }

                IgnoreAccounts =
                    TFinanceReportingWebConnector.GetReportingAccounts(LedgerNumber, IgnoreAccounts, IncludeAccounts);

                // set decimal separator, and thousands separator
                Ict.Common.Catalog.SetCulture(culture);

                List <string> CostCentresInvolved = new List <string>();
                List <string> AccountsInvolved    = new List <string>();

                foreach (string FinancialYearString in FinancialYears.Split(new char[] { ',' }))
                {
                    Int32 FinancialYear = Convert.ToInt32(FinancialYearString);

                    string OutputPathForYear = Path.Combine(OutputPath, (FirstFinancialYear + FinancialYear).ToString());

                    if (!Directory.Exists(OutputPathForYear))
                    {
                        Directory.CreateDirectory(OutputPathForYear);
                    }

                    TGDPdUExportWorkers.Export(OutputPathForYear, CSVSeparator, NewLine,
                                               LedgerNumber * 1000000,
                                               FirstFinancialYear + FinancialYear);

                    TGDPdUExportTransactions.ExportGLTransactions(OutputPathForYear,
                                                                  CSVSeparator,
                                                                  NewLine,
                                                                  LedgerNumber,
                                                                  FinancialYear,
                                                                  ReportingCostCentres,
                                                                  IgnoreAccounts,
                                                                  IgnoreTransactionsByReference,
                                                                  ref CostCentresInvolved,
                                                                  ref AccountsInvolved);

                    TGDPdUExportBalances.ExportGLBalances(OutputPathForYear, CSVSeparator, NewLine, LedgerNumber,
                                                          FinancialYear, ReportingCostCentres,
                                                          IgnoreAccounts);
                }

                TGDPdUExportAccountsAndCostCentres.ExportCostCentres(OutputPath, CSVSeparator, NewLine, LedgerNumber,
                                                                     CostCentresInvolved);

                TGDPdUExportAccountsAndCostCentres.ExportAccounts(OutputPath, CSVSeparator, NewLine, LedgerNumber,
                                                                  AccountsInvolved);
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
            }

            if (TAppSettingsManager.GetValue("interactive", "true") == "true")
            {
                Console.WriteLine("Please press Enter to continue...");
                Console.ReadLine();
            }
        }
Ejemplo n.º 21
0
        public static void Main(string[] args)
        {
            TCmdOpts cmd = new TCmdOpts();

            new TAppSettingsManager(false);

            TLogging.DebugLevel = TAppSettingsManager.GetInt32("debuglevel", 0);

            String OutputDir;

            if (!cmd.IsFlagSet("TemplateDir"))
            {
                Console.WriteLine("call: " + sampleCall);
                return;
            }

            if (cmd.IsFlagSet("outputdir"))
            {
                OutputDir = cmd.GetOptValue("outputdir");

                // calculate ICTPath from outputdir
                string fullOutputPath = Path.GetFullPath(OutputDir).Replace("\\", "/");

                if (!fullOutputPath.Contains("csharp/ICT"))
                {
                    Console.WriteLine("Output path must be below the csharp/ICT directory");
                }

                CSParser.ICTPath = fullOutputPath.Substring(0, fullOutputPath.IndexOf("csharp/ICT") + "csharp/ICT".Length);
            }
            else
            {
                Console.WriteLine("call: " + sampleCall);
                return;
            }

            TNamespace namespaceRoot;

            try
            {
                Console.WriteLine("parsing all cs files for namespaces...");
                namespaceRoot = TNamespace.ParseFromDirectory(OutputDir + "/Server/lib/");

                if (namespaceRoot.Children.Count < 1)
                {
                    Console.WriteLine("problems with parsing namespaces from " + OutputDir + "/Server/lib/");
                    Environment.Exit(-1);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Environment.Exit(-1);
                return;
            }

            try
            {
                CreateInterfaces interfaces = new CreateInterfaces();
                interfaces.CreateFiles(namespaceRoot, OutputDir + "/Shared/lib/Interfaces", cmd.GetOptValue("TemplateDir"));
                CreateInstantiators instantiators = new CreateInstantiators();
                instantiators.CreateFiles(namespaceRoot, OutputDir + "/Server/lib", cmd.GetOptValue("TemplateDir"));
                TCreateConnectors connectors = new TCreateConnectors();
                connectors.CreateFiles(namespaceRoot, OutputDir + "/Server/lib", cmd.GetOptValue("TemplateDir"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Environment.Exit(-1);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// </summary>
        public void ExportBatches(object sender, EventArgs e)
        {
            if (File.Exists(txtFilename.Text))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                                    Catalog.GetString("Export Gifts"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            StreamWriter sw1 = null;

            try
            {
                sw1 = new StreamWriter(txtFilename.Text,
                                       false,
                                       Encoding.GetEncoding(TAppSettingsManager.GetInt32("ExportGiftBatchEncoding", 1252)));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,
                                Catalog.GetString("Failed to open file"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            try
            {
                if (rbtBatchNumberSelection.Checked)
                {
                    if (!txtBatchNumberStart.NumberValueInt.HasValue)
                    {
                        txtBatchNumberStart.NumberValueInt = 0;
                    }

                    if (!txtBatchNumberEnd.NumberValueInt.HasValue)
                    {
                        txtBatchNumberEnd.NumberValueInt = 999999;
                    }
                }
                else
                {
                    if ((dtpDateFrom.Text == "") || (dtpDateTo.Text == ""))
                    {
                        MessageBox.Show(Catalog.GetString("Start and end dates must be provided."),
                                        Catalog.GetString("Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }

                    if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate()))  // If ValidDate fails, it displays a helpful message.
                    {
                        return;
                    }
                }

                String numberFormat = ConvertNumberFormat(cmbNumberFormat);
                String delimiter    = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

                if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == ".")))
                {
                    MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."),
                                    Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return;
                }

                Hashtable requestParams = new Hashtable();
                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false));
                requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
                requestParams.Add("Summary", rbtSummary.Checked);
                requestParams.Add("IncludeUnposted", chkIncludeUnposted.Checked);
                requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
                requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
                requestParams.Add("RecipientNumber", Convert.ToInt64(txtDetailRecipientKey.Text));
                requestParams.Add("FieldNumber", Convert.ToInt64(txtDetailFieldKey.Text));
                requestParams.Add("DateForSummary", dtpDateSummary.Date);
                requestParams.Add("NumberFormat", ConvertNumberFormat(cmbNumberFormat));
                requestParams.Add("ExtraColumns", chkExtraColumns.Checked);

                if (rbtBatchNumberSelection.Checked)
                {
                    requestParams.Add("BatchNumberStart", txtBatchNumberStart.NumberValueInt);
                    requestParams.Add("BatchNumberEnd", txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    requestParams.Add("BatchDateFrom", dtpDateFrom.Date);
                    requestParams.Add("BatchDateTo", dtpDateTo.Date);
                }

                TVerificationResultCollection AMessages = new TVerificationResultCollection();
                String exportString = null;
                Int32  BatchCount   = 0;

                Thread ExportThread = new Thread(() => ExportAllGiftBatchData(
                                                     requestParams,
                                                     out exportString,
                                                     out AMessages,
                                                     out BatchCount));

                using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
                {
                    ExportDialog.ShowDialog();
                }

                if ((AMessages != null) &&
                    (AMessages.Count > 0))
                {
                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                if (BatchCount == 0)
                {
                    MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"),
                                    Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return;
                }

                sw1.Write(exportString);
                sw1.Close();

                SaveUserDefaults();
                MessageBox.Show(Catalog.GetString("Gift Batches Exported successfully."),
                                Catalog.GetString("Gift Batch Export"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                TLogging.Log("GiftBatchExport.ManualCode: " + ex.ToString());
                MessageBox.Show(ex.Message,
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            finally
            {
                sw1.Close();
            }
        }
Ejemplo n.º 23
0
        /// <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";
            }

            TTypedDataTable.ResetStaticVariables();
            TPdfPrinter.ResetStaticVariables();
            THTTPUtils.ResetStaticVariables();
            TSharedDataCache.TMPartner.ResetStaticVariables();
            TServerManagerBase.ResetStaticVariables();
            TClientManager.ResetStaticVariables();

            TSession.InitThread("TOpenPetraOrgSessionManager.Init", ConfigFileName);

            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("TOpenPetraOrgSessionManager.Init Reset", ConfigFileName);
            }

            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);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// processing CAMT file
        /// </summary>
        public void ProcessFileContent(string content, bool AParsePreviousYear, out TVerificationResultCollection AVerificationResult)
        {
            statements          = new List <TStatement>();
            AVerificationResult = new TVerificationResultCollection();

            CultureInfo backupCulture = Thread.CurrentThread.CurrentCulture;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(content);
                XmlNode nodeDocument = doc.DocumentElement;

                string CAMTVersion        = "CAMT.53";
                XmlNamespaceManager nsmgr = GetNamespaceManager(doc, "urn:iso:std:iso:20022:tech:xsd:camt.053.001.02");

                if (nsmgr == null)
                {
                    CAMTVersion = "CAMT.52";
                    nsmgr       = GetNamespaceManager(doc, "urn:iso:std:iso:20022:tech:xsd:camt.052.001.02");
                }

                if (nsmgr == null)
                {
                    throw new Exception("expecting xmlns for CAMT.52 or CAMT.53");
                }

                XmlNodeList stmts = null;

                if (CAMTVersion == "CAMT.53")
                {
                    stmts = nodeDocument.SelectNodes("camt:BkToCstmrStmt/camt:Stmt", nsmgr);
                }
                else if (CAMTVersion == "CAMT.52")
                {
                    stmts = nodeDocument.SelectNodes("camt:BkToCstmrAcctRpt/camt:Rpt", nsmgr);
                }

                Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                foreach (XmlNode nodeStatement in stmts)
                {
                    TStatement stmt = new TStatement();

                    stmt.id          = nodeStatement.SelectSingleNode("camt:ElctrncSeqNb", nsmgr).InnerText;
                    stmt.accountCode = nodeStatement.SelectSingleNode("camt:Acct/camt:Id/camt:IBAN", nsmgr).InnerText;
                    stmt.bankCode    = nodeStatement.SelectSingleNode("camt:Acct/camt:Svcr/camt:FinInstnId/camt:BIC", nsmgr).InnerText;
                    stmt.currency    = nodeStatement.SelectSingleNode("camt:Acct/camt:Ccy", nsmgr).InnerText;

                    Int32 DiffElctrncSeqNb = TAppSettingsManager.GetInt32("DiffElctrncSeqNbFor" + stmt.bankCode + "/" + stmt.accountCode, 0);
                    stmt.id = (Convert.ToInt32(stmt.id) + DiffElctrncSeqNb).ToString();

                    stmt.severalYears = false;
                    XmlNode nm      = nodeStatement.SelectSingleNode("camt:Acct/camt:Ownr/camt:Nm", nsmgr);
                    string  ownName = nm != null?nm.InnerText:
                                      TAppSettingsManager.GetValue("AccountNameFor" + stmt.bankCode + "/" + stmt.accountCode, String.Empty, false);
                    XmlNodeList nodeBalances = nodeStatement.SelectNodes("camt:Bal", nsmgr);

                    foreach (XmlNode nodeBalance in nodeBalances)
                    {
                        // PRCD: PreviouslyClosedBooked
                        if (nodeBalance.SelectSingleNode("camt:Tp/camt:CdOrPrtry/camt:Cd", nsmgr).InnerText == "PRCD")
                        {
                            stmt.startBalance = Decimal.Parse(nodeBalance.SelectSingleNode("camt:Amt", nsmgr).InnerText);

                            // CreditDebitIndicator: CRDT or DBIT for credit or debit
                            if (nodeBalance.SelectSingleNode("camt:CdtDbtInd", nsmgr).InnerText == "DBIT")
                            {
                                stmt.startBalance *= -1.0m;
                            }

                            stmt.date = DateTime.Parse(nodeBalance.SelectSingleNode("camt:Dt", nsmgr).InnerText);
                        }
                        // CLBD: ClosingBooked
                        else if (nodeBalance.SelectSingleNode("camt:Tp/camt:CdOrPrtry/camt:Cd", nsmgr).InnerText == "CLBD")
                        {
                            stmt.endBalance = Decimal.Parse(nodeBalance.SelectSingleNode("camt:Amt", nsmgr).InnerText);

                            // CreditDebitIndicator: CRDT or DBIT for credit or debit
                            if (nodeBalance.SelectSingleNode("camt:CdtDbtInd", nsmgr).InnerText == "DBIT")
                            {
                                stmt.endBalance *= -1.0m;
                            }

                            stmt.date = DateTime.Parse(nodeBalance.SelectSingleNode("camt:Dt", nsmgr).InnerText);
                        }

                        // ITBD: InterimBooked
                        // CLAV: ClosingAvailable
                        // FWAV: ForwardAvailable
                    }

                    string  strDiffBalance = TAppSettingsManager.GetValue("DiffBalanceFor" + stmt.bankCode + "/" + stmt.accountCode, "0");
                    Decimal DiffBalance    = 0.0m;
                    if (Decimal.TryParse(strDiffBalance, out DiffBalance))
                    {
                        stmt.startBalance += DiffBalance;
                        stmt.endBalance   += DiffBalance;
                    }
                    else
                    {
                        TLogging.Log("problem parsing decimal from configuration setting DiffBalanceFor" + stmt.bankCode + "/" + stmt.accountCode);
                    }

                    // if we should parse the transactions only of the past year
                    if (AParsePreviousYear &&
                        stmt.date.Month != 12 &&
                        stmt.date.Day != 31)
                    {
                        stmt.date = new DateTime(stmt.date.Year - 1, 12, 31);
                    }

                    XmlNodeList nodeEntries = nodeStatement.SelectNodes("camt:Ntry", nsmgr);

                    foreach (XmlNode nodeEntry in nodeEntries)
                    {
                        TTransaction tr = new TTransaction();
                        tr.inputDate = DateTime.Parse(nodeEntry.SelectSingleNode("camt:BookgDt/camt:Dt", nsmgr).InnerText);
                        tr.valueDate = DateTime.Parse(nodeEntry.SelectSingleNode("camt:ValDt/camt:Dt", nsmgr).InnerText);

                        if (tr.valueDate.Year != stmt.date.Year)
                        {
                            // ignore transactions that are in a different year than the statement
                            stmt.severalYears = true;
                            continue;
                        }

                        tr.amount = Decimal.Parse(nodeEntry.SelectSingleNode("camt:Amt", nsmgr).InnerText);

                        if (nodeEntry.SelectSingleNode("camt:Amt", nsmgr).Attributes["Ccy"].Value != stmt.currency)
                        {
                            throw new Exception("transaction currency " + nodeEntry.SelectSingleNode("camt:Amt",
                                                                                                     nsmgr).Attributes["Ccy"].Value + " does not match the bank statement currency");
                        }

                        if (nodeEntry.SelectSingleNode("camt:CdtDbtInd", nsmgr).InnerText == "DBIT")
                        {
                            tr.amount *= -1.0m;
                        }

                        XmlNode desc = nodeEntry.SelectSingleNode("camt:NtryDtls/camt:TxDtls/camt:RmtInf/camt:Ustrd", nsmgr);
                        tr.description = desc != null?desc.InnerText:String.Empty;
                        XmlNode partnerName = nodeEntry.SelectSingleNode("camt:NtryDtls/camt:TxDtls/camt:RltdPties/camt:Dbtr/camt:Nm", nsmgr);

                        if (partnerName != null)
                        {
                            tr.partnerName = partnerName.InnerText;
                        }

                        XmlNode accountCode = nodeEntry.SelectSingleNode("camt:NtryDtls/camt:TxDtls/camt:RltdPties/camt:DbtrAcct/camt:Id/camt:IBAN",
                                                                         nsmgr);

                        if (accountCode != null)
                        {
                            tr.accountCode = accountCode.InnerText;
                        }

                        XmlNode CrdtName = nodeEntry.SelectSingleNode("camt:NtryDtls/camt:TxDtls/camt:RltdPties/camt:Cdtr/camt:Nm", nsmgr);
                        XmlNode DbtrName = nodeEntry.SelectSingleNode("camt:NtryDtls/camt:TxDtls/camt:RltdPties/camt:Dbtr/camt:Nm", nsmgr);

                        if ((CrdtName != null) && (CrdtName.InnerText != ownName))
                        {
                            if ((DbtrName != null) && (DbtrName.InnerText == ownName))
                            {
                                // we are the debitor
                            }
                            else if (ownName != String.Empty)
                            {
                                // sometimes donors write the project or recipient in the field where the organisation is supposed to be
                                TLogging.Log("CrdtName is not like expected: " + tr.description + " --- " + CrdtName.InnerText);
                                tr.description += " " + CrdtName.InnerText;
                            }
                        }

                        XmlNode EndToEndId = nodeEntry.SelectSingleNode("camt:NtryDtls/camt:TxDtls/camt:Refs/camt:EndToEndId", nsmgr);

                        if ((EndToEndId != null) &&
                            (EndToEndId.InnerText != "NOTPROVIDED") &&
                            !EndToEndId.InnerText.StartsWith("LS-") &&
                            !EndToEndId.InnerText.StartsWith("ZV") &&
                            !EndToEndId.InnerText.StartsWith("IZV-DISPO"))
                        {
                            // sometimes donors write the project or recipient in unexpected field
                            TLogging.Log("EndToEndId: " + tr.description + " --- " + EndToEndId.InnerText);
                            tr.description += " " + EndToEndId.InnerText;
                        }

                        // eg NSTO+152+00900. look for SEPA Geschäftsvorfallcodes
                        // see the codes: https://www.wgzbank.de/export/sites/wgzbank/de/wgzbank/downloads/produkte_leistungen/firmenkunden/zv_aktuelles/Uebersicht-GVC-und-Buchungstexte-WGZ-BANK_V062015.pdf
                        string[] GVCCode =
                            nodeEntry.SelectSingleNode("camt:NtryDtls/camt:TxDtls/camt:BkTxCd/camt:Prtry/camt:Cd", nsmgr).InnerText.Split(
                                new char[] { '+' });
                        tr.typecode = GVCCode[1];

                        // for SEPA direct debit batches, there are multiple TxDtls records
                        XmlNodeList transactionDetails = nodeEntry.SelectNodes("camt:NtryDtls/camt:TxDtls", nsmgr);

                        if (transactionDetails.Count > 1)
                        {
                            tr.partnerName = String.Empty;
                            tr.description = String.Format(
                                Catalog.GetString("SEPA Sammel-Basislastschrift mit {0} Lastschriften"),
                                transactionDetails.Count);
                        }

                        stmt.transactions.Add(tr);

                        TLogging.LogAtLevel(2, "count : " + stmt.transactions.Count.ToString());
                    }

                    statements.Add(stmt);
                }
            }
            catch (Exception e)
            {
                AVerificationResult.Add(new TVerificationResult(null, "problem with importing camt file; " + e.Message, TResultSeverity.Resv_Critical));
                TLogging.Log("problem with importing camt file; " + e.Message + Environment.NewLine + e.StackTrace);
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = backupCulture;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Connects to the PetraServer and provides a menu with a number of functions,
        /// including stopping the PetraServer.
        /// </summary>
        /// <returns>void</returns>
        public static void Start()
        {
            String  ClientID;
            bool    ExitError = false;
            Boolean SilentSysadm;

            SilentSysadm = false;

            try
            {
                new TLogging();
                new TAppSettingsManager();
                SilentSysadm = true;

                if (TAppSettingsManager.HasValue("DebugLevel"))
                {
                    TLogging.DebugLevel = TAppSettingsManager.GetInt32("DebugLevel");
                }

                if ((!TAppSettingsManager.HasValue("Command") || (TAppSettingsManager.GetValue("Command") == "Stop")))
                {
                    SilentSysadm = false;
                }

                if (TAppSettingsManager.HasValue("ServerAdmin.LogFile"))
                {
                    new TLogging(TAppSettingsManager.GetValue("ServerAdmin.LogFile"));
                }

                if ((!SilentSysadm))
                {
                    string ExePath = TAppSettingsManager.ApplicationDirectory + Path.DirectorySeparatorChar +
                                     "PetraServerAdminConsole.exe";

                    Console.WriteLine();
                    TLogging.Log(
                        "PETRAServerADMIN " + System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString() + ' ' + "Build " +
                        System.IO.File.GetLastWriteTime(ExePath).ToString() + " (OS: " +
                        CommonTypes.ExecutingOSEnumToString(Utilities.DetermineExecutingOS()) + ')');

                    TLogging.Log(Catalog.GetString("Configuration file: " + TAppSettingsManager.ConfigFileName));

                    // System.Reflection.Assembly.GetEntryAssembly.FullName does not return the file path
                    TLogging.Log("Connecting to PETRAServer...");
                    Console.WriteLine();
                }

                // Instantiate a remote object, which provides access to the server
                THttpConnector httpConnector = new THttpConnector(TAppSettingsManager.GetValue("OpenPetra.HTTPServer"));
                httpConnector.ServerAdminSecurityToken = NewSecurityToken();
                TRemote = new TMServerAdminNamespace(httpConnector).WebConnectors;

                try {
                    TRemote.LoginServerAdmin("SYSADMIN");
                }
                catch (Exception)
                {
                    if (TAppSettingsManager.HasValue("Command") && (TAppSettingsManager.GetValue("Command") == "Stop"))
                    {
                        // don't exit with error code because the server is not running anyway
                        if ((!SilentSysadm))
                        {
                            Console.WriteLine("The server is not running, so it cannot be stopped");
                        }

                        System.Environment.Exit(0);
                    }
                    else
                    {
                        throw;
                    }
                }

                if (TAppSettingsManager.HasValue("Command"))
                {
                    if (TAppSettingsManager.GetValue("Command") == "Stop")
                    {
                        ShutDown(false);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "StopAndCloseClients")
                    {
                        ShutDownControlled(false);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "ConnectedClients")
                    {
                        System.Console.WriteLine(TRemote.FormatClientList(false));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "ConnectedClientsSysadm")
                    {
                        System.Console.WriteLine(TRemote.FormatClientListSysadm(false));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "DisconnectedClients")
                    {
                        System.Console.WriteLine(TRemote.FormatClientList(true));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "DisconnectClient")
                    {
                        ClientID = TAppSettingsManager.GetValue("ClientID");
                        DisconnectClient(ClientID);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "LoadYmlGz")
                    {
                        RestoreDatabase(TAppSettingsManager.GetValue("YmlGzFile"));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "SaveYmlGz")
                    {
                        if (!ExportDatabase(TAppSettingsManager.GetValue("YmlGzFile")))
                        {
                            ExitError = true;
                        }
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "UpgradeDatabase")
                    {
                        UpgradeDatabase();
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "SendReminders")
                    {
                        TRemote.PerformTimedProcessingNow("TProcessPartnerReminders");
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "RefreshAllCachedTables")
                    {
                        RefreshAllCachedTables();
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "SetPassword")
                    {
                        if (!SetPassword(TAppSettingsManager.GetValue("UserID"), TAppSettingsManager.GetValue("NewPassword")))
                        {
                            throw new Exception("SetPassword did not work, perhaps too easy password?");
                        }
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "LockSysadmin")
                    {
                        if (!LockSysadmin())
                        {
                            throw new Exception("LockSysadmin did not work");
                        }
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "AddUser")
                    {
                        AddUser(TAppSettingsManager.GetValue("UserId"));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "Menu")
                    {
                        Menu();
                    }
                }
                else
                {
                    Menu();
                }

                // All exceptions that are raised are handled here
                // Note: ServerAdmin stops after handling these exceptions!!!
            }
            catch (Exception exp)
            {
                if ((!SilentSysadm))
                {
                    Console.WriteLine("Exception occured while connecting/communicating to PETRAServer: " + exp.ToString());
                }

                ExitError = true;
            }

            ClearSecurityToken();

            if (ExitError)
            {
                System.Environment.Exit(-1);
            }

            // THE VERY END OF SERVERADMIN :(
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Stops the Petra Server in a more controlled way than the <see cref="StopServer" /> Method.
        /// </summary>
        /// <remarks>
        /// A ClientTask is queued for all connected Clients that asks them to save the UserDefaults,
        /// to disconnect from the Server and to close. This Method monitors the connected Clients until
        /// either all Clients have responded by disconnecting or if at least one Client didn't respond and
        /// a timeout was exceeded. If this is the case and the Argument <paramref name="AForceAutomaticClosing" />
        /// is true, a different ClientTask is queued
        /// for all Clients that are still connected that asks them to close (no saving of UserDefaults and
        /// no disconnection from the server!). This is a fallback in case (1) the client(s) crashed and can't
        /// either save the UserDefaults or can't disconnect, (2) the saving of UserDefaults or
        /// the disconnecting of Clients doesn't work for some server-side reason (e.g. broken DB
        /// connection would prevent saving of UserDefaults).
        /// </remarks>
        /// <param name="AForceAutomaticClosing">Set to true to force closing of non-responding Clients (this
        /// is set to true by the ServerAdminConsole as this process is non-interactive in this case).</param>
        /// <returns>False if AForceAutomaticClosing is false and there are still clients logged in.</returns>
        public bool StopServerControlled(bool AForceAutomaticClosing)
        {
            const int SLEEP_TIME_PER_RETRY = 500; // 500 milliseconds = 0.5 seconds
            const int MAX_RETRIES          = 100; // = 500 milliseconds * 100 = 50 seconds
            int       Retries = 0;
            Int32     ClientKeepAliveCheckIntervalInSeconds =
                TAppSettingsManager.GetInt32("Server.ClientKeepAliveCheckIntervalInSeconds", 60);

            TLogging.Log(Catalog.GetString("CONTROLLED SHUTDOWN PROCEDURE INITIATED"));

            // Check if there are still Clients connected
            if (ClientsConnected > 0)
            {
                // At least one Client is still connected
                TLogging.Log("  " +
                             String.Format(Catalog.GetString("CONTROLLED SHUTDOWN: Notifying all connected Clients ({0} {1}). Please wait..."),
                                           ClientsConnected, ClientsConnected > 1 ? "Clients" : "Client"));

                // Queue a ClientTask for all connected Clients that asks them to save the UserDefaults,  to disconnect from the Server and to close
                QueueClientTask(-1, RemotingConstants.CLIENTTASKGROUP_DISCONNECT, "IMMEDIATE", null, null, null, null, 1);

                // Loop that checks if all Clients have responded by disconnecting or if at least one Client didn't respond and a timeout was exceeded
CheckAllClientsDisconnected:
                Thread.Sleep(SLEEP_TIME_PER_RETRY);

                if ((ClientsConnected > 0) &&
                    (Retries < MAX_RETRIES))
                {
                    Retries++;

                    if (Retries % 4 == 1)
                    {
                        TLogging.Log("    " +
                                     String.Format(Catalog.GetString(
                                                       "CONTROLLED SHUTDOWN: There {2} still {0} {1} connected. Waiting for {3} to disconnect (Waiting {4} more seconds)..."),
                                                   ClientsConnected, ClientsConnected > 1 ? "Clients" : "Client",
                                                   ClientsConnected > 1 ? "are" : "is", ClientsConnected > 1 ? "them" : "it",
                                                   ((SLEEP_TIME_PER_RETRY * MAX_RETRIES) - (SLEEP_TIME_PER_RETRY * Retries)) / 1000));
                    }

                    goto CheckAllClientsDisconnected;
                }

                // Check if at least one Client is still connected
                if (Retries == MAX_RETRIES)
                {
                    // Yes there is still at least one Client connected
                    TLogging.Log("  " +
                                 String.Format(Catalog.GetString(
                                                   "CONTROLLED SHUTDOWN: {0} did not respond to the disconnect request. Enter FORCE to force closing of the {1} and shutdown the Server, or anything else to leave this command."),
                                               ClientsConnected == 1 ? "One Client" : ClientsConnected + " Clients", ClientsConnected > 1 ? "Clients" : "Client"));

                    // Special handling in case this Method is called from the ServerAdminConsole application
                    if (AForceAutomaticClosing)
                    {
                        // Check again that there are still Clients connected (could have disconnected while the user was typing 'FORCE'!)
                        if (ClientsConnected > 0)
                        {
                            // Yes there is still at least one Client connected
                            TLogging.Log("    " +
                                         String.Format(Catalog.GetString(
                                                           "CONTROLLED SHUTDOWN: Forcing all connected Clients ({0} {1}) to close. Please wait..."),
                                                       ClientsConnected, ClientsConnected > 1 ? "Clients" : "Client"));

                            // Queue a ClienTasks for all Clients that are still connected that asks them to close (no saving of UserDefaults and no disconnection from the server!). This is a fallback mechanism.
                            QueueClientTask(-1, RemotingConstants.CLIENTTASKGROUP_DISCONNECT, "IMMEDIATE-HARDEXIT", null, null, null, null, 1);

                            // Loop as long as TSrvSetting.ClientKeepAliveCheckIntervalInSeconds is to ensure that all Clients will have got the chance to pick up the queued Client Task
                            // (since it would not be easy to determine that every connected Client has picked up this message, this is the easy way of ensuring that).
                            for (int Counter = 1; Counter <= 4; Counter++)
                            {
                                TLogging.Log("    " +
                                             String.Format(Catalog.GetString(
                                                               "CONTROLLED SHUTDOWN: Waiting {0} seconds so the Server can be sure that all Clients have got the message that they need to close... ({1} more seconds to wait)"),
                                                           ClientKeepAliveCheckIntervalInSeconds / 1000,
                                                           (ClientKeepAliveCheckIntervalInSeconds -
                                                            ((ClientKeepAliveCheckIntervalInSeconds / 4) * (Counter - 1))) / 1000));

                                Thread.Sleep(ClientKeepAliveCheckIntervalInSeconds / 4);
                            }
                        }
                        else
                        {
                            // No Clients connected anymore -> we can shut down the server.
                            TLogging.Log("  " +
                                         Catalog.GetString(
                                             "CONTROLLED SHUTDOWN: All Clients have disconnected in the meantine, proceeding with shutdown immediately."));
                        }
                    }
                    else
                    {
                        // Abandon the shutdown as there are still connected clients and we are not allowed to force the shutdown
                        return(false);
                    }
                }
            }
            else
            {
                // No Clients connected anymore -> we can shut down the server.
                TLogging.Log("  " + Catalog.GetString("CONTROLLED SHUTDOWN: There were no Clients connected, proceeding with shutdown immediately."));
            }

            // We are now ready to stop the server.
            StopServer();

            return(true);  // this will never get executed, but is necessary for that Method to compile...
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Connects to the PetraServer and provides a menu with a number of functions,
        /// including stopping the PetraServer.
        /// </summary>
        /// <returns>void</returns>
        public static void Start()
        {
            String  ClientID;
            bool    ExitError = false;
            Boolean SilentSysadm;

            SilentSysadm = false;

            try
            {
                new TLogging();
                new TAppSettingsManager();
                SilentSysadm = true;

                if (TAppSettingsManager.HasValue("DebugLevel"))
                {
                    TLogging.DebugLevel = TAppSettingsManager.GetInt32("DebugLevel");
                }

                if ((!TAppSettingsManager.HasValue("Command") || (TAppSettingsManager.GetValue("Command") == "Stop")))
                {
                    SilentSysadm = false;
                }

                if (TAppSettingsManager.HasValue("ServerAdmin.LogFile"))
                {
                    new TLogging(TAppSettingsManager.GetValue("ServerAdmin.LogFile"));
                }

                if ((!SilentSysadm))
                {
                    Console.WriteLine();
                    TLogging.Log(
                        "PETRAServerADMIN " + System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString() + ' ' + "Build " +
                        System.IO.File.GetLastWriteTime(
                            Process.GetCurrentProcess().MainModule.FileName).ToString() + " (OS: " +
                        CommonTypes.ExecutingOSEnumToString(Utilities.DetermineExecutingOS()) + ')');

                    TLogging.Log(Catalog.GetString("Configuration file: " + TAppSettingsManager.ConfigFileName));

                    // System.Reflection.Assembly.GetEntryAssembly.FullName does not return the file path
                    TLogging.Log("Connecting to PETRAServer...");
                    Console.WriteLine();
                }

                // Instantiate a remote object, which provides access to the server
                THttpConnector.ServerAdminSecurityToken = NewSecurityToken();
                THttpConnector.InitConnection(TAppSettingsManager.GetValue("OpenPetra.HTTPServer"));
                TRemote = new TMServerAdminNamespace().WebConnectors;
                TRemote.LoginServerAdmin();

                if (TAppSettingsManager.HasValue("Command"))
                {
                    if (TAppSettingsManager.GetValue("Command") == "Stop")
                    {
                        ShutDown(false);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "StopAndCloseClients")
                    {
                        ShutDownControlled(false);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "ConnectedClients")
                    {
                        System.Console.WriteLine(TRemote.FormatClientList(false));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "ConnectedClientsSysadm")
                    {
                        System.Console.WriteLine(TRemote.FormatClientListSysadm(false));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "DisconnectedClients")
                    {
                        System.Console.WriteLine(TRemote.FormatClientList(true));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "DisconnectClient")
                    {
                        ClientID = TAppSettingsManager.GetValue("ClientID");
                        DisconnectClient(ClientID);
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "LoadYmlGz")
                    {
                        RestoreDatabase(TAppSettingsManager.GetValue("YmlGzFile"));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "SaveYmlGz")
                    {
                        if (!ExportDatabase(TAppSettingsManager.GetValue("YmlGzFile")))
                        {
                            ExitError = true;
                        }
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "UpgradeDatabase")
                    {
                        UpgradeDatabase();
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "RefreshAllCachedTables")
                    {
                        RefreshAllCachedTables();
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "AddUser")
                    {
                        AddUser(TAppSettingsManager.GetValue("UserId"));
                    }
                    else if (TAppSettingsManager.GetValue("Command") == "Menu")
                    {
                        Menu();
                    }
                }
                else
                {
                    Menu();
                }

                // All exceptions that are raised are handled here
                // Note: ServerAdmin stops after handling these exceptions!!!
            }
            catch (Exception exp)
            {
                if ((!SilentSysadm))
                {
                    Console.WriteLine("Exception occured while connecting/communicating to PETRAServer: " + exp.ToString());
                }

                ExitError = true;
            }

            string CannotDisconnectMessage;

            new THTTPClientManager().DisconnectClient(out CannotDisconnectMessage);
            ClearSecurityToken();

            if (ExitError)
            {
                System.Environment.Exit(-1);
            }

            // THE VERY END OF SERVERADMIN :(
        }
Ejemplo n.º 28
0
        /// <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);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Creates a PostgreSQL connection using the 'Npgsql' .NET Data Provider.
        /// This works on Windows and on Linux.
        /// </summary>
        /// <param name="AServer">Database Server.</param>
        /// <param name="APort">Port that the DB server is running on.</param>
        /// <param name="ADatabaseName">Name of the database that we want to connect to.</param>
        /// <param name="AUsername">Username for opening the PostgreSQL connection.</param>
        /// <param name="APassword">Password for opening the PostgreSQL connection.</param>
        /// <param name="AConnectionString">Connection string; if it is not empty, it will
        /// overrule the previous parameters.</param>
        /// <param name="AStateChangeEventHandler">Event Handler for connection state changes
        /// (NOTE: This doesn't work yet with the Npgsql driver - see code comments in this Methods'
        /// source code)!</param>
        /// <returns>
        /// Instantiated NpgsqlConnection, but not opened yet (null if connection could not be established).
        /// </returns>
        public DbConnection GetConnection(String AServer, String APort,
                                          String ADatabaseName,
                                          String AUsername, ref String APassword,
                                          ref String AConnectionString,
                                          StateChangeEventHandler AStateChangeEventHandler)
        {
            ArrayList        ExceptionList;
            NpgsqlConnection TheConnection = null;

#if EXTREME_DEBUGGING
            NpgsqlEventLog.Level        = LogLevel.Debug;
            NpgsqlEventLog.LogName      = "NpgsqlTests.LogFile";
            NpgsqlEventLog.EchoMessages = false;
#endif

            if (String.IsNullOrEmpty(AConnectionString))
            {
                if (String.IsNullOrEmpty(AUsername))
                {
                    throw new ArgumentException("AUsername", "AUsername must not be null or an empty string!");
                }

                if (String.IsNullOrEmpty(APassword))
                {
                    throw new ArgumentException("APassword", "APassword must not be null or an empty string!");
                }

                AConnectionString = String.Format(
                    "Server={0};Port={1};User Id={2};Database={3};Timeout={4};ConnectionLifeTime={5};CommandTimeout={6}" +
                    ";Password="******"Server.DBConnectionTimeout", 10),
                    TAppSettingsManager.GetInt32("Server.DBConnectionLifeTime", 60),
                    TAppSettingsManager.GetInt32("Server.DBCommandTimeout", 3600));
                // Note: We must use TAppSettingsManager above and not TSrvSetting because if we would be using the latter
                // somehow some NUnit Tests fail with extremely weird timeouts...
            }

            try
            {
                // TLogging.Log('Full ConnectionString (with Password!): ''' + ConnectionString + '''');
                // TLogging.Log('Full ConnectionString (with Password!): ''' + ConnectionString + '''');
                // TLogging.Log('ConnectionStringBuilder.ToString (with Password!): ''' + ConnectionStringBuilder.ToString + '''');

                // Now try to connect to the DB
                TheConnection = new NpgsqlConnection();
                TheConnection.ConnectionString = AConnectionString + APassword + ";";
            }
            catch (Exception exp)
            {
                ExceptionList = new ArrayList();
                ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine));
                ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine));
                TLogging.Log(ExceptionList, true);
            }

            if (TheConnection != null)
            {
                // Somehow the StateChange Event is never fired for an NpgsqlConnection, although it is documented.
                // As a result of that we cannot rely on the FConnectionReady variable to contain valid values for
                // NpgsqlConnection. Therefore I (ChristianK) wrote a wrapper routine, ConnectionReady, which
                // handles this difference. FConnectionReady must therefore never be inquired directly, but only
                // through calling ConnectionReady()!
                // (As of Npgsql 2.0.11.92 the Event still isn't raised)

                // TODO: need to test this again
                ((NpgsqlConnection)TheConnection).StateChange += AStateChangeEventHandler;
            }

            return(TheConnection);
        }
Ejemplo n.º 30
0
        /// <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);
        }