static void Main(string[] args)
        {
            new TAppSettingsManager(false);

            ServicePointManager.ServerCertificateValidationCallback = delegate {
                return(true);
            };

            if (!TAppSettingsManager.HasValue("sf-username"))
            {
                Console.WriteLine("call: MantisUpdateVersions.exe -sf-username:pokorra -sf-pwd:xyz -release-version:0.2.16.0");
                Console.WriteLine(
                    "or: MantisUpdateVersions.exe -sf-username:pokorra -sf-pwd:xyz -bug-id:abc,def,ghi -version-fixed-in:\"Alpha 0.2.20\"");
                return;
            }

            string mantisURL = TAppSettingsManager.GetValue("mantis-url", "https://tracker.openpetra.org/api/soap/mantisconnect.php");

            try
            {
                Session session = LoginToMantis(mantisURL, TAppSettingsManager.GetValue("sf-username"), TAppSettingsManager.GetValue("sf-pwd"));

                if (TAppSettingsManager.HasValue("version-fixed-in"))
                {
                    string[] bugids = TAppSettingsManager.GetValue("bug-id").Split(new char[] { ',' });

                    foreach (string bugid in bugids)
                    {
                        SetVersionFixedInForResolvedBug(
                            session,
                            Convert.ToInt32(bugid),
                            TAppSettingsManager.GetValue("version-fixed-in"));
                    }
                }
                else
                {
                    Version releaseVersion = new Version(TAppSettingsManager.GetValue("release-version"));
                    Version devVersion     = new Version(releaseVersion.Major, releaseVersion.Minor, releaseVersion.Build + 1, releaseVersion.Revision);
                    Version nextVersion    = new Version(releaseVersion.Major, releaseVersion.Minor, releaseVersion.Build + 2, releaseVersion.Revision);

                    SortedList <int, string> projectIDs = GetAllProjects(session);

                    foreach (int id in projectIDs.Keys)
                    {
                        Console.WriteLine("project " + projectIDs[id]);
                        UpdateVersionsOfProject(session,
                                                id,
                                                "Alpha " + releaseVersion.ToString(3),
                                                "Alpha " + devVersion.ToString(3) + " Dev",
                                                "Alpha " + nextVersion.ToString(3));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Example #2
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);
            }
        }
Example #3
0
        private void LoadTable(TTable newTable)
        {
            bool IgnoreFile = false;

            TLogging.Log(newTable.strName);

            string oldTableName = DataDefinitionDiff.GetOldTableName(newTable.strName);

            TTable oldTable = storeOld.GetTable(oldTableName);

            // if this is a new table in OpenPetra, do not dump anything. the table will be empty in OpenPetra
            // (except p_partner_attribute_category and p_partner_attribute_type which are populated here)
            if ((oldTable == null) && (newTable.strName != "p_partner_attribute_category") && (newTable.strName != "p_partner_attribute_type"))
            {
                return;
            }

            // the file has already been stored in fulldump, tablename.d.gz
            string dumpFile = TAppSettingsManager.GetValue("fulldumpPath", "fulldump") + Path.DirectorySeparatorChar + oldTableName;

            if (!File.Exists(dumpFile + ".d.gz"))
            {
                TLogging.Log("cannot find file " + dumpFile + ".d.gz");
                return;
            }

            FileInfo info = new FileInfo(dumpFile + ".d.gz");

            // ignore empty files (with one exception)
            if ((oldTableName == "p_partner_gift_destination") ||
                (oldTableName == "p_partner_attribute_category") ||
                (oldTableName == "p_partner_attribute_type"))
            {
                IgnoreFile = true;
            }

            if ((info.Length == 0) && !IgnoreFile)
            {
                TLogging.Log("ignoring " + dumpFile + ".d.gz");
                return;
            }

            if (TAppSettingsManager.HasValue("table") || !File.Exists(dumpFile + ".sql.gz") || ((new FileInfo(dumpFile + ".sql.gz")).Length == 0))
            {
                if (((long)info.Length > MAX_SIZE_D_GZ_SEPARATE_PROCESS) && !TAppSettingsManager.HasValue("table"))
                {
                    if (TAppSettingsManager.GetValue("IgnoreBigTables", "false", false) == "false")
                    {
                        ProcessAndWritePostgresqlFile(dumpFile, newTable);
                    }
                }
                else
                {
                    ProcessAndWritePostgresqlFile(dumpFile, newTable);
                }
            }
        }
Example #4
0
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="ConfigFile"></param>
        /// <param name="iRemote"></param>
        public void GetServerConnection(string ConfigFile, out IServerAdminInterface iRemote)
        {
            iRemote = null;
            try
            {
                if (TAppSettingsManager.HasValue("Server.Port"))
                {
                    DetermineServerIPAddress();

                    IClientChannelSinkProvider TCPSink = new BinaryClientFormatterSinkProvider();

                    if (TAppSettingsManager.HasValue("Server.ChannelEncryption.PublicKeyfile"))
                    {
                        Hashtable properties = new Hashtable();
                        properties.Add("FilePublicKeyXml", TAppSettingsManager.GetValue("Server.ChannelEncryption.PublicKeyfile"));

                        TCPSink.Next = new EncryptionClientSinkProvider(properties);
                    }

                    Hashtable ChannelProperties = new Hashtable();

                    TcpChannel Channel = new TcpChannel(ChannelProperties, TCPSink, null);
                    ChannelServices.RegisterChannel(Channel, false);

                    RemotingConfiguration.RegisterWellKnownClientType(
                        typeof(IServerAdminInterface),
                        String.Format("tcp://{0}:{1}/Servermanager", FServerIPAddr, FServerPort));
                }
                else
                {
                    RemotingConfiguration.Configure(ConfigFile, false);

                    DetermineServerIPAddress();
                }

                iRemote = (IServerAdminInterface)
                          Activator.GetObject(typeof(IServerAdminInterface),
                                              String.Format("tcp://{0}:{1}/Servermanager", FServerIPAddr, FServerPort));

                if ((iRemote != null) && (TLogging.DebugLevel > 0))
                {
                    TLogging.Log(("GetServerConnection: connected."));
                }
            }
            catch (Exception exp)
            {
                TLogging.Log(("Error in GetServerConnection(), Possible reasons :-" + exp.ToString()));
                throw;
            }
        }
Example #5
0
        public static void Main(string[] args)
        {
            new TAppSettingsManager(false);

            if (!TAppSettingsManager.HasValue("file"))
            {
                Console.WriteLine("call: echo SELECT * FROM s_user | SQLiteConsole -file:mydatabase.db -password:secret");
                Environment.Exit(1);
            }

            try
            {
                if (!System.IO.File.Exists(TAppSettingsManager.GetValue("file")))
                {
                    Console.WriteLine("database file " + TAppSettingsManager.GetValue("file") + " does not exist");

                    // this is to avoid InitDBConnection trying to find/copy the base database
                    Environment.Exit(1);
                }

                if (!InitDBConnection(TAppSettingsManager.GetValue("file"), TAppSettingsManager.GetValue("password", "")))
                {
                    Console.WriteLine("cannot connect to database " + TAppSettingsManager.GetValue("file"));
                    Environment.Exit(1);
                }

                string SQLCommand = "";
                string line;

                while ((line = Console.ReadLine()) != null && line.Length > 0)
                {
                    SQLCommand += " " + line.Trim();
                }

                TDBTransaction transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
                DataTable      result      = DBAccess.GDBAccessObj.SelectDT(SQLCommand, "temp", transaction);
                TDataBase.LogTable(result);
                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            if (db.ConnectionOK)
            {
                db.CloseDBConnection();
            }
        }
Example #6
0
        /// <summary>
        /// setup the smtp client from the config file or command line parameters
        /// </summary>
        public TSmtpSender()
        {
            //Set up SMTP client
            String EmailDirectory = "";

            if (TAppSettingsManager.HasValue("OutputEMLToDirectory"))
            {
                EmailDirectory = TAppSettingsManager.GetValue("OutputEMLToDirectory");
            }

            Initialise(
                TAppSettingsManager.GetValue("SmtpHost"),
                TAppSettingsManager.GetInt16("SmtpPort", 25),
                TAppSettingsManager.GetBoolean("SmtpEnableSsl", false),
                TAppSettingsManager.GetValue("SmtpUser", ""),
                TAppSettingsManager.GetValue("SmtpPassword", ""),
                EmailDirectory);
        }
Example #7
0
        /// <summary>
        /// Determines the PetraServer's IP Address and port by parsing the .NET (Remoting) Configuration file.
        /// </summary>
        protected void DetermineServerIPAddress()
        {
            const String CLIENTMANAGERENTRY = "Ict.Common.Remoting.Shared.IClientManagerInterface";

            string strServerIPAddr = string.Empty;

            if (TAppSettingsManager.HasValue("Server.Host"))
            {
                FServerIPAddr = TAppSettingsManager.GetValue("Server.Host");
            }

            if (TAppSettingsManager.HasValue("Server.Port"))
            {
                FServerPort = TAppSettingsManager.GetValue("Server.Port");
            }

            if (FServerIPAddr == "")
            {
                // find entry for ClientManagerInterface in the RegisteredWellKnownClientTypes
                // and extract the Server IP address from it
                foreach (WellKnownClientTypeEntry entr in RemotingConfiguration.GetRegisteredWellKnownClientTypes())
                {
                    if (entr.ObjectType.ToString() == CLIENTMANAGERENTRY)
                    {
                        int indexServerIPAddrStart = entr.ObjectUrl.IndexOf("//") + 2;
                        strServerIPAddr =
                            entr.ObjectUrl.Substring(indexServerIPAddrStart, entr.ObjectUrl.IndexOf(':',
                                                                                                    indexServerIPAddrStart) - indexServerIPAddrStart);
                        int indexPortStart = entr.ObjectUrl.IndexOf(':', indexServerIPAddrStart) + 1;
                        FServerPort = entr.ObjectUrl.Substring(indexPortStart, entr.ObjectUrl.IndexOf('/', indexPortStart) - indexPortStart);
                    }
                }

                FServerIPAddr = strServerIPAddr;
            }

            if (FServerIPAddr.Length == 0)
            {
                throw new EServerIPAddressNotFoundInConfigurationFileException(
                          "The IP Address of the PetraServer could " + "not be extracted from the .NET (Remoting) Configuration File (used '" +
                          CLIENTMANAGERENTRY + "' entry " + "to look for the IP Address)!");
            }
        }
Example #8
0
        private static void SendEmailToAdmin(DataTable AErrors)
        {
            // Create excel output of the errors table
            string excelfile = TAppSettingsManager.GetValue("DataChecks.TempPath") + "/errors.xlsx";

            try
            {
                using (StreamWriter sw = new StreamWriter(excelfile))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        if (!TCsv2Xml.DataTable2ExcelStream(AErrors, m))
                        {
                            return;
                        }

                        m.WriteTo(sw.BaseStream);
                        m.Close();
                        sw.Close();
                    }
                }
            }
            catch (Exception e)
            {
                TLogging.Log("Problems writing to file " + excelfile);
                TLogging.Log(e.ToString());
                return;
            }

            if (TAppSettingsManager.HasValue("DataChecks.Email.Recipient"))
            {
                new TSmtpSender().SendEmail("<" + TAppSettingsManager.GetValue("DataChecks.Email.Sender") + ">",
                                            "OpenPetra DataCheck Robot",
                                            TAppSettingsManager.GetValue("DataChecks.Email.Recipient"),
                                            "Data Check",
                                            "there are " + AErrors.Rows.Count.ToString() + " errors. Please see attachment!",
                                            new string[] { excelfile });
            }
            else
            {
                TLogging.Log("there is no email sent because DataChecks.Email.Recipient is not defined in the config file");
            }
        }
