Exemplo n.º 1
0
        public static System.Boolean GetDBVersion(out System.String APetraDBVersion)
        {
            TDBTransaction ReadTransaction = null;

            APetraDBVersion = "Cannot retrieve DB version";
            TLogging.LogAtLevel(9, "TSysManServerLookups.GetDatabaseVersion called!");

            SSystemDefaultsTable SystemDefaultsDT = new SSystemDefaultsTable();

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(
                IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref ReadTransaction,
                delegate
                {
                    // Load data
                    SystemDefaultsDT = SSystemDefaultsAccess.LoadByPrimaryKey("CurrentDatabaseVersion", ReadTransaction);
                });

            if (SystemDefaultsDT.Rows.Count < 1)
            {
                throw new EOPAppException(
                    "TSysManServerLookups.GetDBVersion: s_system_defaults DB Table is empty; this is unexpected and can lead to sever malfunction of OpenPetra. Contact your Support Team.");
            }

            SSystemDefaultsRow sysrow = SystemDefaultsDT.Rows[0] as SSystemDefaultsRow;

            if (sysrow == null)
            {
                throw new EOPAppException(
                    "TSysManServerLookups.GetDBVersion: s_system_defaults DB Table is empty; this is unexpected and can lead to sever malfunction of OpenPetra. Contact your Support Team.");
            }

            APetraDBVersion = sysrow.DefaultValue;

            return true;
        }
Exemplo n.º 2
0
        private void RunOnceOnActivationManual()
        {
            // Start by dealing with the settings classes that will be displayed in the combo box filter
            DataTable settingsClassDT = FMainDS.SSystemDefaults.DefaultView.ToTable("SettingsClass", true, SSystemDefaultsTable.GetCategoryDBName());

            if (Form.ModifierKeys == (Keys.Alt | Keys.Shift))
            {
                // This is the back-door to showing all the system defaults
                FLaunchedInSysAdminMode = true;

                DataRow dr = settingsClassDT.NewRow();
                dr[0] = "!SysAdmin!";
                settingsClassDT.Rows.Add(dr);
            }

            cmbClass.DisplayMember = SSystemDefaultsTable.GetCategoryDBName();
            cmbClass.ValueMember   = SSystemDefaultsTable.GetCategoryDBName();
            settingsClassDT.DefaultView.RowFilter = string.Format("{0} IS NOT NULL", SSystemDefaultsTable.GetCategoryDBName());
            settingsClassDT.DefaultView.Sort      = string.Format("{0}", cmbClass.DisplayMember);
            cmbClass.DataSource = settingsClassDT.DefaultView;

            // Select the first item in the class filter
            if (settingsClassDT.DefaultView.Count > 0)
            {
                cmbClass.SelectedIndex = 0;
                FActiveClass           = cmbClass.GetSelectedString();
            }

            // This will select the first row in the grid now that everything has been activated
            FSuppressClassChange = false;
            OnSettingsClassChange(null, null);
        }
Exemplo n.º 3
0
        public static SSystemDefaultsTable GetSystemDefaults()
        {
            SSystemDefaultsTable ReturnValue     = null;
            TDBTransaction       ReadTransaction = null;
            bool DBAccessCallSuccessful          = false;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(
                IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref ReadTransaction,
                delegate
            {
                TServerBusyHelper.CoordinatedAutoRetryCall("Loading all SystemDefaults", ref DBAccessCallSuccessful,
                                                           delegate
                {
                    ReturnValue = SSystemDefaultsAccess.LoadAll(ReadTransaction);

                    DBAccessCallSuccessful = true;
                });
            });

            if (!DBAccessCallSuccessful)
            {
                throw new EDBAccessLackingCoordinationException("Loading of System Default failed: server was too busy!");
            }

            return(ReturnValue);
        }
Exemplo n.º 4
0
        public static TSubmitChangesResult SaveData(string ATablename,
                                                    ref TTypedDataTable ASubmitTable, out TVerificationResultCollection AVerificationResult)
        {
            TSubmitChangesResult          ReturnValue        = TSubmitChangesResult.scrError;
            TDBTransaction                WriteTransaction   = null;
            TTypedDataTable               SubmitTable        = null;
            TVerificationResultCollection VerificationResult = null;

            SubmitTable = ASubmitTable;

            // Automatic handling of a DB Transaction - and also the automatic establishment and closing of a DB
            // Connection where a DB Transaction can be exectued (only if that should be needed).
            DBAccess.SimpleAutoTransactionWrapper("TCommonDataReader.SaveData", out WriteTransaction,
                                                  ref ReturnValue,
                                                  delegate
            {
                ReturnValue = SaveData(ATablename, ref SubmitTable, out VerificationResult, WriteTransaction);
            });

            if ((ATablename == SSystemDefaultsTable.GetTableDBName()) && (ReturnValue == TSubmitChangesResult.scrOK))
            {
                // Refresh the cache immediately so clients will get the changes
                TSystemDefaultsCache.GSystemDefaultsCache.ReloadSystemDefaultsTable();
            }

            AVerificationResult = VerificationResult;

            return(ReturnValue);
        }
        public static TSubmitChangesResult SaveData(string ATablename,
                                                    ref TTypedDataTable ASubmitTable, out TVerificationResultCollection AVerificationResult)
        {
            // check access permissions for the current user
            TModuleAccessManager.CheckUserPermissionsForTable(ATablename, TTablePermissionEnum.eCanModify | TTablePermissionEnum.eCanModify | TTablePermissionEnum.eCanDelete);

            TSubmitChangesResult          ReturnValue        = TSubmitChangesResult.scrError;
            TTypedDataTable               SubmitTable        = null;
            TVerificationResultCollection VerificationResult = null;
            TDBTransaction WriteTransaction = new TDBTransaction();
            TDataBase      db = DBAccess.Connect("SaveData");

            SubmitTable = ASubmitTable;
            bool submitOK = true;

            // Automatic handling of a DB Transaction - and also the automatic establishment and closing of a DB
            // Connection where a DB Transaction can be exectued (only if that should be needed).
            db.WriteTransaction(
                ref WriteTransaction,
                ref submitOK,
                delegate
            {
                ReturnValue = SaveData(ATablename, ref SubmitTable, out VerificationResult, WriteTransaction);
                submitOK    = ReturnValue == TSubmitChangesResult.scrOK;
            });

            AVerificationResult = VerificationResult;

            if ((ATablename == SSystemDefaultsTable.GetTableDBName()) && (ReturnValue == TSubmitChangesResult.scrOK))
            {
                // TODO Reload the site key into the session, in case that was changed
            }

            return(ReturnValue);
        }
