Exemplo n.º 1
0
        /// Copy constructor
        public TSrvSetting(TSrvSetting ACopyFrom)
        {
            if (USingletonSrvSetting == null)
            {
                USingletonSrvSetting = this;
            }

            FConfigurationFile                            = ACopyFrom.FConfigurationFile;
            FExecutingOS                                  = ACopyFrom.FExecutingOS;
            FRDBMSType                                    = ACopyFrom.FRDBMSType;
            FDatabaseHostOrFile                           = ACopyFrom.FDatabaseHostOrFile;
            FDatabasePort                                 = ACopyFrom.FDatabasePort;
            FDatabaseName                                 = ACopyFrom.FDatabaseName;
            FDBUsername                                   = ACopyFrom.FDBUsername;
            FDBPassword                                   = ACopyFrom.FDBPassword;
            FIPBasePort                                   = ACopyFrom.FIPBasePort;
            FServerLogFile                                = ACopyFrom.FServerLogFile;
            FHostName                                     = ACopyFrom.FHostName;
            FHostIPAddresses                              = ACopyFrom.FHostIPAddresses;
            FClientIdleStatusAfterXMinutes                = ACopyFrom.FClientIdleStatusAfterXMinutes;
            FClientKeepAliveCheckIntervalInSeconds        = ACopyFrom.FClientKeepAliveCheckIntervalInSeconds;
            FClientKeepAliveTimeoutAfterXSecondsLAN       = ACopyFrom.FClientKeepAliveTimeoutAfterXSecondsLAN;
            FClientKeepAliveTimeoutAfterXSecondsRemote    = ACopyFrom.FClientKeepAliveTimeoutAfterXSecondsRemote;
            FClientConnectionTimeoutAfterXSeconds         = ACopyFrom.FClientConnectionTimeoutAfterXSeconds;
            FClientAppDomainShutdownAfterKeepAliveTimeout = ACopyFrom.FClientAppDomainShutdownAfterKeepAliveTimeout;
            FApplicationVersion                           = ACopyFrom.FApplicationVersion;
            FSMTPServer                                   = ACopyFrom.FSMTPServer;
            FAutomaticIntranetExportEnabled               = ACopyFrom.FAutomaticIntranetExportEnabled;
            FRunAsStandalone                              = ACopyFrom.FRunAsStandalone;
            FIntranetDataDestinationEmail                 = ACopyFrom.FIntranetDataDestinationEmail;
            FIntranetDataSenderEmail                      = ACopyFrom.FIntranetDataSenderEmail;
            FApplicationBinFolder                         = ACopyFrom.FApplicationBinFolder;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initialises the internal variables that hold the Server Settings, using the current config file.
        ///
        /// </summary>
        /// <returns>void</returns>
        public TSrvSetting()
        {
            FConfigurationFile = TAppSettingsManager.ConfigFileName;
            FExecutingOS       = Utilities.DetermineExecutingOS();

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

            FApplicationBinFolder = TAppSettingsManager.GetValue("Server.ApplicationBinDirectory", string.Empty, false);

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

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

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

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

            FApplicationVersion = TFileVersionInfo.GetApplicationVersion();
        }
Exemplo n.º 3
0
        /// <summary>
        /// todoComment
        /// </summary>
        public static void InitializeUnit()
        {
            Networking.DetermineNetworkConfig(out UClientComputerName, out UClientIPAddress);
            UClientOS = Utilities.DetermineExecutingOS();
            UClientAssemblyVersion = TFileVersionInfo.GetApplicationVersion().ToString();

            if (TClientSettings.RunAsRemote)
            {
                UInstallationKind = "Remote Client";
            }
            else
            {
                if (TClientSettings.RunAsStandalone)
                {
                    UInstallationKind = "Standalone Installation";
                }
                else
                {
                    UInstallationKind = "Network Client";
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// todoComment
        /// </summary>
        public static void InitializeUnit()
        {
            Networking.DetermineNetworkConfig(out UClientComputerName, out UClientIPAddress);
            UClientOS = Utilities.DetermineExecutingOS();
            UClientAssemblyVersion = TFileVersionInfo.GetApplicationVersion().ToString();

            if (TClientSettings.RunAsRemote)
            {
                UInstallationKind = "Remote Client";
            }
            else
            {
                if (TClientSettings.RunAsStandalone)
                {
                    UInstallationKind = "Standalone Installation";
                }
                else
                {
                    UInstallationKind = "Network Client";
                }
            }
        }
Exemplo n.º 5
0
        /// Copy constructor
        public TSrvSetting(TSrvSetting ACopyFrom)
        {
            if (USingletonSrvSetting == null)
            {
                USingletonSrvSetting = this;
            }

            FConfigurationFile         = ACopyFrom.FConfigurationFile;
            FExecutingOS               = ACopyFrom.FExecutingOS;
            FRDBMSType                 = ACopyFrom.FRDBMSType;
            FDatabaseHostOrFile        = ACopyFrom.FDatabaseHostOrFile;
            FDatabasePort              = ACopyFrom.FDatabasePort;
            FDatabaseName              = ACopyFrom.FDatabaseName;
            FDBUsername                = ACopyFrom.FDBUsername;
            FDBPassword                = ACopyFrom.FDBPassword;
            FDBConnectionCheckInterval = ACopyFrom.FDBConnectionCheckInterval;
            FIPBasePort                = ACopyFrom.FIPBasePort;
            FServerLogFile             = ACopyFrom.FServerLogFile;
            FHostName        = ACopyFrom.FHostName;
            FHostIPAddresses = ACopyFrom.FHostIPAddresses;
            FClientIdleStatusAfterXMinutes                = ACopyFrom.FClientIdleStatusAfterXMinutes;
            FClientKeepAliveCheckIntervalInSeconds        = ACopyFrom.FClientKeepAliveCheckIntervalInSeconds;
            FClientKeepAliveTimeoutAfterXSecondsLAN       = ACopyFrom.FClientKeepAliveTimeoutAfterXSecondsLAN;
            FClientKeepAliveTimeoutAfterXSecondsRemote    = ACopyFrom.FClientKeepAliveTimeoutAfterXSecondsRemote;
            FClientConnectionTimeoutAfterXSeconds         = ACopyFrom.FClientConnectionTimeoutAfterXSeconds;
            FClientAppDomainShutdownAfterKeepAliveTimeout = ACopyFrom.FClientAppDomainShutdownAfterKeepAliveTimeout;
            FApplicationVersion     = ACopyFrom.FApplicationVersion;
            FSmtpHost               = ACopyFrom.FSmtpHost;
            FSmtpPort               = ACopyFrom.FSmtpPort;
            FSmtpUser               = ACopyFrom.FSmtpUser;
            FSmtpPassword           = ACopyFrom.FSmtpPassword;
            FSmtpEnableSsl          = ACopyFrom.FSmtpEnableSsl;
            FSmtpAuthenticationType = ACopyFrom.FSmtpAuthenticationType;
            FSmtpIgnoreServerCertificateValidation = ACopyFrom.FSmtpIgnoreServerCertificateValidation;
            FRunAsStandalone      = ACopyFrom.FRunAsStandalone;
            FApplicationBinFolder = ACopyFrom.FApplicationBinFolder;
        }
Exemplo n.º 6
0
 /// <summary>
 /// convert the enum to string for the Operating System
 /// </summary>
 /// <param name="AExecutingOS">defines the operating system</param>
 /// <returns>string representing the operating system</returns>
 public static String ExecutingOSEnumToString(TExecutingOSEnum AExecutingOS)
 {
     return(ExecutingOSEnumToString(AExecutingOS, false));
 }
Exemplo n.º 7
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();
        }
Exemplo n.º 8
0
        /// Copy constructor
        public TSrvSetting(TSrvSetting ACopyFrom)
        {
            if (USingletonSrvSetting == null)
            {
                USingletonSrvSetting = this;
            }

            FConfigurationFile = ACopyFrom.FConfigurationFile;
            FExecutingOS = ACopyFrom.FExecutingOS;
            FRDBMSType = ACopyFrom.FRDBMSType;
            FDatabaseHostOrFile = ACopyFrom.FDatabaseHostOrFile;
            FDatabasePort = ACopyFrom.FDatabasePort;
            FDatabaseName = ACopyFrom.FDatabaseName;
            FDBUsername = ACopyFrom.FDBUsername;
            FDBPassword = ACopyFrom.FDBPassword;
            FIPBasePort = ACopyFrom.FIPBasePort;
            FServerLogFile = ACopyFrom.FServerLogFile;
            FHostName = ACopyFrom.FHostName;
            FHostIPAddresses = ACopyFrom.FHostIPAddresses;
            FClientIdleStatusAfterXMinutes = ACopyFrom.FClientIdleStatusAfterXMinutes;
            FClientKeepAliveCheckIntervalInSeconds = ACopyFrom.FClientKeepAliveCheckIntervalInSeconds;
            FClientKeepAliveTimeoutAfterXSecondsLAN = ACopyFrom.FClientKeepAliveTimeoutAfterXSecondsLAN;
            FClientKeepAliveTimeoutAfterXSecondsRemote = ACopyFrom.FClientKeepAliveTimeoutAfterXSecondsRemote;
            FClientConnectionTimeoutAfterXSeconds = ACopyFrom.FClientConnectionTimeoutAfterXSeconds;
            FClientAppDomainShutdownAfterKeepAliveTimeout = ACopyFrom.FClientAppDomainShutdownAfterKeepAliveTimeout;
            FApplicationVersion = ACopyFrom.FApplicationVersion;
            FSMTPServer = ACopyFrom.FSMTPServer;
            FAutomaticIntranetExportEnabled = ACopyFrom.FAutomaticIntranetExportEnabled;
            FRunAsStandalone = ACopyFrom.FRunAsStandalone;
            FIntranetDataDestinationEmail = ACopyFrom.FIntranetDataDestinationEmail;
            FIntranetDataSenderEmail = ACopyFrom.FIntranetDataSenderEmail;
        }
        /// <summary>
        /// Runs a test on posting a batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The data row corresponding to the batch to post</param>
        public void TestPostBatch(ABatchRow ACurrentBatchRow)
        {
            if (!SaveBatchForPosting())
            {
                return;
            }

            TVerificationResultCollection Verifications;
            TFrmExtendedMessageBox        ExtendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

            FMyForm.Cursor = Cursors.WaitCursor;

            List <TVariant> Result = TRemote.MFinance.GL.WebConnectors.TestPostGLBatch(FLedgerNumber, ACurrentBatchRow.BatchNumber, out Verifications);

            try
            {
                if ((Verifications != null) && (Verifications.Count > 0))
                {
                    string ErrorMessages = string.Empty;

                    foreach (TVerificationResult verif in Verifications)
                    {
                        ErrorMessages += "[" + verif.ResultContext + "] " +
                                         verif.ResultTextCaption + ": " +
                                         verif.ResultText + Environment.NewLine;
                    }

                    ExtendedMessageBox.ShowDialog(ErrorMessages,
                                                  Catalog.GetString("Test Post Failed"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
                else
                {
                    string header  = string.Empty;
                    string message = string.Empty;

                    foreach (TVariant value in Result)
                    {
                        ArrayList compValues = value.ToComposite();

                        message += String.Format(Catalog.GetString("--{1}/{0} ({3}/{2}) is: {4} and would be: {5}{6}"),
                                                 ((TVariant)compValues[0]).ToString(),
                                                 ((TVariant)compValues[2]).ToString(),
                                                 ((TVariant)compValues[1]).ToString(),
                                                 ((TVariant)compValues[3]).ToString(),
                                                 StringHelper.FormatCurrency((TVariant)compValues[4], "currency"),
                                                 StringHelper.FormatCurrency((TVariant)compValues[5], "currency"),
                                                 Environment.NewLine);
                    }

                    if (Result.Count > 25)
                    {
                        string line = new String('_', 70);
                        header =
                            String.Format(Catalog.GetString(
                                              "{0}{1}{1}{2} results listed below. Do you want to export this list to a CSV file?{1}{0}{1}{1}"),
                                          line,
                                          Environment.NewLine,
                                          Result.Count);

                        if (ExtendedMessageBox.ShowDialog((header + message),
                                                          Catalog.GetString("Result of Test Posting"), string.Empty,
                                                          TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                          TFrmExtendedMessageBox.TIcon.embiQuestion) == TFrmExtendedMessageBox.TResult.embrYes)
                        {
                            // store to CSV file
                            string cSVForExport  = string.Empty;
                            string messageExport = string.Empty;

                            foreach (TVariant value in Result)
                            {
                                ArrayList compValues = value.ToComposite();

                                string[] columns = new string[] {
                                    ((TVariant)compValues[0]).ToString(),
                                    ((TVariant)compValues[1]).ToString(),
                                    ((TVariant)compValues[2]).ToString(),
                                    ((TVariant)compValues[3]).ToString(),
                                    StringHelper.FormatCurrency((TVariant)compValues[4], "CurrencyCSV"),
                                    StringHelper.FormatCurrency((TVariant)compValues[5], "CurrencyCSV")
                                };

                                cSVForExport += StringHelper.StrMerge(columns,
                                                                      Thread.CurrentThread.CurrentCulture.TextInfo.ListSeparator[0]) +
                                                Environment.NewLine;
                            }

                            try
                            {
                                string CSVFilePath = TClientSettings.PathLog + Path.DirectorySeparatorChar + "Batch" +
                                                     ACurrentBatchRow.BatchNumber.ToString() +
                                                     "_TestPosting.csv";

                                StreamWriter sw = new StreamWriter(CSVFilePath, false, System.Text.Encoding.UTF8);
                                sw.Write(cSVForExport);
                                sw.Close();

                                messageExport = String.Format(Catalog.GetString("Please see the results in the file:{1}{1}'{0}'{1}{1}"),
                                                              CSVFilePath,
                                                              Environment.NewLine);
                                messageExport += "Do you want to open the file for viewing now?";

                                if (MessageBox.Show(messageExport,
                                                    Catalog.GetString("Result of Test Posting"),
                                                    MessageBoxButtons.YesNo,
                                                    MessageBoxIcon.Question) == DialogResult.Yes)
                                {
                                    try
                                    {
                                        ProcessStartInfo si = new ProcessStartInfo(CSVFilePath);
                                        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: '") + CSVFilePath + "'!", Catalog.GetString(
                                                            "Result of Test Posting"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);


                                        //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}\"", CSVFilePath));
                                            }
                                            catch
                                            {
                                                MessageBox.Show(Catalog.GetString(
                                                                    "Unable to launch Windows File Explorer to open: '") + CSVFilePath + "'!", Catalog.GetString(
                                                                    "Result of Test Posting"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error trying to export test posting results to CSV file: " + ex.Message,
                                                "Test Posting Results Export",
                                                MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        ExtendedMessageBox.ShowDialog(message,
                                                      Catalog.GetString("Result of Test Posting"), string.Empty,
                                                      TFrmExtendedMessageBox.TButtons.embbOK,
                                                      TFrmExtendedMessageBox.TIcon.embiInformation);
                    }
                }
            }
            finally
            {
                FMyForm.Cursor = Cursors.Default;
            }
        }
Exemplo n.º 10
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>
        private void BtnOK_Click(object sender, EventArgs e)
        {
            FExportFileName = txtFilename.Text;
            String fileContents = string.Empty;
            Int32  budgetCount  = 0;

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

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

                FExportFileName = string.Empty;
                return;
            }

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

                try
                {
                    File.Delete(FExportFileName);
                }
                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 Budget"),
                                    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("NumberFormat", ConvertNumberFormat(cmbNumberFormat));

            TVerificationResultCollection AMessages;

            string[] delims = new string[1];
            delims[0] = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

            TFrmStatusDialog dlgStatus = null;

            try
            {
                this.Cursor = Cursors.WaitCursor;

                dlgStatus = new TFrmStatusDialog(FPetraUtilsObject.GetForm());

                dlgStatus.Show();
                dlgStatus.Heading       = Catalog.GetString("Exporting Budgets");
                dlgStatus.CurrentStatus = Catalog.GetString("Exporting budget data for this year and next...");

                budgetCount = TRemote.MFinance.Budget.WebConnectors.ExportBudgets(FLedgerNumber,
                                                                                  FExportFileName,
                                                                                  delims,
                                                                                  ref fileContents,
                                                                                  ref FBudgetDS,
                                                                                  out AMessages);

                dlgStatus.Close();
                dlgStatus = null;

                this.Cursor = Cursors.Default;

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

                        FExportFileName = string.Empty;
                        return;
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                SaveUserDefaults();

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

                    FExportFileName = string.Empty;
                    return;
                }

                StreamWriter sw1 = new StreamWriter(FExportFileName);
                sw1.Write(fileContents);
                sw1.Close();
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                this.Cursor = Cursors.Default;

                if (dlgStatus != null)
                {
                    dlgStatus.Close();
                    dlgStatus = null;
                }
            }

            bool ShowExportedFileInExplorer = false;

            // Offer the client the chance to open the file in Excel or whatever
            if (MessageBox.Show(String.Format(Catalog.GetString(
                                                  "{0} Budget rows were exported successfully! Would you like to open the file in your default application?"),
                                              budgetCount.ToString()),
                                Catalog.GetString("Budget Export"),
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Information,
                                MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    ProcessStartInfo si = new ProcessStartInfo(FExportFileName);
                    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: '") + FExportFileName + "'!", Catalog.GetString(
                                        "Budget 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}\"", FExportFileName));
                    }
                    catch
                    {
                        MessageBox.Show(Catalog.GetString(
                                            "Unable to launch Windows File Explorer to open: '") + FExportFileName + "'!", Catalog.GetString(
                                            "Budget Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }

            Close();
        }
Exemplo n.º 11
0
        /// <summary>
        /// convert the enum to string for the Operating System
        /// </summary>
        /// <param name="AExecutingOS">defines the operating system</param>
        /// <param name="ALongDescription">we want a long description of the OS</param>
        /// <returns>string representing the operating system</returns>
        public static String ExecutingOSEnumToString(TExecutingOSEnum AExecutingOS, Boolean ALongDescription)
        {
            String ReturnValue;

            switch (AExecutingOS)
            {
            case TExecutingOSEnum.eosLinux:
                ReturnValue = "Linux";
                break;

            case TExecutingOSEnum.eosWin98ToWinME:

                if (ALongDescription)
                {
                    ReturnValue = "Windows98 to WindowsME";
                }
                else
                {
                    ReturnValue = "Windows98/ME";
                }

                break;

            case TExecutingOSEnum.eosWinXP:
                return("Windows XP / Server 2003");

            case TExecutingOSEnum.eosWinVista:
                return("Windows Vista");

            case TExecutingOSEnum.eosWin7:
                return("Windows 7 / Server 2008");

            case TExecutingOSEnum.eosWinNTOrLater:

                if (ALongDescription)
                {
                    ReturnValue = "WindowsNT or later";
                }
                else
                {
                    ReturnValue = "WindowsNT/XP/Win7/2008";
                }

                break;

            case TExecutingOSEnum.oesUnsupportedPlatform:

                if (ALongDescription)
                {
                    ReturnValue = "#UNSUPPORTED PLATFORM!#";
                }
                else
                {
                    ReturnValue = "#UNSUPPORTED!#";
                }

                break;

            default:
                ReturnValue = null;
                break;
            }

            return(ReturnValue);
        }
Exemplo n.º 12
0
        /// <summary>
        /// convert the enum to string for the Operating System
        /// </summary>
        /// <param name="AExecutingOS">defines the operating system</param>
        /// <param name="ALongDescription">we want a long description of the OS</param>
        /// <returns>string representing the operating system</returns>
        public static String ExecutingOSEnumToString(TExecutingOSEnum AExecutingOS, Boolean ALongDescription)
        {
            String ReturnValue;

            switch (AExecutingOS)
            {
                case TExecutingOSEnum.eosLinux:
                    ReturnValue = "Linux";
                    break;

                case TExecutingOSEnum.eosWin98ToWinME:

                    if (ALongDescription)
                    {
                        ReturnValue = "Windows98 to WindowsME";
                    }
                    else
                    {
                        ReturnValue = "Windows98/ME";
                    }

                    break;

                case TExecutingOSEnum.eosWinXP:
                    return "Windows XP / Server 2003";

                case TExecutingOSEnum.eosWinVista:
                    return "Windows Vista";

                case TExecutingOSEnum.eosWin7:
                    return "Windows 7 / Server 2008";

                case TExecutingOSEnum.eosWinNTOrLater:

                    if (ALongDescription)
                    {
                        ReturnValue = "WindowsNT or later";
                    }
                    else
                    {
                        ReturnValue = "WindowsNT/XP/Win7/2008";
                    }

                    break;

                case TExecutingOSEnum.oesUnsupportedPlatform:

                    if (ALongDescription)
                    {
                        ReturnValue = "#UNSUPPORTED PLATFORM!#";
                    }
                    else
                    {
                        ReturnValue = "#UNSUPPORTED!#";
                    }

                    break;

                default:
                    ReturnValue = null;
                    break;
            }

            return ReturnValue;
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
0
 /// <summary>
 /// Constructor that initialises the property values.
 ///
 /// @todo Change the class to retrieve the Server info on its own on
 ///
 /// </summary>
 /// <param name="ServerOS">Operating System of the PetraServer that the Client is
 /// connected to
 /// </param>
 /// <returns>void</returns>
 public TServerInfo(TExecutingOSEnum ServerOS)
 {
     // TODO ochristiank cServer_Info : Load Server info from Server.
     PServerOS = ServerOS;
 }
Exemplo n.º 15
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);

            FApplicationBinFolder = TAppSettingsManager.GetValue("Server.ApplicationBinDirectory", string.Empty, false);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            FApplicationVersion = TFileVersionInfo.GetApplicationVersion();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initialises the internal variables that hold the Server Settings, using the current config file.
        ///
        /// </summary>
        /// <returns>void</returns>
        public TSrvSetting()
        {
            if (USingletonSrvSetting == null)
            {
                USingletonSrvSetting = this;
            }

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

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

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

            FApplicationBinFolder = TAppSettingsManager.GetValue("Server.ApplicationBinDirectory", string.Empty, false);

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

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

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

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

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

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

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

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

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

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

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

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

            FSmtpHost               = TAppSettingsManager.GetValue("SmtpHost", "");
            FSmtpPort               = TAppSettingsManager.GetInt32("SmtpPort", 25);
            FSmtpUser               = TAppSettingsManager.GetValue("SmtpUser", "YourSmtpUser");
            FSmtpPassword           = TAppSettingsManager.GetValue("SmtpPassword", "YourSmtpPassword");
            FSmtpEnableSsl          = TAppSettingsManager.GetBoolean("SmtpEnableSsl", true);
            FSmtpAuthenticationType = TAppSettingsManager.GetValue("SmtpAuthenticationType", "config").ToLower();
            FSmtpIgnoreServerCertificateValidation = TAppSettingsManager.GetBoolean("IgnoreServerCertificateValidation", false);

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

            FApplicationVersion = TFileVersionInfo.GetApplicationVersion();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Public method to export GL batches
        /// </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 Batches"),
                                    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 GL 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.ValidDate()) || (!dtpDateTo.ValidDate()))
                {
                    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);
            }

            // Save the defaults
            SaveUserDefaults();

            String dateFormatString = cmbDateFormat.GetSelectedString();

            // might be called from the main navigation window (FMainDS is null), or from the GL Batch screen (reusing MainDS)
            if (FMainDS == null)
            {
                FMainDS = new Ict.Petra.Shared.MFinance.GL.Data.GLBatchTDS();
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatch(FLedgerNumber, -1, -1));
            }

            Int32 ALedgerNumber = 0;

            ArrayList batches = new ArrayList();

            foreach (ABatchRow batch in FMainDS.ABatch.Rows)
            {
                // check conditions for exporting this batch
                // Batch Status
                bool exportThisBatch = batch.BatchStatus.Equals(MFinanceConstants.BATCH_POSTED) ||
                                       (chkIncludeUnposted.Checked && batch.BatchStatus.Equals(MFinanceConstants.BATCH_UNPOSTED));

                if (rbtBatchNumberSelection.Checked)
                {
                    exportThisBatch &= (batch.BatchNumber >= txtBatchNumberStart.NumberValueInt);
                    exportThisBatch &= (batch.BatchNumber <= txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    exportThisBatch &= (batch.DateEffective >= dtpDateFrom.Date);
                    exportThisBatch &= (batch.DateEffective <= dtpDateTo.Date);
                }

                if (exportThisBatch)
                {
                    batches.Add(batch.BatchNumber);
                }

                ALedgerNumber = batch.LedgerNumber;
            }

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

            // Do the actual export work
            try
            {
                Hashtable requestParams = new Hashtable();
                requestParams.Add("ALedgerNumber", ALedgerNumber);
                requestParams.Add("Delimiter", delimiter);
                requestParams.Add("DateFormatString", dateFormatString);
                requestParams.Add("Summary", rbtSummary.Checked);
                requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
                requestParams.Add("BaseCurrency", FMainDS.ALedger[0].BaseCurrency);
                requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
                requestParams.Add("bDontSummarize", chkDontSummarize.Checked);
                requestParams.Add("DontSummarizeAccount", cmbDontSummarizeAccount.GetSelectedString());
                requestParams.Add("DateForSummary", dtpDateSummary.Date);
                requestParams.Add("NumberFormat", numberFormat);

                String exportString = null;
                Thread ExportThread = new Thread(() => ExportAllGLBatchData(batches, requestParams, out exportString));
                using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
                {
                    ExportDialog.ShowDialog();
                }

                // Now we have the string we can write it to the file
                StreamWriter sw1 = new StreamWriter(ExportFileName);
                sw1.Write(exportString);
                sw1.Close();
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }

            bool ShowExportedFileInExplorer = false;

            if (AWithInteractionOnSuccess)
            {
                if (MessageBox.Show(Catalog.GetString(
                                        "GL Batches Exported successfully. Would you like to open the file in your default application?"),
                                    Catalog.GetString("GL 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(
                                            "GL 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(
                                            "GL Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 18
0
 /// <summary>
 /// convert the enum to string for the Operating System
 /// </summary>
 /// <param name="AExecutingOS">defines the operating system</param>
 /// <returns>string representing the operating system</returns>
 public static String ExecutingOSEnumToString(TExecutingOSEnum AExecutingOS)
 {
     return ExecutingOSEnumToString(AExecutingOS, false);
 }
Exemplo n.º 19
0
        /// <summary>
        /// Called by a Client to request connection to the Petra Server.
        ///
        /// Creates an AppDomain, loads Petra Module DLL's into it and returns
        /// .NET Remoting URLs for intantiated objects that represent the Petra Module
        /// Root Namespaces (eg. MPartner, MFinance).
        ///
        /// </summary>
        /// <param name="AUserName">Username with which the Client connects</param>
        /// <param name="APassword">Password with which the Client connects</param>
        /// <param name="AClientComputerName">Computer name of the Client</param>
        /// <param name="AClientExeVersion"></param>
        /// <param name="AClientIPAddress">IP Address of the Client</param>
        /// <param name="AClientServerConnectionType">Type of the connection (eg. LAN, Remote)</param>
        /// <param name="AClientName">Server-assigned Name of the Client</param>
        /// <param name="AClientID">Server-assigned ID of the Client</param>
        /// <param name="ACrossDomainURL">there is only one url now for connecting to the services</param>
        /// <param name="ARemotingURLs">A HashTable containing .NET Remoting URLs of the Petra
        /// Module Root Namespaces (eg. MPartner, MFinance) and other important objects
        /// that need to be called from the Client.</param>
        /// <param name="AServerOS">Operating System that the Server is running on
        /// </param>
        /// <param name="AProcessID"></param>
        /// <param name="AWelcomeMessage"></param>
        /// <param name="ASystemEnabled"></param>
        /// <param name="AUserInfo"></param>
        /// <returns>void</returns>
        public void ConnectClient(String AUserName,
            String APassword,
            String AClientComputerName,
            String AClientIPAddress,
            System.Version AClientExeVersion,
            TClientServerConnectionType AClientServerConnectionType,
            out String AClientName,
            out System.Int32 AClientID,
            out string ACrossDomainURL,
            out Hashtable ARemotingURLs,
            out TExecutingOSEnum AServerOS,
            out Int32 AProcessID,
            out String AWelcomeMessage,
            out Boolean ASystemEnabled,
            out IPrincipal AUserInfo)
        {
            String LoadInAppDomainName;
            IClientAppDomainConnection ClientDomainManager = null;
            String RemotingURL_RemotedObject = "";
            String RemotingURL_PollClientTasks;
            TRunningAppDomain AppDomainEntry;
            String CantDisconnectReason;

            ACrossDomainURL = CROSSDOMAINURL;

            if (TLogging.DL >= 10)
            {
                TLogging.Log(
                    "Loaded Assemblies in AppDomain " + Thread.GetDomain().FriendlyName + " (at call of ConnectClient):", TLoggingType.ToConsole |
                    TLoggingType.ToLogfile);

                foreach (Assembly tmpAssembly in Thread.GetDomain().GetAssemblies())
                {
                    TLogging.Log(tmpAssembly.FullName, TLoggingType.ToConsole | TLoggingType.ToLogfile);
                }
            }

            /*
             * Every Client Connection request is coming in in a separate Thread
             * (.NET Remoting does that for us and this is good!). However, the next block
             * of code must be executed only by exactly ONE thread at the same time to
             * preserve the integrity of Client tracking!
             */
            try
            {
                if (Monitor.TryEnter(UConnectClientMonitor, TSrvSetting.ClientConnectionTimeoutAfterXSeconds * 1000))
                {
                    #region Logging

                    if (TLogging.DL >= 4)
                    {
                        Console.WriteLine(FormatClientList(false));
                        Console.WriteLine(FormatClientList(true));
                    }

                    if (TLogging.DL >= 4)
                    {
                        TLogging.Log("Client '" + AUserName + "' is connecting...", TLoggingType.ToConsole | TLoggingType.ToLogfile);
                    }
                    else
                    {
                        TLogging.Log("Client '" + AUserName + "' is connecting...", TLoggingType.ToLogfile);
                    }

                    #endregion
                    #region Variable assignments
                    ARemotingURLs = new Hashtable(6);
                    AClientID = (short)FClientsConnectedTotal;
                    FClientsConnectedTotal++;
                    AClientName = AUserName.ToUpper() + "_" + AClientID.ToString();
                    AServerOS = TSrvSetting.ExecutingOS;
                    LoadInAppDomainName = AClientName + "_Domain";
                    #endregion
                    try
                    {
                        if (Monitor.TryEnter(UClientObjects.SyncRoot))
                        {
                            // Add the new Client to UClientObjects SortedList
                            UClientObjects.Add((object)AClientID,
                                new TRunningAppDomain(AClientID, AUserName.ToUpper(), AClientName, AClientComputerName, AClientIPAddress,
                                    AClientServerConnectionType, LoadInAppDomainName));
                        }
                    }
                    finally
                    {
                        Monitor.Exit(UClientObjects.SyncRoot);
                    }

                    #region Client Version vs. Server Version check

                    if (TLogging.DL >= 9)
                    {
                        Console.WriteLine(
                            "Client EXE Program Version: " + AClientExeVersion.ToString() + "; Server EXE Program Version: " +
                            TSrvSetting.ApplicationVersion.ToString());
                    }

                    if (TSrvSetting.ApplicationVersion.Compare(new TFileVersionInfo(AClientExeVersion)) != 0)
                    {
                        ((TRunningAppDomain)UClientObjects[(object)AClientID]).AppDomainStatus = TAppDomainStatus.adsStopped;
                        #region Logging

                        if (TLogging.DL >= 4)
                        {
                            TLogging.Log(
                                "Client '" + AUserName + "' tried to connect, but its Program Version (" + AClientExeVersion.ToString() +
                                ") doesn't match! Aborting Client Connection!", TLoggingType.ToConsole | TLoggingType.ToLogfile);
                        }
                        else
                        {
                            TLogging.Log(
                                "Client '" + AUserName + "' tried to connect, but its Program Version (" + AClientExeVersion.ToString() +
                                ") doesn't match! Aborting Client Connection!", TLoggingType.ToLogfile);
                        }

                        #endregion
                        throw new EClientVersionMismatchException(String.Format(StrClientServerExeProgramVersionMismatchMessage,
                                AClientExeVersion.ToString(), TSrvSetting.ApplicationVersion.ToString()));
                    }

                    #endregion

                    #region Login request verification (incl. User authentication)

                    // Perform login checks such as User authentication and Site Key check
                    try
                    {
                        AUserInfo = PerformLoginChecks(AUserName,
                            APassword,
                            AClientComputerName,
                            AClientIPAddress,
                            out AProcessID,
                            out ASystemEnabled);
                    }
                    catch (EPetraSecurityException)
                    #region Exception handling
                    {
                        #region Logging

                        if (TLogging.DL >= 4)
                        {
                            TLogging.Log("Client '" + AUserName + "' tried to connect, but it failed the Login Checks. Aborting Client Connection!",
                                TLoggingType.ToConsole | TLoggingType.ToLogfile);
                        }
                        else
                        {
                            TLogging.Log("Client '" + AUserName + "' tried to connect, but it failed the Login Checks. Aborting Client Connection!",
                                TLoggingType.ToLogfile);
                        }

                        #endregion
                        ((TRunningAppDomain)UClientObjects[(object)AClientID]).AppDomainStatus = TAppDomainStatus.adsStopped;
                        throw;
                    }
                    catch (Exception)
                    {
                        ((TRunningAppDomain)UClientObjects[(object)AClientID]).AppDomainStatus = TAppDomainStatus.adsStopped;
                        throw;
                    }
                    #endregion

                    // Login Checks were successful!
                    ((TRunningAppDomain)UClientObjects[(object)AClientID]).AppDomainStatus = TAppDomainStatus.adsConnectingLoginOK;

                    // Retrieve Welcome message
                    try
                    {
                        if (UMaintenanceLogonMessage != null)
                        {
                            AWelcomeMessage = UMaintenanceLogonMessage.GetLogonMessage(AUserInfo, true);
                        }
                        else
                        {
                            AWelcomeMessage = "Welcome";
                        }
                    }
                    catch (Exception)
                    {
                        ((TRunningAppDomain)UClientObjects[(object)AClientID]).AppDomainStatus = TAppDomainStatus.adsStopped;
                        throw;
                    }

                    if (TLogging.DL >= 10)
                    {
                        TLogging.Log(
                            "Loaded Assemblies in AppDomain " + Thread.GetDomain().FriendlyName + " (before new AppDomain load):",
                            TLoggingType.ToConsole | TLoggingType.ToLogfile);

                        foreach (Assembly tmpAssembly in Thread.GetDomain().GetAssemblies())
                        {
                            TLogging.Log(tmpAssembly.FullName, TLoggingType.ToConsole | TLoggingType.ToLogfile);
                        }
                    }

                    #region Create new AppDomain for Client, load ClientDomain DLL into it, initialise AppDomain
                    try
                    {
                        try
                        {
                            // The following statement creates a new AppDomain for the connecting
                            // Client and remotes an instance of TRemoteLoader into it.
                            ClientDomainManager = UClientDomainManager.CreateAppDomain(AClientName);

                            if (TLogging.DL >= 10)
                            {
                                TLogging.Log(
                                    "Loaded Assemblies in AppDomain " + Thread.GetDomain().FriendlyName +
                                    ": (after TClientAppDomainConnection.Create)",
                                    TLoggingType.ToConsole | TLoggingType.ToLogfile);

                                foreach (Assembly tmpAssembly in Thread.GetDomain().GetAssemblies())
                                {
                                    TLogging.Log(tmpAssembly.FullName, TLoggingType.ToConsole | TLoggingType.ToLogfile);
                                }
                            }

                            // The following statement loads the ClientDomain DLL into the Client's
                            // AppDomain, instantiates the main Class and initialises the AppDomain
                            ClientDomainManager.LoadDomainManagerAssembly(AClientID,
                                AClientServerConnectionType,
                                FClientManagerCallForwarder,
                                USystemDefaultsCache,
                                UCacheableTablesManager,
                                AUserInfo,
                                out RemotingURL_PollClientTasks);
                            ARemotingURLs.Add(RemotingConstants.REMOTINGURL_IDENTIFIER_POLLCLIENTTASKS, RemotingURL_PollClientTasks);
                        }
                        catch (TargetInvocationException exp)
                        {
                            TLogging.Log(
                                "Error while creating new AppDomain for Client! Exception: " +
                                exp.ToString() +
                                "\r\n" + "InnerException: " + exp.InnerException.ToString());
                            throw exp.InnerException;
                        }
                        catch (Exception exp)
                        {
                            TLogging.Log(
                                "Error while creating new AppDomain for Client! Exception: " + exp.ToString());
                            throw;
                        }
                    }
                    catch (Exception)
                    {
                        // we should cleanly shut down the appdomain, to avoid exception:
                        // System.Net.Sockets.SocketException: Address already in use
                        AppDomainEntry = (TRunningAppDomain)UClientObjects[(object)AClientID];

                        if ((AppDomainEntry == null) || (ClientDomainManager == null))
                        {
                            // Application domain was not setup yet
                            AppDomainEntry.AppDomainStatus = TAppDomainStatus.adsStopped;
                        }
                        else
                        {
                            AppDomainEntry.PassInClientRemotingInfo(RemotingURL_RemotedObject, ClientDomainManager);
                            ServerDisconnectClient(AClientID, out CantDisconnectReason);
                        }

                        throw;
                    }
                    #endregion

                    if (TLogging.DL >= 10)
                    {
                        TLogging.Log(
                            "Loaded Assemblies in AppDomain " + Thread.GetDomain().FriendlyName + " (after new AppDomain load):",
                            TLoggingType.ToConsole |
                            TLoggingType.ToLogfile);

                        foreach (Assembly tmpAssembly in Thread.GetDomain().GetAssemblies())
                        {
                            TLogging.Log(tmpAssembly.FullName, TLoggingType.ToConsole | TLoggingType.ToLogfile);
                        }
                    }

                    ((TRunningAppDomain)UClientObjects[(object)AClientID]).PassInClientRemotingInfo(RemotingURL_RemotedObject,
                        ClientDomainManager);
                    ((TRunningAppDomain)UClientObjects[(object)AClientID]).AppDomainStatus = TAppDomainStatus.adsConnectingAppDomainSetupOK;

                    /*
                     * Uncomment the following statement to be able to better test how the
                     * Client reacts when it tries to connect and receives a
                     * ELoginFailedServerTooBusyException.
                     */

                    // Thread.Sleep(7000);

                    /*
                     * Notify all waiting Clients (that have not timed out yet) that they can
                     * now try to connect...
                     */
                    Monitor.PulseAll(UConnectClientMonitor);
                }
                else
                {
                    /*
                     * Throw Exception to tell any timed-out connecting Client that the Server
                     * is too busy to accept connect requests at the moment.
                     */
                    throw new ELoginFailedServerTooBusyException();
                }
            }
            finally
            {
                Monitor.Exit(UConnectClientMonitor);
            }

            ClientDomainManager.LoadAssemblies(AClientID.ToString(), AUserInfo, ref ARemotingURLs);

            ((TRunningAppDomain)UClientObjects[(object)AClientID]).AppDomainStatus = TAppDomainStatus.adsActive;
            ((TRunningAppDomain)UClientObjects[(object)AClientID]).FClientConnectionFinishedTime = DateTime.Now;


            #region Logging

            //
            // Assemblies successfully loaded into Client AppDomain
            //
            if (TLogging.DL >= 4)
            {
                TLogging.Log(
                    "Client '" + AUserName + "' successfully connected (took " +
                    ((TRunningAppDomain)UClientObjects[(object)AClientID]).FClientConnectionFinishedTime.Subtract(
                        ((TRunningAppDomain)UClientObjects[(object)AClientID]).FClientConnectionStartTime).
                    TotalSeconds.ToString() + " sec). ClientID: " + AClientID.ToString(),
                    TLoggingType.ToConsole | TLoggingType.ToLogfile);
            }
            else
            {
                TLogging.Log("Client '" + AUserName + "' successfully connected. ClientID: " + AClientID.ToString(), TLoggingType.ToLogfile);
            }

            #endregion
        }
Exemplo n.º 20
0
 /// <summary>
 /// Constructor that initialises the property values.
 ///
 /// @todo Change the class to retrieve the Server info on its own on
 ///
 /// </summary>
 /// <param name="ServerOS">Operating System of the PetraServer that the Client is
 /// connected to
 /// </param>
 /// <returns>void</returns>
 public TServerInfo(TExecutingOSEnum ServerOS)
 {
     // TODO ochristiank cServer_Info : Load Server info from Server.
     PServerOS = ServerOS;
 }
Exemplo n.º 21
0
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="AParseDate"></param>
        /// <param name="ADescription"></param>
        /// <param name="AParsedDate"></param>
        /// <param name="AShowVerificationError"></param>
        /// <param name="ATypeWhichCallsVerification"></param>
        /// <returns></returns>
        private static Boolean LongDateStringToDateTimeInternal(String AParseDate,
                                                                String ADescription,
                                                                out object AParsedDate,
                                                                Boolean AShowVerificationError,
                                                                System.Type ATypeWhichCallsVerification)
        {
            Boolean ReturnValue;
            Int32   DayOffset;
            String  TmpYear;
            String  TmpMonth;
            String  TmpDay;
            String  TmpMonthDayExchange = "";
            String  TmpShortDatePattern;
            Int16   YearStart = 0;
            Int16   RestStart = 0;

            // see StringHelper.DateToLocalizedString
            // Mono and .Net return different strings for month of March in german culture

            TExecutingOSEnum OSVersion = Utilities.DetermineExecutingOS();

            bool   IsPossiblyWin10 = ((OSVersion == TExecutingOSEnum.eosWin8Plus) || (OSVersion == TExecutingOSEnum.eosWin10));
            string CurrentCulture  = Thread.CurrentThread.CurrentCulture.ToString();

            List <string> CulturesToIgnore = new List <string>();

            CulturesToIgnore.Add("de-BE");
            CulturesToIgnore.Add("de-CH");
            CulturesToIgnore.Add("de-LI");
            CulturesToIgnore.Add("de-LU");

            if ((CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "de") &&
                !(CurrentCulture == "de-AT") &&
                !(IsPossiblyWin10 && CulturesToIgnore.Contains(CurrentCulture)))
            {
                AParseDate = AParseDate.Replace("MÄR", "MRZ");
            }

            AParsedDate = null;
            DateTimeFormatInfo CurrentDateTimeFormatInfo;

            ReturnValue = false;
            try
            {
                // TODO: implement parsing of localised short month names like 4GL does (according to user's default language setting), eg. accept 'M�R' instead of 'MAR' for March if the user's language setting is DE (German)
                // MessageBox.Show('AParseDate: ' + AParseDate);
                if (TDateChecks.IsValidDateTime(AParseDate, "") != null)
                {
                    // MessageBox.Show('No regular DateTime');
                    if ((AParseDate.StartsWith("-")) || ((AParseDate.StartsWith("+")) && (AParseDate.Length != 1)))
                    {
                        // MessageBox.Show('Calculating date from the amount that follows the + or  sign...');
                        // calculate date from the amount that follows the + or  sign
                        if (TNumericalChecks.IsValidInteger(AParseDate.Substring(1), "") == null)
                        {
                            DayOffset = System.Convert.ToInt32(AParseDate.Substring(1));

                            // MessageBox.Show('DayOffset: ' + DayOffset.ToString);
                            if (AParseDate.StartsWith("+"))
                            {
                                AParseDate = DateTime.Now.Date.AddDays(DayOffset).ToString("D");
                            }
                            else
                            {
                                AParseDate = DateTime.Now.Date.Subtract(new TimeSpan(DayOffset, 0, 0, 0)).ToString("D");
                            }
                        }
                        else
                        {
                            // characters following the + or  are not an Int32
                            if (AShowVerificationError)
                            {
                                TMessages.MsgGeneralError(TDateChecks.GetInvalidDateVerificationResult(ADescription), ATypeWhichCallsVerification);
                            }

                            return(ReturnValue);
                        }
                    }
                    else if ((AParseDate.Length <= 8) &&
                             (AParseDate.Length != 1) &&
                             (TNumericalChecks.IsValidInteger(AParseDate, "") == null))
                    {
//                        MessageBox.Show("Checking for dates entered like eg. 211105 or 21112005 ...");

                        /*
                         * Checking for dates entered like eg. 211105 or 21112005.
                         *
                         * Notes:
                         * Petra.NET accepts date entry dependent on current Culture
                         * (=settings are taken from Windows Control Panel -> Regional and
                         * Language Options).
                         * However, 4GL Petra parses dates according to the server-wide setting
                         * '-d'in startup.pf (Progress home directory). This should normally be
                         * the same than the Windows Control Panel setting on the user's
                         * machines, so there should be no deviation.
                         */
                        CurrentDateTimeFormatInfo = DateTimeFormatInfo.CurrentInfo;
                        TmpShortDatePattern       = CurrentDateTimeFormatInfo.ShortDatePattern.ToUpper();

                        if (TmpShortDatePattern.StartsWith("Y"))
                        {
                            YearStart = 0;

                            switch (AParseDate.Length)
                            {
                            case 8:
                                RestStart = 4;
                                break;

                            case 6:
                                RestStart = 2;
                                break;

                            case 4:
                                RestStart = 0;
                                YearStart = -1;
                                break;
                            }
                        }
                        else
                        {
                            RestStart = 0;

                            switch (AParseDate.Length)
                            {
                            case 6:
                            case 8:
                                YearStart = 4;
                                break;

                            case 4:
                                YearStart = -1;
                                break;
                            }
                        }

//MessageBox.Show("TmpShortDatePattern: " + TmpShortDatePattern + "; TmpDateSeparator: " + TmpDateSeparator +
//    "\r\nYearStart: " + YearStart.ToString() + "; RestStart: " + RestStart.ToString());
                        if (AParseDate.Length <= 6)
                        {
                            if (YearStart != -1)
                            {
                                TmpYear = AParseDate.Substring(YearStart, 2);

                                // Determine the correct century for twodigit years.
                                // For compatibility reasons: This is the way how it's done in 4GL,
                                // in sp_date.p/ConvertStringToDate
                                if (Convert.ToInt32(TmpYear) < 80)
                                {
                                    TmpYear = "20" + TmpYear;
                                }
                                else if (Convert.ToInt32(TmpYear) < 100)
                                {
                                    TmpYear = "19" + TmpYear;
                                }

                                //
                                // This would be the Windows way of doing it...
                                // I (ChristianK) found no way to retrieve the correct century from
                                // .NET, so it's hardcoded here, taking the default values of Windows
                                // XP :(
                                //
                                // if Convert.ToInt32(TmpYear) <= 29 then
                                // begin
                                // TmpYear := '20' + TmpYear;
                                // end
                                // else
                                // begin
                                // TmpYear := '19' + TmpYear;
                                // end;
                            }
                            else
                            {
                                TmpYear = DateTime.Now.Year.ToString();
                            }
                        }
                        else
                        {
                            TmpYear = AParseDate.Substring(YearStart, 4);
                        }

                        if ((AParseDate.Length == 4) || (AParseDate.Length == 6) || (AParseDate.Length == 8))
                        {
                            if (TmpShortDatePattern.IndexOf('M') < TmpShortDatePattern.IndexOf('D'))
                            {
                                TmpMonth = AParseDate.Substring(RestStart, 2);
                                TmpDay   = AParseDate.Substring(RestStart + 2, 2);
                            }
                            else
                            {
                                TmpDay   = AParseDate.Substring(RestStart, 2);
                                TmpMonth = AParseDate.Substring(RestStart + 2, 2);
                            }
                        }
                        else
                        {
                            // format with other number of digits not supported
                            if (AShowVerificationError)
                            {
                                TMessages.MsgGeneralError(TDateChecks.GetInvalidDateVerificationResult(ADescription), ATypeWhichCallsVerification);
                            }

                            return(ReturnValue);
                        }

                        if (Convert.ToInt16(TmpMonth) > 12)
                        {
                            TmpMonthDayExchange = TmpMonth;
                            TmpMonth            = TmpDay;
                            TmpDay = TmpMonthDayExchange;
                        }

                        // AParseDate := TmpYear + TmpDateSeparator + TmpMonth + TmpDateSeparator + TmpDay;    For testing purposes
                        // MessageBox.Show('AParseDate (1): ' + AParseDate);    For testing purposes
                        try
                        {
                            // TmpMonth + '/' + TmpDay + '/' + TmpYear;
                            AParseDate = new DateTime(Convert.ToInt32(TmpYear), Convert.ToInt32(TmpMonth), Convert.ToInt32(TmpDay)).ToString("D");

                            if (TmpMonthDayExchange != "")
                            {
                                MessageBox.Show(StrMonthDayExchangedInfo, StrMonthDayExchangedInfoTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                        catch (Exception)
                        {
                            if (AShowVerificationError)
                            {
                                TMessages.MsgGeneralError(TDateChecks.GetInvalidDateVerificationResult(ADescription), ATypeWhichCallsVerification);
                            }

                            return(ReturnValue);
                        }

//MessageBox.Show("TmpShortDatePattern: " + TmpShortDatePattern + "; TmpDateSeparator: " + TmpDateSeparator +
//                                        "\r\nYearStart: " + YearStart.ToString() + "; RestStart: " + RestStart.ToString() +
//"; TmpDay: " + TmpDay + "; TmpMonth: " + TmpMonth + "; TmpYear: " + TmpYear + "\r\nAParseDate: " + AParseDate);
                        AParsedDate = AParseDate;
                        ReturnValue = true;
                        return(ReturnValue);
                    }
                    else if (AParseDate == string.Empty)
                    {
                        AParsedDate = DBNull.Value;
                        ReturnValue = true;
                        return(ReturnValue);
                    }
                    else if ((AParseDate == "=") || (AParseDate == "+") || (AParseDate.ToLower() == Catalog.GetString("today").ToLower()))
                    {
                        AParsedDate = DateTime.Now.ToString("D");
                        ReturnValue = true;
                        return(ReturnValue);
                    }
                    else
                    {
                        if (AShowVerificationError)
                        {
                            // not an accepted date parse string
                            TMessages.MsgGeneralError(TDateChecks.GetInvalidDateVerificationResult(ADescription), ATypeWhichCallsVerification);
                        }

                        return(ReturnValue);
                    }
                }

                // AParseDate ready to be parsed
                AParsedDate = DateTime.Parse(AParseDate).ToString("D");
                ReturnValue = true;
            }
            catch (Exception /* Exp */)
            {
                if (AShowVerificationError)
                {
                    TMessages.MsgGeneralError(TDateChecks.GetInvalidDateVerificationResult(ADescription), ATypeWhichCallsVerification);
                }
            }

            return(ReturnValue);
        }