Example #9
0
        /// <summary>
        /// Opens a .NET Remoting connection to the PetraServer's ClientManager.
        ///
        /// </summary>
        /// <param name="ConfigFile">File name of the .NET (Remoting) Configuration file</param>
        /// <param name="ARemote">.NET Remoting Proxy object for the ClientManager object
        /// </param>
        /// <returns>void</returns>
        public virtual void GetRemoteServerConnection(string ConfigFile, out IClientManagerInterface ARemote)
        {
            ARemote = null;
            try
            {
                if (!FRemotingConfigurationSetup)
                {
                    FRemotingConfigurationSetup = true;

                    if (TAppSettingsManager.HasValue("Server.Port"))
                    {
                        IChannel[] regChannels = ChannelServices.RegisteredChannels;

                        foreach (IChannel ch in regChannels)
                        {
                            ChannelServices.UnregisterChannel(ch);
                        }

                        ChannelServices.RegisterChannel(new TcpChannel(0), false);
                    }
                    else if (TAppSettingsManager.HasValue("OpenPetra.ChannelEncryption.PublicKeyfile"))
                    {
                        IClientChannelSinkProvider TCPSink = new BinaryClientFormatterSinkProvider();

                        Hashtable properties = new Hashtable();
                        properties.Add("HttpsPublicKeyXml", TAppSettingsManager.GetValue("OpenPetra.ChannelEncryption.PublicKeyfile"));

                        TCPSink.Next = new EncryptionClientSinkProvider(properties);

                        Hashtable ChannelProperties = new Hashtable();

                        TcpChannel Channel = new TcpChannel(ChannelProperties, TCPSink, null);
                        ChannelServices.RegisterChannel(Channel, false);
                    }
                    else
                    {
                        // The following call must be done only once while the application runs (otherwise a RemotingException occurs)
                        RemotingConfiguration.Configure(ConfigFile, false);
                    }
                }

                DetermineServerIPAddress();

                ARemote = (IClientManagerInterface)
                          Activator.GetObject(typeof(IClientManagerInterface),
                                              String.Format("tcp://{0}:{1}/Clientmanager", FServerIPAddr, FServerPort));

                if (ARemote != null)
                {
                    if (TLogging.DebugLevel >= CONNECTOR_LOGGING)
                    {
                        TLogging.Log("GetRemoteServerConnection: connected.", TLoggingType.ToLogfile);
                    }
                }
            }
            catch (Exception exp)
            {
                TLogging.Log("Error in GetRemoteServerConnection(), Possible reasons :-" + exp.ToString(), TLoggingType.ToLogfile);
                throw;
            }
        }