Exemplo n.º 6
0
        public static System.Boolean GetDBVersion(out System.String APetraDBVersion)
        {
            TDBTransaction ReadTransaction = null;

            APetraDBVersion = "Cannot retrieve DB version";
            TLogging.LogAtLevel(9, "TSysManServerLookups.GetDatabaseVersion called!");

            SSystemDefaultsTable SystemDefaultsDT = new SSystemDefaultsTable();

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(
                IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref ReadTransaction,
                delegate
            {
                // Load data
                SystemDefaultsDT = SSystemDefaultsAccess.LoadByPrimaryKey("CurrentDatabaseVersion", ReadTransaction);
            });

            if (SystemDefaultsDT.Rows.Count < 1)
            {
                throw new EOPAppException(
                          "TSysManServerLookups.GetDBVersion: s_system_defaults DB Table is empty; this is unexpected and can lead to sever malfunction of OpenPetra. Contact your Support Team.");
            }

            SSystemDefaultsRow sysrow = SystemDefaultsDT.Rows[0] as SSystemDefaultsRow;

            if (sysrow == null)
            {
                throw new EOPAppException(
                          "TSysManServerLookups.GetDBVersion: s_system_defaults DB Table is empty; this is unexpected and can lead to sever malfunction of OpenPetra. Contact your Support Team.");
            }

            APetraDBVersion = sysrow.DefaultValue;

            return(true);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Returns the value of the specified System Default.
        /// For that, the whole System Defaults DB table is read from the server - that's not a problem so long as there's not
        /// thousands of system defaults, and this method isn't called too often!
        /// </summary>
        /// <param name="ASystemDefaultName">The System Default for which the value should be returned.</param>
        /// <returns>The value of the System Default, or SYSDEFAULT_NOT_FOUND if the
        /// specified System Default was not found.</returns>
        public static String GetSystemDefault(String ASystemDefaultName)
        {
            SSystemDefaultsTable SystemDefaultsDT = null;
            SSystemDefaultsRow   FoundSystemDefaultsRow;
            bool ServerCallSuccessful = false;

            TServerBusyHelper.CoordinatedAutoRetryCall("System Defaults", ref ServerCallSuccessful,
                                                       delegate
            {
                SystemDefaultsDT = TRemote.MSysMan.Maintenance.SystemDefaults.WebConnectors.GetSystemDefaults();

                ServerCallSuccessful = true;
            });

            if (!ServerCallSuccessful)
            {
                TServerBusyHelperGui.ShowLoadingOfDataGotCancelledDialog();

                return(SharedConstants.SYSDEFAULT_NOT_FOUND);
            }

            if (SystemDefaultsDT != null)
            {
                // Look up the System Default
                FoundSystemDefaultsRow = (SSystemDefaultsRow)SystemDefaultsDT.Rows.Find(ASystemDefaultName);

                return(FoundSystemDefaultsRow != null ? FoundSystemDefaultsRow.DefaultValue : SharedConstants.SYSDEFAULT_NOT_FOUND);
            }
            else
            {
                // 'Back-stop' - should never get here
                return(SharedConstants.SYSDEFAULT_NOT_FOUND);
            }
        }
Exemplo n.º 8
0
        private void FPetraUtilsObject_DataSavingValidated(object Sender, System.ComponentModel.CancelEventArgs e)
        {
            // Capture any rows that are going to be saved that we are interested in
            SSystemDefaultsTable submitDT = FMainDS.SSystemDefaults.GetChangesTyped();

            FIncludesLocalisedCountyLabel = (SSystemDefaultsRow)submitDT.Rows.Find(SharedConstants.SYSDEFAULT_LOCALISEDCOUNTYLABEL);
            FIncludesDonorZero            = (SSystemDefaultsRow)submitDT.Rows.Find(SharedConstants.SYSDEFAULT_DONORZEROISVALID);
            FIncludesRecipientZero        = (SSystemDefaultsRow)submitDT.Rows.Find(SharedConstants.SYSDEFAULT_RECIPIENTZEROISVALID);
        }
Exemplo n.º 9
0
        private void OnSettingsClassChange(object sender, EventArgs e)
        {
            // We get called here when the settings class combo has changed
            if ((FFilterAndFindObject == null) || (FSuppressClassChange == true))
            {
                return;
            }

            if (sender != null)
            {
                // We don't do this at startup, but after that we need to set the class back to what it was before if validation fails
                if (!ValidateAllData(false, TErrorProcessingMode.Epm_All))
                {
                    FSuppressClassChange = true;
                    ((TCmbAutoComplete)sender).SetSelectedString(FActiveClass);
                    FSuppressClassChange = false;
                    return;
                }

                FActiveClass = ((TCmbAutoComplete)sender).GetSelectedString();
            }

            // We need to know if we are displaying a sysAdmin row or not
            string sysAdminRowFilter = "12345";
            string rowFilter         = string.Format("{0}>0 AND ", FControlsCountName);

            if (cmbClass.SelectedValue == null)
            {
                rowFilter += "1=0";
            }
            else if (FLaunchedInSysAdminMode && (cmbClass.SelectedIndex == 0))
            {
                sysAdminRowFilter = string.Format("{0}=0 OR {1} IS NULL", FControlsCountName, SSystemDefaultsTable.GetCategoryDBName());
                rowFilter         = sysAdminRowFilter;
            }
            else
            {
                rowFilter += string.Format("{0}='{1}'", SSystemDefaultsTable.GetCategoryDBName(), cmbClass.SelectedValue.ToString());
            }

            FFilterAndFindObject.FilterPanelControls.SetBaseFilter(rowFilter, true);

            // Both these will cause validation to run, but it should be ok because we checked it above
            FFilterAndFindObject.ApplyFilter();
            SelectRowInGrid(1);

            // Depending on how validation worked out we now know whether we are displaying the sysAdmin codes or not
            FShowingSysAdminCodes = FMainDS.SSystemDefaults.DefaultView.RowFilter.StartsWith(sysAdminRowFilter);

            // Now we can show/hide columns 0 and 1
            grdDetails.Columns[0].Visible = FShowingSysAdminCodes;
            grdDetails.Columns[1].Visible = !FShowingSysAdminCodes;
            grdDetails.AutoResizeGrid();
        }
Exemplo n.º 10
0
        public static void SetSystemDefault(String AKey, String AValue)
        {
            Boolean NewTransaction = false;
            Boolean ShouldCommit   = false;

            try
            {
                TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                                                               TEnforceIsolationLevel.eilMinimum,
                                                                                               out NewTransaction);
                SSystemDefaultsTable tbl = SSystemDefaultsAccess.LoadByPrimaryKey(AKey, Transaction);

                if (tbl.Rows.Count > 0) // I already have this. (I expect this is the case usually!)
                {
                    DataRow Row = tbl[0];
                    ((SSystemDefaultsRow)Row).DefaultValue = AValue;
                }
                else
                {
                    DataRow Row = tbl.NewRowTyped(true);
                    ((SSystemDefaultsRow)Row).DefaultCode        = AKey;
                    ((SSystemDefaultsRow)Row).DefaultDescription = "Created in OpenPetra";
                    ((SSystemDefaultsRow)Row).DefaultValue       = AValue;
                    tbl.Rows.Add(Row);
                }

                SSystemDefaultsAccess.SubmitChanges(tbl, Transaction);
                ShouldCommit = true;
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the saving of a single System Default:" + Environment.NewLine + Exc.ToString());
                ShouldCommit = false;
                throw;
            }
            finally
            {
                if (NewTransaction)
                {
                    if (ShouldCommit)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                    }
                    else
                    {
                        DBAccess.GDBAccessObj.RollbackTransaction();
                    }
                }
            }
        }