Example #10
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 :(
        }
Example #11
0
        /// <summary>
        /// main function
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            new TAppSettingsManager(false);
            new TLogging("Ict.Tools.DataDumpPetra2.log");

            if (!TAppSettingsManager.HasValue("debuglevel"))
            {
                Console.Error.WriteLine("dumps one single table or all tables from Progress Petra 2.3 into Postgresql SQL load format");
                Console.Error.WriteLine(
                    "usage: Ict.Tools.DataDumpPetra2 -debuglevel:<0..10> -table:<single table or all> -oldpetraxml:<path and filename of old petra.xml> -newpetraxml:<path and filename of petra.xml>");
                Console.Error.WriteLine("will default to processing all tables, and using petra23.xml and petra.xml from the current directory");
                Console.Error.WriteLine(
                    "usage for creating fulldump23.p: Ict.Tools.DataDumpPetra2 -operation:createProgressCode");
                Console.Error.WriteLine("");
            }

            try
            {
                TLogging.DebugLevel = TAppSettingsManager.GetInt16("debuglevel", 0);

                if (TAppSettingsManager.GetValue("operation", false) == "createProgressCode")
                {
                    TCreateFulldumpProgressCode createProgressCode = new TCreateFulldumpProgressCode();
                    createProgressCode.GenerateFulldumpCode();
                    return;
                }

                if (TAppSettingsManager.GetValue("clean", "false") == "true")
                {
                    TLogging.Log("deleting all resulting files...");

                    // delete sql.gz files, also _*.txt
                    string[] FilesToDelete = Directory.GetFiles(TAppSettingsManager.GetValue("fulldumpPath", "fulldump"), "*.sql.gz");

                    foreach (string file in FilesToDelete)
                    {
                        File.Delete(file);
                    }

                    FilesToDelete = Directory.GetFiles(TAppSettingsManager.GetValue("fulldumpPath", "fulldump"), "_*.txt");

                    foreach (string file in FilesToDelete)
                    {
                        File.Delete(file);
                    }
                }

                StringCollection tables = StringHelper.StrSplit(TAppSettingsManager.GetValue("table", ""), ",");

                // the upgrade process is split into two steps, to make testing quicker

                // Step 1: dump from Progress Petra 2.3 to CSV files, write gz files to keep size of fulldump small
                // this takes about 7 minutes for the german database
                // use the generated fulldump23.p
                if ((TAppSettingsManager.GetValue("operation", "dump23") == "dump23") && File.Exists("fulldump23.r"))
                {
                    TDumpProgressToPostgresql dumper = new TDumpProgressToPostgresql();

                    if (tables.Count == 0)
                    {
                        dumper.DumpTablesToCSV(String.Empty);
                    }
                    else
                    {
                        foreach (var ProcessTable in tables)
                        {
                            dumper.DumpTablesToCSV(ProcessTable);
                        }
                    }
                }

                // Step 2: produce one or several sql load files for PostgreSQL
                // can be called independant from first step: for all tables or just one table
                // for tables merged into one: append to previous file
                // this takes 50 minutes on my virtual machine on the german server for all tables. on a faster machine, it is only 25 minutes
                if (TAppSettingsManager.GetValue("operation", "load30") == "load30")
                {
                    TDumpProgressToPostgresql dumper = new TDumpProgressToPostgresql();

                    if (tables.Count == 0)
                    {
                        dumper.LoadTablesToPostgresql(String.Empty);
                    }
                    else
                    {
                        foreach (var ProcessTable in tables)
                        {
                            dumper.LoadTablesToPostgresql(ProcessTable);
                        }
                    }
                }

                // Step 3: concatenate all existing sql.gz files into one load sql file, gzipped. in the correct order
                if (TAppSettingsManager.GetValue("operation", "createSQL") == "createSQL")
                {
                    TDumpProgressToPostgresql dumper = new TDumpProgressToPostgresql();

                    if (tables.Count == 0)
                    {
                        dumper.CreateNewSQLFile(String.Empty);
                    }
                    else
                    {
                        foreach (var ProcessTable in tables)
                        {
                            dumper.CreateNewSQLFile(ProcessTable);
                        }
                    }
                }

                // TODO: also anonymize the names of the partners (use random names from external list of names)? what about amounts?
            }
            catch (Exception e)
            {
                TLogging.Log(e.Message);

                if (e.InnerException != null)
                {
                    TLogging.Log(e.InnerException.Message);
                }

                TLogging.Log(e.StackTrace);
            }
        }
Example #12
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 :(
        }
Example #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);
        }
Example #14
0
        public static void Main(string[] args)
        {
            try
            {
                new TAppSettingsManager(false);

                if (Directory.Exists("log"))
                {
                    new TLogging("log/generatewinforms.log");
                }
                else
                {
                    new TLogging("generatewinforms.log");
                }

                TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0);

                if (!TAppSettingsManager.HasValue("op"))
                {
                    Console.WriteLine("call: GenerateWinForms -op:generate -ymlfile:c:\\test.yaml -petraxml:petra.xml -localisation:en");
                    Console.WriteLine("  or: GenerateWinForms -op:generate -ymldir:c:\\myclient -petraxml:petra.xml -localisation:en");
                    Console.WriteLine("  or: GenerateWinForms -op:clean -ymldir:c:\\myclient");
                    Console.WriteLine("  or: GenerateWinForms -op:preview");
                    Console.Write("Press any key to continue . . . ");
                    Console.ReadLine();
                    Environment.Exit(-1);
                    return;
                }

                // calculate ICTPath from ymlfile path
                string fullYmlfilePath =
                    Path.GetFullPath(TAppSettingsManager.GetValue("ymlfile", TAppSettingsManager.GetValue("ymldir", false))).Replace(
                        "\\",
                        "/");

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

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

                if (TAppSettingsManager.GetValue("op") == "clean")
                {
                    if (!Directory.Exists(fullYmlfilePath))
                    {
                        throw new Exception("invalid directory " + fullYmlfilePath);
                    }

                    // delete all generated files in the directory
                    foreach (string file in System.IO.Directory.GetFiles(fullYmlfilePath, "*.yaml", SearchOption.AllDirectories))
                    {
                        DeleteGeneratedFile(file, "-generated.cs");
                        DeleteGeneratedFile(file, "-generated.Designer.cs");
                        DeleteGeneratedFile(file, "-generated.resx");
                    }
                }
                else if (TAppSettingsManager.GetValue("op") == "preview")
                {
                    string SelectedLocalisation = null;         // none selected by default; winforms autosize works quite well

                    if (TAppSettingsManager.HasValue("localisation"))
                    {
                        SelectedLocalisation = TAppSettingsManager.GetValue("localisation");
                    }

                    TDataBinding.FPetraXMLStore = new TDataDefinitionStore();
                    Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true));
                    TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true));
                    parser.ParseDocument(ref TDataBinding.FPetraXMLStore, true, true);

                    TFrmYamlPreview PreviewWindow = new TFrmYamlPreview(
                        TAppSettingsManager.GetValue("ymlfile"),
                        SelectedLocalisation);

                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
                    Application.ThreadException += new ThreadExceptionEventHandler(UnhandledThreadExceptionHandler);

                    PreviewWindow.ShowDialog();

                    return;
                }
                else if (TAppSettingsManager.GetValue("op") == "generate")
                {
                    string SelectedLocalisation = null;         // none selected by default; winforms autosize works quite well

                    if (TAppSettingsManager.HasValue("localisation"))
                    {
                        SelectedLocalisation = TAppSettingsManager.GetValue("localisation");
                    }

                    TDataBinding.FPetraXMLStore = new TDataDefinitionStore();
                    Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true));
                    TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true));
                    parser.ParseDocument(ref TDataBinding.FPetraXMLStore, true, true);

                    string ymlfileParam = TAppSettingsManager.GetValue("ymlfile", TAppSettingsManager.GetValue("ymldir", false));

                    if (ymlfileParam.Contains(","))
                    {
                        StringCollection collection = StringHelper.StrSplit(ymlfileParam, ",");

                        foreach (string file in collection)
                        {
                            ProcessFile(file, SelectedLocalisation);
                        }
                    }
                    else if (System.IO.Directory.Exists(ymlfileParam))
                    {
                        string[] yamlfiles = System.IO.Directory.GetFiles(ymlfileParam, "*.yaml", SearchOption.AllDirectories);
                        // sort the files so that the deepest files are first processed,
                        // since the files higher up are depending on them
                        // eg. FinanceMain.yaml needs to check for GLBatch-generated.cs

                        List <string> yamlFilesSorted = new List <string>(yamlfiles.Length);

                        foreach (string file in yamlfiles)
                        {
                            yamlFilesSorted.Add(file);
                        }

                        yamlFilesSorted.Sort(new YamlFileOrderComparer());

                        foreach (string file in yamlFilesSorted)
                        {
                            // only look for main files, not language specific files (*.xy-XY.yaml or *.xy.yaml)
                            if (TProcessYAMLForms.IgnoreLanguageSpecificYamlFile(file))
                            {
                                continue;
                            }

                            Console.WriteLine("working on " + file);
                            ProcessFile(file, SelectedLocalisation);
                        }
                    }
                    else
                    {
                        ProcessFile(ymlfileParam, SelectedLocalisation);
                    }
                }
            }
            catch (Exception e)
            {
                string commandline = "";

                foreach (string s in args)
                {
                    commandline += s + " ";
                }

                Console.WriteLine("Problem while processing " + commandline);
                Console.WriteLine(e.GetType().ToString() + ": " + e.Message);

                if (e.InnerException != null)
                {
                    Console.WriteLine(e.InnerException.GetType().ToString() + ": " + e.InnerException.Message);
                }

                // do not print a stacktrace for custom generated exception, eg. by the YML parser
                if ((e.GetType() != typeof(System.Exception)) || (TLogging.DebugLevel > 0))
                {
                    Console.WriteLine(e.StackTrace);
                }

                Environment.Exit(-1);
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            string BugIDs = String.Empty;

            new TAppSettingsManager(false);

            if ((!TAppSettingsManager.HasValue("sf-username")) ||
                (!TAppSettingsManager.HasValue("sf-pwd")) ||
                (!TAppSettingsManager.HasValue("bugs-csv-file")) ||
                (!TAppSettingsManager.HasValue("version-fixed-in-earlier-than"))
                )
            {
                Console.WriteLine(
                    "call: MantisCloseResolvedBugs.exe -sf-username:pokorra -sf-pwd:xyz -bugs-csv-file:resolvedbugs.csv -version-fixed-in-earlier-than:\"Alpha 0.2.20\"");
                return;
            }

            // Process CSV file: turn it into an XmlDocument for ease of use
            string      bugsCSVFile = TAppSettingsManager.GetValue("bugs-csv-file");
            XmlDocument bugsXmlDoc  = TCsv2Xml.ParseCSV2Xml(bugsCSVFile, ",");

            XmlNode RecordNode = bugsXmlDoc.FirstChild.NextSibling.FirstChild;

            // Extract all Bug ID's from the XmlDocument
            while (RecordNode != null)
            {
                BugIDs += TXMLParser.GetAttribute(RecordNode, "Id") + ",";

                RecordNode = RecordNode.NextSibling;
            }

            BugIDs = BugIDs.Substring(0, BugIDs.Length - 1);   // remove last comma ','


            // Start the processing in the web browser
            string loginURL  = TAppSettingsManager.GetValue("login-url", "http://sourceforge.net/account/login.php");
            string mantisURL = TAppSettingsManager.GetValue("mantis-url", "https://sourceforge.net/apps/mantisbt/openpetraorg/");

            IWebDriver driver = new FirefoxDriver();

            try
            {
                LoginToSourceforge(driver, loginURL, TAppSettingsManager.GetValue("sf-username"), TAppSettingsManager.GetValue("sf-pwd"));

                string[] bugids = BugIDs.Split(new char[] { ',' });

                // Process each Bug
                foreach (string bugid in bugids)
                {
                    SetResolvedBugToClosed(
                        driver,
                        mantisURL + "bug_update_page.php?bug_id=" + bugid,
                        TAppSettingsManager.GetValue("version-fixed-in-earlier-than"));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());

                StreamWriter sw = new StreamWriter("error.html");
                sw.WriteLine(driver.PageSource.Replace("a0:", "").Replace(":a0", ""));
                sw.Close();
                Console.WriteLine("please check " + Path.GetFullPath("error.html"));
            }
            finally
            {
                driver.Quit();
            }
        }