Exemplo n.º 11
0
        public static String GetSystemDefault(String ASystemDefaultName)
        {
            String ReturnValue = SharedConstants.SYSDEFAULT_NOT_FOUND;
            SSystemDefaultsTable SystemDefaultsTable = GetSystemDefaults();

            // Look up the System Default
            SSystemDefaultsRow FoundSystemDefaultsRow = (SSystemDefaultsRow)SystemDefaultsTable.Rows.Find(ASystemDefaultName);

            if (FoundSystemDefaultsRow != null)
            {
                ReturnValue = FoundSystemDefaultsRow.DefaultValue;
            }

            return(ReturnValue);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Loads the System Defaults into the cached Typed DataTable.
        ///
        /// The System Defaults are retrieved from the s_system_defaults table and are
        /// put into a Typed DataTable that has the structure of this table.
        ///
        /// </summary>
        /// <returns>void</returns>
        private void LoadSystemDefaultsTable()
        {
            TDataBase      DBAccessObj     = new Ict.Common.DB.TDataBase();
            TDBTransaction ReadTransaction = null;

            // Prevent other threads from obtaining a read lock on the cache table while we are (re)loading the cache table!
            FReadWriteLock.AcquireWriterLock(SharedConstants.THREADING_WAIT_INFINITE);

            try
            {
                if (FSystemDefaultsDT != null)
                {
                    FSystemDefaultsDT.Clear();
                }

                try
                {
                    DBAccessObj.EstablishDBConnection(TSrvSetting.RDMBSType,
                                                      TSrvSetting.PostgreSQLServer,
                                                      TSrvSetting.PostgreSQLServerPort,
                                                      TSrvSetting.PostgreSQLDatabaseName,
                                                      TSrvSetting.DBUsername,
                                                      TSrvSetting.DBPassword,
                                                      "",
                                                      "SystemDefaultsCache DB Connection");

                    DBAccessObj.BeginAutoReadTransaction(IsolationLevel.RepeatableRead, ref ReadTransaction,
                                                         delegate
                    {
                        FSystemDefaultsDT = SSystemDefaultsAccess.LoadAll(ReadTransaction);
                    });
                }
                finally
                {
                    DBAccessObj.CloseDBConnection();
                }

                // Thread.Sleep(5000);     uncomment this for debugging. This allows checking whether read access to FSystemDefaultsDT actually waits until we release the WriterLock in the finally block.
            }
            finally
            {
                // Other threads are now free to obtain a read lock on the cache table.
                FReadWriteLock.ReleaseWriterLock();
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Loads the System Defaults into the cached Typed DataTable.
        ///
        /// The System Defaults are retrieved from the s_system_defaults table and are
        /// put into a Typed DataTable that has the structure of this table.
        ///
        /// </summary>
        /// <returns>void</returns>
        private void LoadSystemDefaultsTable()
        {
            TDataBase      DBAccessObj     = DBAccess.Connect("LoadSystemDefaultsTable", FDataBase);
            TDBTransaction ReadTransaction = new TDBTransaction();

            if (FSystemDefaultsDT != null)
            {
                FSystemDefaultsDT.Clear();
            }

            DBAccessObj.ReadTransaction(ref ReadTransaction,
                                        delegate
            {
                FSystemDefaultsDT = SSystemDefaultsAccess.LoadAll(ReadTransaction);
            });

            if (FDataBase == null)
            {
                DBAccessObj.CloseDBConnection();
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Returns the value of the specified System Default.
        ///
        /// The whole table is read from the server - it's not a problem so long as there's not
        /// thousands of system defaults, and this method isn't called too often!
        ///
        /// </summary>
        /// <param name="ASystemDefaultName">The System Default for which the value should be returned</param>
        /// <returns>The value of the System Default, or SYSDEFAULT_NOT_FOUND if the
        /// specified System Default was not found
        /// </returns>
        public static String GetSystemDefault(String ASystemDefaultName)
        {
            String             ReturnValue;
            SSystemDefaultsRow FoundSystemDefaultsRow;

            SSystemDefaultsTable SystemDefaultsDT = TRemote.MSysMan.Maintenance.SystemDefaults.WebConnectors.GetSystemDefaults();

            // Look up the System Default
            FoundSystemDefaultsRow = (SSystemDefaultsRow)SystemDefaultsDT.Rows.Find(ASystemDefaultName);

            if (FoundSystemDefaultsRow != null)
            {
                ReturnValue = FoundSystemDefaultsRow.DefaultValue;
            }
            else
            {
                ReturnValue = SharedConstants.SYSDEFAULT_NOT_FOUND;
            }

            return(ReturnValue);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Loads the System Defaults into the cached Typed DataTable.
        ///
        /// The System Defaults are retrieved from the s_system_defaults table and are
        /// put into a Typed DataTable that has the structure of this table.
        ///
        /// </summary>
        /// <returns>void</returns>
        private void LoadSystemDefaultsTable()
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            // Prevent other threads from obtaining a read lock on the cache table while we are (re)loading the cache table!
            FReadWriteLock.AcquireWriterLock(SharedConstants.THREADING_WAIT_INFINITE);

            try
            {
                if (FSystemDefaultsDT != null)
                {
                    FSystemDefaultsDT.Clear();
                }

                try
                {
                    ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                                                        TEnforceIsolationLevel.eilMinimum,
                                                                                        out NewTransaction);
                    FSystemDefaultsDT = SSystemDefaultsAccess.LoadAll(ReadTransaction);
                }
                finally
                {
                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                        TLogging.LogAtLevel(7, "TSystemDefaultsCache.LoadSystemDefaultsTable: commited own transaction.");
                    }
                }

                // Thread.Sleep(5000);     uncomment this for debugging. This allows checking whether read access to FSystemDefaultsDT actually waits until we release the WriterLock in the finally block.
            }
            finally
            {
                // Other threads are now free to obtain a read lock on the cache table.
                FReadWriteLock.ReleaseWriterLock();
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Saves changes to the submitted Typed SystemDefaults DataTable to the DB.
        ///
        /// @comment Currently always returns false because the function needs to be
        /// rewritten!
        ///
        /// @todo Rewrite this function so that it saves entries that originally came
        /// from the s_system_parameter table in the DB to this table instead of
        /// writing them to the s_system_defaults table! Also use the DataStore to
        /// save the data instead of using SQL queries!!!
        ///
        /// </summary>
        /// <param name="ASystemDefaultsDataTable">Typed SystemDefaults DataTable</param>
        /// <returns>true if the System Defaults could be saved successfully
        /// </returns>
        public Boolean SaveSystemDefaults(SSystemDefaultsTable ASystemDefaultsDataTable)
        {
            // var
            // Transaction: OdbcTransaction;
            // ParametersArray: array of OdbcParameter;
            // Counter,
            // DefaultInDataBaseCount: Int16;
            // AllSubmissionsOK: Boolean;

            /* TODO 2 oChristanK cDB : Rewrite this function so that it saves entries that originally came from the s_system_parameter table
             * in the DB to this table instead of writing them to the s_system_defaults table! Also use the DataStore to
             * save the data instead of using SQL queries!!!
             */

            // Currently always returns false because the function needs to be rewritten!
            return false;

            // AllSubmissionsOK := false;
            // DefaultInDataBaseCount := 0;
            //
            // if (ASystemDefaultsDataTable <> nil) and (ASystemDefaultsDataTable.Rows.Count > 0) then
            // begin
            // $IFDEF DEBUGMODE if TLogging.DL >= 8 then Console.WriteLine('Saving ' + (ASystemDefaultsDataTable.Rows.Count).ToString + ' System Defaults...'); $ENDIF
            //
            // Transaction := DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            //
            // Loop over all changed/added System Defaults
            // for Counter := 0 to ASystemDefaultsDataTable.Rows.Count  1 do
            // begin
            // Look whether the System Default already exists in the DB
            // SetLength(ParametersArray, 1);
            // ParametersArray[0] := new OdbcParameter('', OdbcType.VarChar, 32);
            // ParametersArray[0].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'].ToString;
            //
            // try
            // DefaultInDataBaseCount := Convert.ToInt16( DBAccess.GDBAccessObj.ExecuteScalar(
            // 'SELECT COUNT) ' +
            // 'FROM PUB_s_system_defaults ' +
            // 'WHERE s_default_code_c = ?', Transaction, false, ParametersArray) );
            // except
            // on exp: Exception do
            // begin
            // Result := false;
            // $IFDEF DEBUGMODE if TLogging.DL >= 9 then Console.WriteLine(this.GetType.FullName + '.SaveSystemDefaults: Error running count query!!! ' +
            // 'Possible cause: ' + exp.ToString); $ENDIF
            // Exit;
            // end;
            // end;
            //
            // if DefaultInDataBaseCount = 0 then
            // begin
            // System Default doesn't exist yet > create it

            /* $IFDEF DEBUGMODE if TLogging.DL >= 8 then Console.WriteLine('Inserting SystemDefault ' + ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'].ToString + '; Value: ' +
             *ASystemDefaultsDataTable.Rows[Counter].Item['s_default_value_c'].ToString);$ENDIF */

            // SetLength(ParametersArray, 3);
            // ParametersArray[0] := new OdbcParameter('', OdbcType.VarChar, 32);
            // ParametersArray[0].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'].ToString;
            // ParametersArray[0] := new OdbcParameter('', OdbcType.VarChar, 48);
            // ParametersArray[0].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_description_c'].ToString;
            // ParametersArray[2] := new OdbcParameter('', OdbcType.VarChar, 96);
            // ParametersArray[2].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_value_c'].ToString;
            //
            // try
            // DBAccess.GDBAccessObj.ExecuteNonQuery(
            // 'INSERT INTO PUB_s_system_defaults ' +
            // '(s_default_code_c, s_default_description_c, s_default_value_c) ' +
            // 'VALUES (?, ?, ?)', Transaction, false, ParametersArray);
            // except
            // on exp: Exception do
            // begin
            // Result := false;
            // $IFDEF DEBUGMODE if TLogging.DL >= 9 then Console.WriteLine(this.GetType.FullName + '.SaveSystemDefaults: Error running insert query!!! ' +
            // 'Possible cause: ' + exp.ToString); $ENDIF
            // Exit;
            // end;
            // end;
            // end
            // else
            // begin
            // System Default exists > update it

            /* $IFDEF DEBUGMODE if TLogging.DL >= 8 then Console.WriteLine('Updating SystemDefault ' + ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'].ToString + '; Value: ' +
             *ASystemDefaultsDataTable.Rows[Counter].Item['s_default_value_c'].ToString);$ENDIF */

            // SetLength(ParametersArray, 3);
            // ParametersArray[0] := new OdbcParameter('', OdbcType.VarChar, 48);
            // ParametersArray[0].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_description_c'];
            // ParametersArray[1] := new OdbcParameter('', OdbcType.VarChar, 96);
            // ParametersArray[1].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_value_c'];
            // ParametersArray[2] := new OdbcParameter('', OdbcType.VarChar, 32);
            // ParametersArray[2].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'];
            //
            // try
            // DBAccess.GDBAccessObj.ExecuteNonQuery(
            // 'UPDATE PUB_s_system_defaults ' +
            // 'SET s_default_description_c = ?, s_default_value_c = ? ' +
            // 'WHERE s_default_code_c = ?', Transaction, false, ParametersArray);
            // except
            // on exp: Exception do
            // begin
            // Result := false;
            // $IFDEF DEBUGMODE if TLogging.DL >= 9 then Console.WriteLine(this.GetType.FullName + '.SaveSystemDefaults: Error runing insert query!!! ' +
            // 'Possible cause: ' + exp.ToString); $ENDIF
            // Exit;
            // end;
            // end;
            // end;
            // end;
            //
            // DBAccess.GDBAccessObj.CommitTransaction;
            // Result := AllSubmissionsOK;
            // end
            // else
            // begin
            // nothing to save!
            // Result := false;
            // end;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Loads the System Defaults into the cached Typed DataTable.
        ///
        /// The System Defaults are retrieved from the s_system_defaults table and are
        /// put into a Typed DataTable that has the structure of this table.
        ///
        /// </summary>
        /// <returns>void</returns>
        private void LoadSystemDefaultsTable()
        {
            TDBTransaction ReadTransaction;
            Boolean NewTransaction = false;

            // Prevent other threads from obtaining a read lock on the cache table while we are (re)loading the cache table!
            FReadWriteLock.AcquireWriterLock(SharedConstants.THREADING_WAIT_INFINITE);

            try
            {
                if (FSystemDefaultsDT != null)
                {
                    FSystemDefaultsDT.Clear();
                }

                try
                {
                    ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                        TEnforceIsolationLevel.eilMinimum,
                        out NewTransaction);
                    FSystemDefaultsDT = SSystemDefaultsAccess.LoadAll(ReadTransaction);
                }
                finally
                {
                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                        TLogging.LogAtLevel(7, "TSystemDefaultsCache.LoadSystemDefaultsTable: commited own transaction.");
                    }
                }

                // Thread.Sleep(5000);     uncomment this for debugging. This allows checking whether read access to FSystemDefaultsDT actually waits until we release the WriterLock in the finally block.
            }
            finally
            {
                // Other threads are now free to obtain a read lock on the cache table.
                FReadWriteLock.ReleaseWriterLock();
            }
        }
        public static void GetData(string ATablename, TSearchCriteria[] ASearchCriteria, out TTypedDataTable AResultTable,
                                   TDBTransaction AReadTransaction)
        {
            AResultTable = null;
            string context = string.Format("GetData {0}", SharedConstants.MODULE_ACCESS_MANAGER);

            // check access permissions for the current user
            TModuleAccessManager.CheckUserPermissionsForTable(ATablename, TTablePermissionEnum.eCanRead);

            // TODO: auto generate
            if (ATablename == AApSupplierTable.GetTableDBName())
            {
                AResultTable = AApSupplierAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == AApDocumentTable.GetTableDBName())
            {
                AResultTable = AApDocumentAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == ATransactionTypeTable.GetTableDBName())
            {
                AResultTable = ATransactionTypeAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == ACurrencyTable.GetTableDBName())
            {
                AResultTable = ACurrencyAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == ADailyExchangeRateTable.GetTableDBName())
            {
                AResultTable = ADailyExchangeRateAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == ACorporateExchangeRateTable.GetTableDBName())
            {
                AResultTable = ACorporateExchangeRateAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == ACurrencyLanguageTable.GetTableDBName())
            {
                AResultTable = ACurrencyLanguageAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == AFeesPayableTable.GetTableDBName())
            {
                AResultTable = AFeesPayableAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == AFeesReceivableTable.GetTableDBName())
            {
                AResultTable = AFeesReceivableAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == AAnalysisTypeTable.GetTableDBName())
            {
                AResultTable = AAnalysisTypeAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == AGiftBatchTable.GetTableDBName())
            {
                AResultTable = AGiftBatchAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == AJournalTable.GetTableDBName())
            {
                AResultTable = AJournalAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == ALedgerTable.GetTableDBName())
            {
                AResultTable = ALedgerAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == MExtractMasterTable.GetTableDBName())
            {
                if (ASearchCriteria == null)
                {
                    AResultTable = MExtractMasterAccess.LoadAll(AReadTransaction);
                }
                else
                {
                    AResultTable = MExtractMasterAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
                }
            }
            else if (ATablename == MExtractTable.GetTableDBName())
            {
                // it does not make sense to load ALL extract rows for all extract masters so search criteria needs to be set
                if (ASearchCriteria != null)
                {
                    AResultTable = MExtractAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
                }
            }
            else if (ATablename == PcAttendeeTable.GetTableDBName())
            {
                AResultTable = PcAttendeeAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == PcConferenceCostTable.GetTableDBName())
            {
                AResultTable = PcConferenceCostAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == PcEarlyLateTable.GetTableDBName())
            {
                AResultTable = PcEarlyLateAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == PcSupplementTable.GetTableDBName())
            {
                AResultTable = PcSupplementAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == PcDiscountTable.GetTableDBName())
            {
                AResultTable = PcDiscountAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == PCountryTable.GetTableDBName())
            {
                AResultTable = PCountryAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == PFormTable.GetTableDBName())
            {
                string[]         columns   = TTypedDataTable.GetColumnStringList(PFormTable.TableId);
                StringCollection fieldList = new StringCollection();

                for (int i = 0; i < columns.Length; i++)
                {
                    // Do not load the template document - we don't display it and it is big!
                    if (columns[i] != PFormTable.GetTemplateDocumentDBName())
                    {
                        fieldList.Add(columns[i]);
                    }
                }

                AResultTable = PFormAccess.LoadAll(fieldList, AReadTransaction);
            }
            else if (ATablename == PInternationalPostalTypeTable.GetTableDBName())
            {
                AResultTable = PInternationalPostalTypeAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == PtApplicationTypeTable.GetTableDBName())
            {
                AResultTable = PtApplicationTypeAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == PFormalityTable.GetTableDBName())
            {
                AResultTable = PFormalityAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == PMailingTable.GetTableDBName())
            {
                AResultTable = PMailingAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName())
            {
                AResultTable = PPartnerGiftDestinationAccess.LoadUsingTemplate(ASearchCriteria, AReadTransaction);
            }
            else if (ATablename == PmDocumentTypeTable.GetTableDBName())
            {
                AResultTable = PmDocumentTypeAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == SGroupTable.GetTableDBName())
            {
                TSecurityChecks.CheckUserModulePermissions(SharedConstants.PETRAMODULE_SYSADMIN, context);
                AResultTable = SGroupAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == SSystemDefaultsTable.GetTableDBName())
            {
                TSecurityChecks.CheckUserModulePermissions(SharedConstants.PETRAMODULE_SYSADMIN, context);
                AResultTable = SSystemDefaultsAccess.LoadAll(AReadTransaction);
            }
            else if (ATablename == SSystemDefaultsGuiTable.GetTableDBName())
            {
                AResultTable = SSystemDefaultsGuiAccess.LoadAll(AReadTransaction);
            }
            else
            {
                throw new Exception("TCommonDataReader.GetData: unknown table " + ATablename);
            }

            // Accept row changes here so that the Client gets 'unmodified' rows
            AResultTable.AcceptChanges();
        }
        public static TSubmitChangesResult SaveData(string ATablename,
                                                    ref TTypedDataTable ASubmitTable, out TVerificationResultCollection AVerificationResult,
                                                    TDBTransaction AWriteTransaction)
        {
            AVerificationResult = null;

            // TODO: check write permissions
            string context = string.Format("SaveData {0}", SharedConstants.MODULE_ACCESS_MANAGER);

            if (ASubmitTable != null)
            {
                AVerificationResult = new TVerificationResultCollection();

                try
                {
                    if (ATablename == AAccountingPeriodTable.GetTableDBName())
                    {
                        AAccountingPeriodAccess.SubmitChanges((AAccountingPeriodTable)ASubmitTable, AWriteTransaction);

                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheableFinanceTablesEnum.AccountingPeriodList.ToString());
                    }
                    else if (ATablename == ACurrencyTable.GetTableDBName())
                    {
                        ACurrencyAccess.SubmitChanges((ACurrencyTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ADailyExchangeRateTable.GetTableDBName())
                    {
                        TSecurityChecks.CheckUserModulePermissions(
                            string.Format("AND({0},{1})", SharedConstants.PETRAGROUP_FINANCE1, SharedConstants.PETRAMODULE_FINEXRATE),
                            context);
                        ADailyExchangeRateAccess.SubmitChanges((ADailyExchangeRateTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ACorporateExchangeRateTable.GetTableDBName())
                    {
                        // AlanP:  I don't think this is used any more.  There is a TDS Save method instead
                        ACorporateExchangeRateAccess.SubmitChanges((ACorporateExchangeRateTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ACurrencyLanguageTable.GetTableDBName())
                    {
                        ACurrencyLanguageAccess.SubmitChanges((ACurrencyLanguageTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == AFeesPayableTable.GetTableDBName())
                    {
                        AFeesPayableAccess.SubmitChanges((AFeesPayableTable)ASubmitTable, AWriteTransaction);

                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheableFinanceTablesEnum.FeesPayableList.ToString());
                    }
                    else if (ATablename == AFeesReceivableTable.GetTableDBName())
                    {
                        AFeesReceivableAccess.SubmitChanges((AFeesReceivableTable)ASubmitTable, AWriteTransaction);

                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheableFinanceTablesEnum.FeesReceivableList.ToString());
                    }
                    else if (ATablename == AGiftBatchTable.GetTableDBName())
                    {
                        // This method is called from ADailyExchangeRate Setup - please do not remove
                        // The method is not required for changes made to the gift batch screens, which use a TDS
                        AGiftBatchAccess.SubmitChanges((AGiftBatchTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == AJournalTable.GetTableDBName())
                    {
                        // This method is called from ADailyExchangeRate Setup - please do not remove
                        // The method is not required for changes made to the journal screens, which use a TDS
                        AJournalAccess.SubmitChanges((AJournalTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ARecurringJournalTable.GetTableDBName())
                    {
                        // This method is called from Submit Recurring GL Batch form - please do not remove
                        // The method is not required for changes made to the journal screens, which use a TDS
                        ARecurringJournalAccess.SubmitChanges((ARecurringJournalTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ALedgerTable.GetTableDBName())
                    {
                        // This method is called from ADailyExchangeRate Testing - please do not remove
                        ALedgerAccess.SubmitChanges((ALedgerTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == AAnalysisTypeTable.GetTableDBName())
                    {
                        AAnalysisTypeAccess.SubmitChanges((AAnalysisTypeTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ASuspenseAccountTable.GetTableDBName())
                    {
                        ASuspenseAccountAccess.SubmitChanges((ASuspenseAccountTable)ASubmitTable, AWriteTransaction);

                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheableFinanceTablesEnum.SuspenseAccountList.ToString());
                    }
                    else if (ATablename == PcAttendeeTable.GetTableDBName())
                    {
                        PcAttendeeAccess.SubmitChanges((PcAttendeeTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcConferenceTable.GetTableDBName())
                    {
                        PcConferenceAccess.SubmitChanges((PcConferenceTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcConferenceCostTable.GetTableDBName())
                    {
                        PcConferenceCostAccess.SubmitChanges((PcConferenceCostTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcEarlyLateTable.GetTableDBName())
                    {
                        PcEarlyLateAccess.SubmitChanges((PcEarlyLateTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcSupplementTable.GetTableDBName())
                    {
                        PcSupplementAccess.SubmitChanges((PcSupplementTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcDiscountTable.GetTableDBName())
                    {
                        PcDiscountAccess.SubmitChanges((PcDiscountTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PInternationalPostalTypeTable.GetTableDBName())
                    {
                        ValidateInternationalPostalType(ref AVerificationResult, ASubmitTable);
                        ValidateInternationalPostalTypeManual(ref AVerificationResult, ASubmitTable);

                        if (TVerificationHelper.IsNullOrOnlyNonCritical(AVerificationResult))
                        {
                            PInternationalPostalTypeAccess.SubmitChanges((PInternationalPostalTypeTable)ASubmitTable, AWriteTransaction);
                        }
                    }
                    else if (ATablename == PtApplicationTypeTable.GetTableDBName())
                    {
                        PtApplicationTypeAccess.SubmitChanges((PtApplicationTypeTable)ASubmitTable, AWriteTransaction);

                        // mark dependent lists for needing to be refreshed since there was a change in base list
                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheablePersonTablesEnum.EventApplicationTypeList.ToString());
                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheablePersonTablesEnum.FieldApplicationTypeList.ToString());
                    }
                    else if (ATablename == PFormTable.GetTableDBName())
                    {
                        PFormAccess.SubmitChanges((PFormTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PFormalityTable.GetTableDBName())
                    {
                        PFormalityAccess.SubmitChanges((PFormalityTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PMailingTable.GetTableDBName())
                    {
                        PMailingAccess.SubmitChanges((PMailingTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName())
                    {
                        PPartnerGiftDestinationAccess.SubmitChanges((PPartnerGiftDestinationTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PmDocumentTypeTable.GetTableDBName())
                    {
                        PmDocumentTypeAccess.SubmitChanges((PmDocumentTypeTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == SGroupTable.GetTableDBName())
                    {
                        SGroupAccess.SubmitChanges((SGroupTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == SSystemDefaultsTable.GetTableDBName())
                    {
                        SSystemDefaultsAccess.SubmitChanges((SSystemDefaultsTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == SSystemDefaultsGuiTable.GetTableDBName())
                    {
                        SSystemDefaultsGuiAccess.SubmitChanges((SSystemDefaultsGuiTable)ASubmitTable, AWriteTransaction);
                    }
                    else
                    {
                        throw new EOPAppException("TCommonDataReader.SaveData: unknown table '" + ATablename + "'");
                    }
                }
                catch (Exception Exc)
                {
                    AVerificationResult.Add(
                        new TVerificationResult(null, "Cannot SubmitChanges:" + Environment.NewLine +
                                                Exc.Message, "UNDEFINED", TResultSeverity.Resv_Critical));
                }
            }

            if ((AVerificationResult != null) &&
                (AVerificationResult.Count > 0))
            {
                // Downgrade TScreenVerificationResults to TVerificationResults in order to allow
                // Serialisation (needed for .NET Remoting).
                TVerificationResultCollection.DowngradeScreenVerificationResults(AVerificationResult);

                return(AVerificationResult.HasCriticalErrors ? TSubmitChangesResult.scrError : TSubmitChangesResult.scrOK);
            }

            return(TSubmitChangesResult.scrOK);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Stores a System Default in the DB. If it was already there it gets updated, if it wasn't there it gets added.
        /// </summary>
        /// <remarks>The change gets reflected in the System Defaults Cache the next time the System Defaults Cache
        /// gets accessed.</remarks>
        /// <param name="AKey">Name of the System Default.</param>
        /// <param name="AValue">Value of the System Default.</param>
        /// <param name="AAdded">True if the System Default got added, false if it already existed.</param>
        /// <param name="ADataBase"></param>
        /// <remarks>SystemDefault Names are not case sensitive.</remarks>
        public void SetSystemDefault(String AKey, String AValue, out bool AAdded, TDataBase ADataBase = null)
        {
            TDataBase            DBConnectionObj  = null;
            TDBTransaction       WriteTransaction = new TDBTransaction();
            bool                 SubmissionOK     = false;
            SSystemDefaultsTable SystemDefaultsDT;
            Boolean              Added = false;

            try
            {
                // Open a separate DB Connection...
                DBConnectionObj = DBAccess.Connect("SetSystemDefault", ADataBase);

                // ...and start a DB Transaction on that separate DB Connection
                DBConnectionObj.WriteTransaction(ref WriteTransaction, ref SubmissionOK,
                                                 delegate
                {
                    SystemDefaultsDT = SSystemDefaultsAccess.LoadAll(WriteTransaction);

                    // This will find the row that matches a case-insensitive search of the table primary keys
                    SystemDefaultsDT.CaseSensitive = false;         // It is anyway
                    SSystemDefaultsRow match       = (SSystemDefaultsRow)SystemDefaultsDT.Rows.Find(AKey);

                    if (match != null)
                    {
                        // I already have this System Default in the DB --> simply update the Value in the DB.
                        // (This will often be the case!)
                        match.DefaultValue = AValue;

                        Added = false;
                    }
                    else
                    {
                        // The System Default isn't in the DB yet --> store it in the DB.
                        var SystemDefaultsDR                = SystemDefaultsDT.NewRowTyped(true);
                        SystemDefaultsDR.DefaultCode        = AKey;
                        SystemDefaultsDR.DefaultDescription = "Created in OpenPetra";
                        SystemDefaultsDR.DefaultValue       = AValue;

                        SystemDefaultsDT.Rows.Add(SystemDefaultsDR);

                        Added = true;
                    }

                    SSystemDefaultsAccess.SubmitChanges(SystemDefaultsDT, WriteTransaction);

                    SubmissionOK = true;
                });

                AAdded = Added;
            }
            catch (Exception Exc)
            {
                TLogging.Log(
                    "TSystemDefaultCache.SetSystemDefault: An Exception occured during the saving of the System Default '" + AKey +
                    "'. Value to be saved: + '" + AValue + "'" +
                    Environment.NewLine + Exc.ToString());

                throw;
            }
            finally
            {
                if (ADataBase == null)
                {
                    DBConnectionObj.CloseDBConnection();
                }

                if (SubmissionOK && (FSystemDefaultsDT != null))
                {
                    // We need to ensure that the next time the System Defaults Caches gets accessed it is refreshed from the DB!!!
                    FSystemDefaultsDT.Clear();
                    FSystemDefaultsDT = null;
                }
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Determines the 'Last Reminder Date', that is the date when PartnerReminders last ran.
        /// <para>
        /// This is done by reading a certain SystemDefault. If PartnerReminders was never run before,
        /// this SystemDefault is created.
        /// </para>
        /// </summary>
        /// <param name="ALastReminderDate">Date when PartnerReminders last ran. Will be January 1st, 1980
        /// if PartnerReminders never ran before.</param>
        /// <param name="ASystemDefaultsDR">SystemDefaults DataRow containing the date. This is used later for updating
        /// the date.</param>
        /// <param name="AReadWriteTransaction">Already instantiated DB Transaction.</param>
        /// <returns>True if the 'Last Reminder Date' could be read/created. False if PartnerReminders was never run before
        /// AND creation of the new SystemDefault record failed for some reason.</returns>
        private static bool GetLastReminderDate(out DateTime ALastReminderDate,
                                                out SSystemDefaultsRow ASystemDefaultsDR,
                                                TDBTransaction AReadWriteTransaction)
        {
            const string UNDEFINED_SYSTEMDEFAULT_LAST_REMINDER_DATE = "1980,1,1";   // Double check order!

            SSystemDefaultsTable SystemDefaultsDT = new SSystemDefaultsTable();
            string LastReminderDateStr;

            string[] DateParts;
            bool     ReturnValue = true;


            ASystemDefaultsDR = null;

            // Check if there is already a SystemDefault for the Last Reminder Date (most likely there is!)
            if (SSystemDefaultsAccess.Exists(SYSTEMDEFAULT_LAST_REMINDER_DATE, AReadWriteTransaction))
            {
                if (TLogging.DebugLevel >= 6)
                {
                    TLogging.Log("GetLastReminderDate: System Default for the Last Reminder Date exists: use it.");
                }

                // There is already a SystemDefault for the Last Reminder Date: read its value
                SystemDefaultsDT = SSystemDefaultsAccess.LoadByPrimaryKey(SYSTEMDEFAULT_LAST_REMINDER_DATE, AReadWriteTransaction);

                // Used later to update the row
                ASystemDefaultsDR = SystemDefaultsDT[0];
            }
            else
            {
                // System Default for the Last Reminder Date doesn't exist: add a new SystemDefault for future use
                if (TLogging.DebugLevel >= 6)
                {
                    TLogging.Log("GetLastReminderDate: System Default for the Last Reminder Date doesn't exist yet: creating it.");
                }

                ASystemDefaultsDR                    = SystemDefaultsDT.NewRowTyped();
                ASystemDefaultsDR.DefaultCode        = SYSTEMDEFAULT_LAST_REMINDER_DATE;
                ASystemDefaultsDR.DefaultDescription = SYSTEMDEFAULT_LAST_REMINDER_DATE_DESC;
                ASystemDefaultsDR.DefaultValue       = UNDEFINED_SYSTEMDEFAULT_LAST_REMINDER_DATE;

                try
                {
                    SSystemDefaultsAccess.SubmitChanges(SystemDefaultsDT, AReadWriteTransaction);
                }
                catch (Exception Exc)
                {
                    TLogging.Log("TProcessPartnerReminders.GetLastReminderDate: An Exception occured:" + Environment.NewLine + Exc.ToString());

                    throw;
                }
            }

            LastReminderDateStr = ASystemDefaultsDR.DefaultValue;

            // Last Reminder Date is stored as YEAR,MONTH,DAY
            DateParts         = LastReminderDateStr.Split(',');
            ALastReminderDate = new DateTime(
                Convert.ToInt32(DateParts[0]), Convert.ToInt32(DateParts[1]), Convert.ToInt32(DateParts[2]),
                0, 0, 1);   // One second past midnight

            if (TLogging.DebugLevel >= 6)
            {
                TLogging.Log(String.Format("GetLastReminderDate: DB Field value: {0}; Parsed date: {1}", LastReminderDateStr, ALastReminderDate));
            }

            return(ReturnValue);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Determines the 'Last Reminder Date', that is the date when PartnerReminders last ran.
        /// <para>
        /// This is done by reading a certain SystemDefault. If PartnerReminders was never run before,
        /// this SystemDefault is created.
        /// </para>
        /// </summary>
        /// <param name="ALastReminderDate">Date when PartnerReminders last ran. Will be January 1st, 1980
        /// if PartnerReminders never ran before.</param>
        /// <param name="ASystemDefaultsDR">SystemDefaults DataRow containing the date. This is used later for updating
        /// the date.</param>
        /// <param name="AReadWriteTransaction">Already instantiated DB Transaction.</param>
        /// <returns>True if the 'Last Reminder Date' could be read/created. False if PartnerReminders was never run before
        /// AND creation of the new SystemDefault record failed for some reason.</returns>
        private static bool GetLastReminderDate(out DateTime ALastReminderDate,
            out SSystemDefaultsRow ASystemDefaultsDR,
            TDBTransaction AReadWriteTransaction)
        {
            const string UNDEFINED_SYSTEMDEFAULT_LAST_REMINDER_DATE = "1980,1,1";   // Double check order!

            SSystemDefaultsTable SystemDefaultsDT = new SSystemDefaultsTable();
            string LastReminderDateStr;

            string[] DateParts;
            bool ReturnValue = true;


            ASystemDefaultsDR = null;

            // Check if there is already a SystemDefault for the Last Reminder Date (most likely there is!)
            if (SSystemDefaultsAccess.Exists(SYSTEMDEFAULT_LAST_REMINDER_DATE, AReadWriteTransaction))
            {
                if (TLogging.DebugLevel >= 6)
                {
                    TLogging.Log("GetLastReminderDate: System Default for the Last Reminder Date exists: use it.");
                }

                // There is already a SystemDefault for the Last Reminder Date: read its value
                SystemDefaultsDT = SSystemDefaultsAccess.LoadByPrimaryKey(SYSTEMDEFAULT_LAST_REMINDER_DATE, AReadWriteTransaction);

                // Used later to update the row
                ASystemDefaultsDR = SystemDefaultsDT[0];
            }
            else
            {
                // System Default for the Last Reminder Date doesn't exist: add a new SystemDefault for future use
                if (TLogging.DebugLevel >= 6)
                {
                    TLogging.Log("GetLastReminderDate: System Default for the Last Reminder Date doesn't exist yet: creating it.");
                }

                ASystemDefaultsDR = SystemDefaultsDT.NewRowTyped();
                ASystemDefaultsDR.DefaultCode = SYSTEMDEFAULT_LAST_REMINDER_DATE;
                ASystemDefaultsDR.DefaultDescription = SYSTEMDEFAULT_LAST_REMINDER_DATE_DESC;
                ASystemDefaultsDR.DefaultValue = UNDEFINED_SYSTEMDEFAULT_LAST_REMINDER_DATE;

                try
                {
                    SSystemDefaultsAccess.SubmitChanges(SystemDefaultsDT, AReadWriteTransaction);
                }
                catch (Exception Exc)
                {
                    TLogging.Log("TProcessPartnerReminders.GetLastReminderDate: An Exception occured:" + Environment.NewLine + Exc.ToString());

                    throw;
                }
            }

            LastReminderDateStr = ASystemDefaultsDR.DefaultValue;

            // Last Reminder Date is stored as YEAR,MONTH,DAY
            DateParts = LastReminderDateStr.Split(',');
            ALastReminderDate = new DateTime(
                Convert.ToInt32(DateParts[0]), Convert.ToInt32(DateParts[1]), Convert.ToInt32(DateParts[2]),
                0, 0, 1);   // One second past midnight

            if (TLogging.DebugLevel >= 6)
            {
                TLogging.Log(String.Format("GetLastReminderDate: DB Field value: {0}; Parsed date: {1}", LastReminderDateStr, ALastReminderDate));
            }

            return ReturnValue;
        }
Exemplo n.º 23
0
        /// <summary>
        /// Saves changes to the submitted Typed SystemDefaults DataTable to the DB.
        ///
        /// @comment Currently always returns false because the function needs to be
        /// rewritten!
        ///
        /// @todo Rewrite this function so that it saves entries that originally came
        /// from the s_system_parameter table in the DB to this table instead of
        /// writing them to the s_system_defaults table! Also use the DataStore to
        /// save the data instead of using SQL queries!!!
        ///
        /// </summary>
        /// <param name="ASystemDefaultsDataTable">Typed SystemDefaults DataTable</param>
        /// <returns>true if the System Defaults could be saved successfully
        /// </returns>
        public Boolean SaveSystemDefaults(SSystemDefaultsTable ASystemDefaultsDataTable)
        {
            // var
            // Transaction: OdbcTransaction;
            // ParametersArray: array of OdbcParameter;
            // Counter,
            // DefaultInDataBaseCount: Int16;
            // AllSubmissionsOK: Boolean;

            /* TODO 2 oChristanK cDB : Rewrite this function so that it saves entries that originally came from the s_system_parameter table
             * in the DB to this table instead of writing them to the s_system_defaults table! Also use the DataStore to
             * save the data instead of using SQL queries!!!
             */

            // Currently always returns false because the function needs to be rewritten!
            return(false);

            // AllSubmissionsOK := false;
            // DefaultInDataBaseCount := 0;
            //
            // if (ASystemDefaultsDataTable <> nil) and (ASystemDefaultsDataTable.Rows.Count > 0) then
            // begin
            // $IFDEF DEBUGMODE if TLogging.DL >= 8 then Console.WriteLine('Saving ' + (ASystemDefaultsDataTable.Rows.Count).ToString + ' System Defaults...'); $ENDIF
            //
            // Transaction := DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            //
            // Loop over all changed/added System Defaults
            // for Counter := 0 to ASystemDefaultsDataTable.Rows.Count  1 do
            // begin
            // Look whether the System Default already exists in the DB
            // SetLength(ParametersArray, 1);
            // ParametersArray[0] := new OdbcParameter('', OdbcType.VarChar, 32);
            // ParametersArray[0].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'].ToString;
            //
            // try
            // DefaultInDataBaseCount := Convert.ToInt16( DBAccess.GDBAccessObj.ExecuteScalar(
            // 'SELECT COUNT) ' +
            // 'FROM PUB_s_system_defaults ' +
            // 'WHERE s_default_code_c = ?', Transaction, false, ParametersArray) );
            // except
            // on exp: Exception do
            // begin
            // Result := false;
            // $IFDEF DEBUGMODE if TLogging.DL >= 9 then Console.WriteLine(this.GetType.FullName + '.SaveSystemDefaults: Error running count query!!! ' +
            // 'Possible cause: ' + exp.ToString); $ENDIF
            // Exit;
            // end;
            // end;
            //
            // if DefaultInDataBaseCount = 0 then
            // begin
            // System Default doesn't exist yet > create it

            /* $IFDEF DEBUGMODE if TLogging.DL >= 8 then Console.WriteLine('Inserting SystemDefault ' + ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'].ToString + '; Value: ' +
             * ASystemDefaultsDataTable.Rows[Counter].Item['s_default_value_c'].ToString);$ENDIF */

            // SetLength(ParametersArray, 3);
            // ParametersArray[0] := new OdbcParameter('', OdbcType.VarChar, 32);
            // ParametersArray[0].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'].ToString;
            // ParametersArray[0] := new OdbcParameter('', OdbcType.VarChar, 48);
            // ParametersArray[0].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_description_c'].ToString;
            // ParametersArray[2] := new OdbcParameter('', OdbcType.VarChar, 96);
            // ParametersArray[2].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_value_c'].ToString;
            //
            // try
            // DBAccess.GDBAccessObj.ExecuteNonQuery(
            // 'INSERT INTO PUB_s_system_defaults ' +
            // '(s_default_code_c, s_default_description_c, s_default_value_c) ' +
            // 'VALUES (?, ?, ?)', Transaction, false, ParametersArray);
            // except
            // on exp: Exception do
            // begin
            // Result := false;
            // $IFDEF DEBUGMODE if TLogging.DL >= 9 then Console.WriteLine(this.GetType.FullName + '.SaveSystemDefaults: Error running insert query!!! ' +
            // 'Possible cause: ' + exp.ToString); $ENDIF
            // Exit;
            // end;
            // end;
            // end
            // else
            // begin
            // System Default exists > update it

            /* $IFDEF DEBUGMODE if TLogging.DL >= 8 then Console.WriteLine('Updating SystemDefault ' + ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'].ToString + '; Value: ' +
             * ASystemDefaultsDataTable.Rows[Counter].Item['s_default_value_c'].ToString);$ENDIF */

            // SetLength(ParametersArray, 3);
            // ParametersArray[0] := new OdbcParameter('', OdbcType.VarChar, 48);
            // ParametersArray[0].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_description_c'];
            // ParametersArray[1] := new OdbcParameter('', OdbcType.VarChar, 96);
            // ParametersArray[1].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_value_c'];
            // ParametersArray[2] := new OdbcParameter('', OdbcType.VarChar, 32);
            // ParametersArray[2].Value := ASystemDefaultsDataTable.Rows[Counter].Item['s_default_code_c'];
            //
            // try
            // DBAccess.GDBAccessObj.ExecuteNonQuery(
            // 'UPDATE PUB_s_system_defaults ' +
            // 'SET s_default_description_c = ?, s_default_value_c = ? ' +
            // 'WHERE s_default_code_c = ?', Transaction, false, ParametersArray);
            // except
            // on exp: Exception do
            // begin
            // Result := false;
            // $IFDEF DEBUGMODE if TLogging.DL >= 9 then Console.WriteLine(this.GetType.FullName + '.SaveSystemDefaults: Error runing insert query!!! ' +
            // 'Possible cause: ' + exp.ToString); $ENDIF
            // Exit;
            // end;
            // end;
            // end;
            // end;
            //
            // DBAccess.GDBAccessObj.CommitTransaction;
            // Result := AllSubmissionsOK;
            // end
            // else
            // begin
            // nothing to save!
            // Result := false;
            // end;
        }