Example #16
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 :(
        }
Example #17
0
        private static void SendEmailForUser(TDataBase ADataBaseObj, string AUserId, DataTable AErrors)
        {
            TDBTransaction ReadTransaction = new TDBTransaction();
            SUserRow       userrow         = null;

            // get the email address of the user
            ADataBaseObj.ReadTransaction(ref ReadTransaction,
                                         delegate
            {
                userrow = SUserAccess.LoadByPrimaryKey(AUserId, ReadTransaction)[0];
            });

            string   excelfile        = TAppSettingsManager.GetValue("DataChecks.TempPath") + "/errors" + AUserId + ".xlsx";
            DateTime Errors_SinceDate = DateTime.Today.AddDays(-1 * SENDREPORTFORDAYS_TOUSERS);

            DataView v = new DataView(AErrors,
                                      "(CreatedBy='" + AUserId + "' AND ModifiedBy IS NULL AND DateCreated > #" + Errors_SinceDate.ToString("MM/dd/yyyy") + "#) " +
                                      "OR (ModifiedBy='" + AUserId + "' AND DateModified > #" + Errors_SinceDate.ToString("MM/dd/yyyy") + "#)",
                                      string.Empty, DataViewRowState.CurrentRows);

            try
            {
                using (StreamWriter sw = new StreamWriter(excelfile))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        if (!TCsv2Xml.DataTable2ExcelStream(v.ToTable(), m))
                        {
                            return;
                        }

                        m.WriteTo(sw.BaseStream);
                        m.Close();
                        sw.Close();
                    }
                }
            }
            catch (Exception e)
            {
                TLogging.Log("Problems writing to file " + excelfile);
                TLogging.Log(e.ToString());
                return;
            }

            string recipientEmail = string.Empty;

            if (!userrow.IsEmailAddressNull())
            {
                recipientEmail = userrow.EmailAddress;
            }
            else if (TAppSettingsManager.HasValue("DataChecks.Email.Recipient.UserDomain"))
            {
                recipientEmail = userrow.FirstName + "." + userrow.LastName + "@" + TAppSettingsManager.GetValue(
                    "DataChecks.Email.Recipient.UserDomain");
            }
            else if (TAppSettingsManager.HasValue("DataChecks.Email.Recipient"))
            {
                recipientEmail = TAppSettingsManager.GetValue("DataChecks.Email.Recipient");
            }

            if (recipientEmail.Length > 0)
            {
                new TSmtpSender().SendEmail("<" + TAppSettingsManager.GetValue("DataChecks.Email.Sender") + ">",
                                            "OpenPetra DataCheck Robot",
                                            recipientEmail,
                                            "Data Check for " + AUserId,
                                            "there are " + v.Count.ToString() + " errors. Please see attachment!",
                                            new string[] { excelfile });
            }
            else
            {
                TLogging.Log("no email can be sent to " + AUserId);
            }
        }
Example #18
0
        public static void Main(string[] args)
        {
            try
            {
                new TAppSettingsManager(false);

                if (Directory.Exists(TAppSettingsManager.GetValue("logPath")))
                {
                    new TLogging(TAppSettingsManager.GetValue("logPath") + "/generateextjsforms.log");
                }
                else
                {
                    new TLogging("generateextjsforms.log");
                }

                TLogging.DebugLevel = TAppSettingsManager.GetInt16("DebugLevel", 0);

                if (!TAppSettingsManager.HasValue("ymlfile"))
                {
                    Console.WriteLine("call: GenerateExtJsForms -ymlfile:c:\\test.yaml -petraxml:petra.xml -localisation:en");
                    Console.Write("Press any key to continue . . . ");
                    Console.ReadLine();
                    Environment.Exit(-1);
                    return;
                }

                // calculate ICTPath from ymlfile path
                string fullYmlfilePath = Path.GetFullPath(TAppSettingsManager.GetValue("ymlfile")).Replace("\\", "/");

                string SelectedLocalisation = null;         // none selected by default

                if (TAppSettingsManager.HasValue("localisation"))
                {
                    SelectedLocalisation = TAppSettingsManager.GetValue("localisation");
                }

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

                TDataBinding.FPetraXMLStore = new TDataDefinitionStore();
                Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true));
                TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true));
                parser.ParseDocument(ref TDataBinding.FPetraXMLStore, true, true);

                string ymlfileParam = TAppSettingsManager.GetValue("ymlfile", true);

                if (ymlfileParam.Contains(","))
                {
                    StringCollection collection = StringHelper.StrSplit(ymlfileParam, ",");

                    foreach (string file in collection)
                    {
                        ProcessFile(file, SelectedLocalisation);
                    }
                }
                else if (System.IO.Directory.Exists(ymlfileParam))
                {
                    ProcessDirectory(ymlfileParam, SelectedLocalisation);
                }
                else
                {
                    ProcessFile(ymlfileParam, SelectedLocalisation);
                }

                // TODO: generate localised versions
                // TODO: generate minified version. either using YUICompressor, or simple string operation?
                // Or should the xsp server do that? generate js files on the fly? figure out the language of the client? cache files?
            }
            catch (Exception e)
            {
                string commandline = "";

                foreach (string s in args)
                {
                    commandline += s + " ";
                }

                Console.WriteLine("Problem while processing " + commandline);
                Console.WriteLine(e.GetType().ToString() + ": " + e.Message);

                if (e.InnerException != null)
                {
                    Console.WriteLine(e.InnerException.GetType().ToString() + ": " + e.InnerException.Message);
                }

                // do not print a stacktrace for custom generated exception, eg. by the YML parser
                if ((e.GetType() != typeof(System.Exception)) || (TLogging.DebugLevel > 0))
                {
                    Console.WriteLine(e.StackTrace);
                }

                Environment.Exit(-1);
            }
        }
Example #19
0
        /// <summary>
        /// Starts the Petra Server.
        ///
        /// </summary>
        /// <returns>void</returns>
        public void Startup()
        {
            try
            {
                //
                // Uncomment the following lines to see which DLL's are loaded into the Default AppDomain at application start.
                // It can help in identifying which DLL's are loaded later in addition to those that were loaded at application start.

/*
 *          Console.WriteLine("Loaded Assemblies in AppDomain " + Thread.GetDomain().FriendlyName + " (at Server start):");
 *          foreach (Assembly tmpAssembly in Thread.GetDomain().GetAssemblies())
 *          {
 *              Console.WriteLine(tmpAssembly.FullName);
 *          }
 */
                new TAppSettingsManager();

                TLanguageCulture.Init();

                TheServerManager = new TServerManager();

                // Ensure Logging and an 'ordered cooperative shutdown' in case of an Unhandled Exception
                TheServerManager.HookupProperShutdownProcessing();

                Console.WriteLine();
                TLogging.Log(TheServerManager.ServerInfoVersion);
                TLogging.Log(Catalog.GetString("Configuration file: " + TheServerManager.ConfigurationFileName));

                //
                // Connect to main Database
                //
                try
                {
                    TheServerManager.EstablishDBConnection();
                }
                catch (FileNotFoundException ex)
                {
                    TLogging.Log(ex.Message);
                    TLogging.Log("Please check your OpenPetra.build.config file ...");
                    TLogging.Log("Maybe a nant initConfigFile helps ...");
                    throw new EOPAppException();
                }
                catch (Exception ex)
                {
                    TLogging.Log(ex.Message);
                    throw;
                }

                // Setup Server Timed Processing
                try
                {
                    TheServerManager.SetupServerTimedProcessing();
                }
                catch (Exception)
                {
                    throw;
                }

                //
                // Remote the remoteable objects
                //
                try
                {
                    if (TAppSettingsManager.HasValue("LifetimeServices.LeaseTimeInSeconds"))
                    {
                        TLogging.Log(Catalog.GetString("Reading parameters for server remote configuration from config file..."));

                        BinaryServerFormatterSinkProvider TCPSink = new BinaryServerFormatterSinkProvider();
                        TCPSink.TypeFilterLevel = TypeFilterLevel.Low;
                        IServerChannelSinkProvider EncryptionSink = TCPSink;

                        if (TAppSettingsManager.GetValue("Server.ChannelEncryption.PrivateKeyfile", "", false).Length > 0)
                        {
                            EncryptionSink      = new EncryptionServerSinkProvider();
                            EncryptionSink.Next = TCPSink;
                        }

                        Hashtable ChannelProperties = new Hashtable();
                        ChannelProperties.Add("port", TAppSettingsManager.GetValue("Server.Port"));

                        string SpecificIPAddress = TAppSettingsManager.GetValue("ListenOnIPAddress", "", false);

                        if (SpecificIPAddress.Length > 0)
                        {
                            ChannelProperties.Add("machineName", SpecificIPAddress);
                        }

                        TcpChannel Channel = new TcpChannel(ChannelProperties, null, EncryptionSink);
                        ChannelServices.RegisterChannel(Channel, false);

                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(Ict.Petra.Server.App.Core.TServerManager),
                                                                           "Servermanager", WellKnownObjectMode.Singleton);
                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(Ict.Common.Remoting.Server.TClientManager),
                                                                           "Clientmanager", WellKnownObjectMode.Singleton);
                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(TCrossDomainMarshaller),
                                                                           TClientManager.CROSSDOMAINURL, WellKnownObjectMode.Singleton);

                        LifetimeServices.LeaseTime            = TimeSpan.FromSeconds(TAppSettingsManager.GetDouble("LifetimeServices.LeaseTimeInSeconds", 5.0f));
                        LifetimeServices.RenewOnCallTime      = TimeSpan.FromSeconds(TAppSettingsManager.GetDouble("LifetimeServices.RenewOnCallTime", 5.0f));
                        LifetimeServices.LeaseManagerPollTime =
                            TimeSpan.FromSeconds(TAppSettingsManager.GetDouble("LifetimeServices.LeaseManagerPollTime", 1.0f));
                    }
                    else
                    {
                        TLogging.Log(Catalog.GetString("Reading server remote configuration from config file..."));

                        if (TheServerManager.ConfigurationFileName == "")
                        {
                            RemotingConfiguration.Configure(Environment.GetCommandLineArgs()[0] + ".config", false);
                        }
                        else
                        {
                            RemotingConfiguration.Configure(TheServerManager.ConfigurationFileName, false);
                        }

                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(TCrossDomainMarshaller),
                                                                           TClientManager.CROSSDOMAINURL, WellKnownObjectMode.Singleton);
                    }
                }
                catch (RemotingException rex)
                {
                    if (rex.Message.IndexOf("SocketException") > 1)
                    {
                        TLogging.Log("A SocketException has been thrown.");
                        TLogging.Log("Most probably problem is that the address port is used twice!");
                        throw new EOPAppException();
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                Thread.Sleep(50);
                TrackingServices.RegisterTrackingHandler(new TRemotingTracker());

                // Display information that the Server is ready to accept .NET Remoting requests
                TLogging.Log(TheServerManager.ServerInfoState);

                //
                // Server startup done.
                // From now on just listen on .NET Remoting Framework object invocations or on
                // menu commands...
                //

                bool RunWithoutMenu = TAppSettingsManager.GetBoolean("RunWithoutMenu", false);

                if ((!RunWithoutMenu))
                {
                    Console.WriteLine(Environment.NewLine + Catalog.GetString("-> Press \"m\" for menu."));
                    WriteServerPrompt();
                }

                // All exceptions that are raised from various parts of the Server are handled below.
                // Note: The Server stops after handling these exceptions!!!
                if (RunWithoutMenu)
                {
                    RunInBackground();
                }
                else
                {
                    RunMenu();
                }

                // THE VERY END OF THE SERVER :(
            }
            catch (System.Net.Sockets.SocketException exp)
            {
                TLogging.Log(
                    Environment.NewLine + "Unable to start the Server: The IP Port " + TSrvSetting.IPBasePort.ToString() +
                    " is being used by a different instance of the Server or some other application." + Environment.NewLine + exp.ToString());
            }
            catch (System.Runtime.Remoting.RemotingException exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.ToString());
                TLogging.Log(Environment.NewLine + "Exception occured while setting up Remoting Framework:" + Environment.NewLine + exp.ToString());
            }
            catch (EOPAppException)
            {
                // This Exception is used if no more messages shall be done ...
            }
            catch (Exception exp)
            {
                TLogging.Log(Environment.NewLine + "Exception occured:" + Environment.NewLine + exp.ToString());
            }
        }
Example #20
0
        public static void Main(string[] args)
        {
            new TAppSettingsManager(false);

            if (!TAppSettingsManager.HasValue("file"))
            {
                Console.WriteLine("call: echo SELECT * FROM s_user | SQLiteConsole -file:mydatabase.db -password:secret");
                Environment.Exit(1);
            }

            try
            {
                if (!System.IO.File.Exists(TAppSettingsManager.GetValue("file")))
                {
                    Console.WriteLine("database file " + TAppSettingsManager.GetValue("file") + " does not exist");

                    // this is to avoid InitDBConnection trying to find/copy the base database
                    Environment.Exit(1);
                }

                if (!InitDBConnection(TAppSettingsManager.GetValue("file"), TAppSettingsManager.GetValue("password", "")))
                {
                    Console.WriteLine("cannot connect to database " + TAppSettingsManager.GetValue("file"));
                    Environment.Exit(1);
                }

                string SQLCommand = "";
                string line;

                while ((line = Console.ReadLine()) != null && line.Length > 0)
                {
                    SQLCommand += " " + line.Trim();
                }

                TDBTransaction transaction = new TDBTransaction();
                DataTable      result      = null;
                db.ReadTransaction(ref transaction,
                                   delegate
                {
                    result = db.SelectDT(SQLCommand, "temp", transaction);
                });

                if (result == null)
                {
                    TLogging.Log("The query returned a NULL table of results!");
                }
                else
                {
                    TDataBase.LogTable(result);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            if (db.ConnectionOK)
            {
                db.CloseDBConnection();
            }
        }
Example #21
0
        public static void Main(string[] args)
        {
            new TAppSettingsManager(false);

            //enable execution without nant -> debugging easier
            bool independentmode = false;

            if (independentmode)
            {
                TLogging.Log("started in independent-mode");
            }

            try
            {
                if ((TAppSettingsManager.HasValue("do") && (TAppSettingsManager.GetValue("do") == "removeDoNotTranslate")) || independentmode)
                {
                    string doNotTranslatePath;
                    string poFilePath;

                    if (independentmode)
                    {
                        doNotTranslatePath = "E:\\openpetra\\bzr\\work-690\\i18n\\doNotTranslate.po";
                        poFilePath         = "E:\\openpetra\\bzr\\work-690\\i18n\\template.pot";
                    }
                    else
                    {
                        doNotTranslatePath = TAppSettingsManager.GetValue("dntFile");
                        poFilePath         = TAppSettingsManager.GetValue("poFile");
                    }

                    // remove all strings from po file that are listed in the "Do Not Translate" file
                    TDropUnwantedStrings.RemoveUnwantedStringsFromTranslation(doNotTranslatePath, poFilePath);
                }
                else if (TAppSettingsManager.HasValue("do") && (TAppSettingsManager.GetValue("do") == "errorcodedoc"))
                {
                    TGenerateErrorCodeDoc.Execute(TAppSettingsManager.GetValue("csharppath"),
                                                  TAppSettingsManager.GetValue("templatefilepath"),
                                                  TAppSettingsManager.GetValue("outfilepath"));
                }
                else if (TAppSettingsManager.HasValue("do") && (TAppSettingsManager.GetValue("do") == "yamlfiles"))
                {
                    GenerateYamlFiles.WriteYamlFiles(
                        TAppSettingsManager.GetValue("language"),
                        TAppSettingsManager.GetValue("path"),
                        TAppSettingsManager.GetValue("pofile"));
                }
                else if (TAppSettingsManager.HasValue("file"))
                {
                    TGenerateCatalogStrings.Execute(TAppSettingsManager.GetValue("file"), null, null);
                }
                else if (TAppSettingsManager.HasValue("filelist"))
                {
                    TDataDefinitionStore store = new TDataDefinitionStore();
                    Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true));
                    TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true));
                    parser.ParseDocument(ref store, true, true);

                    string CollectedStringsFilename = TAppSettingsManager.GetValue("tmpPath") +
                                                      Path.DirectorySeparatorChar +
                                                      "GenerateI18N.CollectedGettext.cs";
                    StreamWriter writerCollectedStringsFile = new StreamWriter(CollectedStringsFilename);

                    string GettextApp = TAppSettingsManager.GetValue("gettext");

                    string       filesToParseWithGettext = string.Empty;
                    StreamReader readerFilelist          = new StreamReader(TAppSettingsManager.GetValue("filelist"));

                    while (!readerFilelist.EndOfStream)
                    {
                        string pathCodeFile = readerFilelist.ReadLine().Trim();
                        string ext          = Path.GetExtension(pathCodeFile);

                        if (".cs" == ext)
                        {
                            if (TGenerateCatalogStrings.Execute(pathCodeFile, store, writerCollectedStringsFile))
                            {
                                filesToParseWithGettext += "\"" + pathCodeFile + "\" ";

                                if (filesToParseWithGettext.Length > 1500)
                                {
                                    ParseWithGettext(GettextApp, TAppSettingsManager.GetValue("poFile"), filesToParseWithGettext);
                                    filesToParseWithGettext = string.Empty;
                                }
                            }
                        }
                        else if (".yml" == ext)
                        {
                            TGenerateCatalogStrings.AddTranslationUINavigation(pathCodeFile, writerCollectedStringsFile);
                        }
                        else
                        {
                            Console.WriteLine("the file " + pathCodeFile + " has an unknown extension! File ignored!");
                        }
                    }

                    if (filesToParseWithGettext.Length > 0)
                    {
                        ParseWithGettext(GettextApp, TAppSettingsManager.GetValue("poFile"), filesToParseWithGettext);
                    }

                    writerCollectedStringsFile.Close();

                    // delete the file if it is empty
                    if (File.ReadAllText(CollectedStringsFilename).Length == 0)
                    {
                        File.Delete(CollectedStringsFilename);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Environment.Exit(-1);
            }
        }
Example #22
0
        /// <summary>
        /// Initialises the internal variables that hold the Server Settings, using the current config file.
        ///
        /// </summary>
        /// <returns>void</returns>
        public TSrvSetting()
        {
            if (USingletonSrvSetting == null)
            {
                USingletonSrvSetting = this;
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            FApplicationVersion = TFileVersionInfo.GetApplicationVersion();
        }