Ejemplo n.º 1
0
        /// <summary>
        /// Tests whether the current user has access to a particular Partner.
        /// </summary>
        /// <remarks>Corresponds to Progress 4GL Method 'CanAccessPartner' in
        /// common/sp_partn.p</remarks>
        /// <param name="APartnerKey">PartnerKey of Partner for which access should
        /// be checked for.</param>
        /// <param name="AThrowExceptionIfDenied"></param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with a new Database connection</param>
        /// <returns><see cref="TPartnerAccessLevelEnum.palGranted" /> if access
        /// to the Partner is granted (or Partner doesn't exist), otherwise a different
        /// <see cref="TPartnerAccessLevelEnum" /> value.</returns>
        public static TPartnerAccessLevelEnum CanAccessPartnerByKey(Int64 APartnerKey,
                                                                    bool AThrowExceptionIfDenied, TDataBase ADataBase = null)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction;
            PPartnerTable  PartnerTable;

            if (APartnerKey != 0)
            {
                TDataBase db = DBAccess.Connect("DetermineBestAddress", ADataBase);
                ReadTransaction = db.GetNewOrExistingTransaction(
                    IsolationLevel.ReadCommitted,
                    out NewTransaction);

                // Load Partner
                try
                {
                    PartnerTable = PPartnerAccess.LoadByPrimaryKey(APartnerKey, ReadTransaction);

                    if (PartnerTable.Rows.Count > 0)
                    {
                        // Partner exists, now check Access Level
                        if (!AThrowExceptionIfDenied)
                        {
                            return(CanAccessPartner(PartnerTable[0], ADataBase));
                        }
                        else
                        {
                            CanAccessPartnerExc(PartnerTable[0], ADataBase);

                            /*
                             * The previous Method call would throw an Exception
                             * in case access would not be granted and program execution
                             * would leave this Method at that point; if it doesn't
                             * then this implies that access is granted.
                             */
                            return(TPartnerAccessLevelEnum.palGranted);
                        }
                    }
                    else
                    {
                        // Partner not found. Access Level is Granted in this case.
                        return(TPartnerAccessLevelEnum.palGranted);
                    }
                }
                finally
                {
                    if (NewTransaction)
                    {
                        ReadTransaction.Commit();
                        TLogging.LogAtLevel(8, "TSecurity.CanAccessPartnerByKey: committed own transaction.");
                    }
                }
            }
            else
            {
                // Invalid Partner. Access Level is Granted in this case.
                return(TPartnerAccessLevelEnum.palGranted);
            }
        }
Ejemplo n.º 2
0
 public UC_Transaction()
 {
     sqlite = new SQLiteHelper();
     InitializeComponent();
     Add_GUI();
     readtran = new ReadTransaction();
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Tests whether the current user has access to a particular Partner.
        /// </summary>
        /// <remarks>
        /// <para>Corresponds to Progress 4GL Method 'CanAccessPartner' in
        /// common/sp_partn.p</para>
        /// <para>A shared implementation of this Method exists that has two additional
        /// Arguments. It needs the Foundation Row to be passed in, but has the
        /// advantage of not needing a Server roundtrip for a DB lookup!</para>
        /// </remarks>
        /// <param name="APartnerRow">Partner for which access should be checked for.</param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with a new Database connection</param>
        /// <returns><see cref="T:TPartnerAccessLevelEnum.palGranted" /> if access
        /// to the Partner is granted, otherwise a different
        /// <see cref="T:TPartnerAccessLevelEnum" /> value.</returns>
        public static TPartnerAccessLevelEnum CanAccessPartner(
            PPartnerRow APartnerRow, TDataBase ADataBase = null)
        {
            TDBTransaction   ReadTransaction;
            Boolean          NewTransaction;
            PFoundationTable FoundationTable;

            if (APartnerRow.PartnerKey != 0)
            {
                // If PartnerClass is ORGANISATION, we need to check if it is a Foundation
                if (APartnerRow.PartnerClass == SharedTypes.PartnerClassEnumToString(
                        TPartnerClass.ORGANISATION))
                {
                    TDataBase db = DBAccess.Connect("DetermineBestAddress", ADataBase);
                    ReadTransaction = db.GetNewOrExistingTransaction(
                        IsolationLevel.ReadCommitted,
                        out NewTransaction);

                    // Load Foundation
                    try
                    {
                        FoundationTable = PFoundationAccess.LoadByPrimaryKey(APartnerRow.PartnerKey,
                                                                             ReadTransaction);

                        if (FoundationTable.Rows.Count > 0)
                        {
                            // The ORGANISATION is a Foundation, we need to check Foundation Security
                            return(Ict.Petra.Shared.MPartner.TSecurity.CanAccessPartner(APartnerRow,
                                                                                        true, FoundationTable[0]));
                        }
                        else
                        {
                            // The ORGANISATION isn't a Foundation, we don't need to check Foundation Security
                            return(Ict.Petra.Shared.MPartner.TSecurity.CanAccessPartner(APartnerRow,
                                                                                        false, null));
                        }
                    }
                    finally
                    {
                        if (NewTransaction)
                        {
                            ReadTransaction.Commit();
                            TLogging.LogAtLevel(8, "TSecurity.CanAccessPartnerByKey: committed own transaction.");
                        }
                    }
                }
                else
                {
                    // PartnerClass isn't ORGANISATION, we don't need to check Foundation Security
                    return(Ict.Petra.Shared.MPartner.TSecurity.CanAccessPartner(APartnerRow,
                                                                                false, null));
                }
            }
            else
            {
                // Invalid Partner. Access Level is Granted in this case.
                return(TPartnerAccessLevelEnum.palGranted);
            }
        }
Ejemplo n.º 4
0
        private static bool GetAllReceivingFields(long AConferenceKey, ref DataTable AFieldsTable)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            TLogging.LogAtLevel(9, "TConferenceOptions.GetAllReceivingFields called!");

            TDataBase db = DBAccess.Connect("GetAllReceivingFields");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                OdbcParameter[] ParametersArray;

                ParametersArray = new OdbcParameter[0];

                DataSet TmpDS = ReadTransaction.DataBaseObj.Select(
                    "SELECT PUB_" + PUnitTable.GetTableDBName() + '.' + PUnitTable.GetPartnerKeyDBName() +
                    ", PUB_" + PUnitTable.GetTableDBName() + '.' + PUnitTable.GetUnitNameDBName() +
                    " FROM PUB_" + PUnitTable.GetTableDBName() +
                    ", PUB_" + PPartnerTable.GetTableDBName() + ", " +
                    "PUB_" + PPartnerTypeTable.GetTableDBName() +
                    " WHERE PUB_" + PUnitTable.GetTableDBName() + '.' + PUnitTable.GetPartnerKeyDBName() +
                    " = PUB_" + PPartnerTable.GetTableDBName() + '.' + PPartnerTable.GetPartnerKeyDBName() +
                    " AND PUB_" + PPartnerTypeTable.GetTableDBName() + '.' + PPartnerTypeTable.GetPartnerKeyDBName() +
                    " = PUB_" + PPartnerTable.GetTableDBName() + '.' + PPartnerTable.GetPartnerKeyDBName() +
                    " AND PUB_" + PPartnerTable.GetTableDBName() + '.' + PPartnerTable.GetStatusCodeDBName() + " = \"ACTIVE\"" +
                    " AND PUB_" + PPartnerTypeTable.GetTableDBName() + '.' + PPartnerTypeTable.GetTypeCodeDBName() + " = \"LEDGER\"" +
                    " ORDER BY PUB_" + PUnitTable.GetTableDBName() + '.' + PUnitTable.GetUnitNameDBName() + " ASC",
                    "TempTable", ReadTransaction, ParametersArray);

                DataTable ResultTale = TmpDS.Tables[0];

                for (int Counter = 0; Counter < ResultTale.Rows.Count; ++Counter)
                {
                    DataRow NewRow = AFieldsTable.NewRow();

                    NewRow[SELECTION]          = false;
                    NewRow[UNIT_KEY]           = ResultTale.Rows[Counter][PUnitTable.GetPartnerKeyDBName()];
                    NewRow[UNIT_NAME]          = ResultTale.Rows[Counter][PUnitTable.GetUnitNameDBName()];
                    NewRow[USED_IN_CONFERENCE] = true;

                    AFieldsTable.Rows.Add(NewRow);
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetReceivingFields: committed own transaction.");
                }
            }
            return(true);
        }
Ejemplo n.º 5
0
        public SelectData ProcessReadTransaction(ReadTransaction readTransaction)
        {
            lock (_tableLocks[readTransaction.TableDefinition.DataAddress])
            {
                SelectData selectData = _reader.GetRows(readTransaction.TableDefinition, readTransaction.Selects, readTransaction.PredicateOperations);

                return(selectData);
            }
        }
Ejemplo n.º 6
0
        public override ReadReportResponse ReadReport(ReadReportRequest request)
        {
            var response = new ReadReportResponse {
                FilePath     = request.FilePath,
                Transactions = new List <ReadTransaction>()
            };
            var source = ReportSource.GetLines(request.FilePath);
            var list   = ((string[])source).ToList();

            for (var row = 0; row < list.Count; row++)
            {
                var line = list[row];
                if (string.IsNullOrEmpty(response.SourceId))
                {
                    response.SourceId = DetermineSourceId(line);
                }
                if (line == TransactionBegin)
                {
                    var transaction = new ReadTransaction();
                    for (var i = 1; i < MaxRecipRowsCount && row + i < list.Count; i++)
                    {
                        line = list[row + i];
                        decimal amount;
                        if (ParseAmmount(line, TransactionAmountPosted, out amount) ||
                            ParseAmmount(line, TransactionAmount, out amount))
                        {
                            transaction.Amount        = amount;
                            transaction.DirectionType = amount < 0
                                                                ? DirectionType.Expense
                                                                : DirectionType.Incoming;
                        }
                        if (line.StartsWith(TransactionDate))
                        {
                            transaction.DateIn = DateTime.Parse(line.Replace(TransactionDate, ""));
                        }
                        if (line.StartsWith(TransactionNumber))
                        {
                            var number = line.Replace(TransactionNumber, "");
                            transaction.Comment += $"#{number}: ";
                        }
                        if (line.StartsWith(TransactionDescription))
                        {
                            transaction.Comment += line.Replace(TransactionDescription, "");
                        }
                        if (line.StartsWith(TransactionEnd))
                        {
                            response.Transactions.Add(transaction);
                            row += i;
                            break;
                        }
                    }
                }
            }
            return(response);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Adds the OMer field from the person and family record of the partner
        /// to the data table if it is not already there.
        /// </summary>
        /// <param name="APartnerKey"></param>
        /// <param name="AFieldsTable"></param>
        /// <returns></returns>
        private static bool GetReceivingFieldFromGiftDestination(long APartnerKey, ref DataTable AFieldsTable)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            TLogging.LogAtLevel(9, "TConferenceOptions.GetReceivingFieldFromGiftDestination called!");

            TDataBase db = DBAccess.Connect("GetReceivingFieldFromGiftDestination");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                PPersonTable PersonTable;
                PPartnerGiftDestinationTable GiftDestinationTable;
                long FamilyKey = APartnerKey;

                PersonTable = PPersonAccess.LoadByPrimaryKey(APartnerKey, ReadTransaction);

                if (PersonTable.Rows.Count > 0)
                {
                    PPersonRow PersonRow = (PPersonRow)PersonTable[0];

                    FamilyKey = PersonRow.FamilyKey;
                }

                GiftDestinationTable = PPartnerGiftDestinationAccess.LoadViaPPartner(FamilyKey, ReadTransaction);

                if (GiftDestinationTable.Rows.Count > 0)
                {
                    foreach (PPartnerGiftDestinationRow Row in GiftDestinationTable.Rows)
                    {
                        // check if the gift destination is currently active
                        if ((Row.DateEffective <= DateTime.Today) &&
                            (Row.IsDateExpiresNull() || ((Row.DateExpires >= DateTime.Today) && (Row.DateExpires != Row.DateEffective))))
                        {
                            AddFieldToTable(Row.FieldKey, ref AFieldsTable, ref ReadTransaction);
                        }
                    }
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetReceivingFieldFromPartnerTable: committed own transaction.");
                }
            }
            return(true);
        }
Ejemplo n.º 8
0
        public List <List <IComparable> > RunQuery(string query)
        {
            var tableName = _selectParser.GetTableName(query);

            var tableDef = _schemaFetcher.GetTableDefinition(tableName);

            List <SelectColumnDto> columns = _selectParser.GetColumns(query);

            IEnumerable <SelectColumnDto> selects = tableDef.ColumnDefinitions
                                                    .Select(x => new SelectColumnDto(x)).OrderBy(x => x.Index).ToList();

            foreach (var select in selects)
            {
                if (columns.Select(x => x.ColumnName).Contains(select.ColumnName) || columns.First().ColumnName == "*")
                {
                    select.IsInSelect = true;

                    SelectColumnDto firstMatchingColumn = columns.FirstOrDefault(x => x.ColumnName == select.ColumnName);

                    if (firstMatchingColumn != null)
                    {
                        select.AggregateFunction = firstMatchingColumn.AggregateFunction;
                    }
                }
            }

            PredicateStep predicateStep = _selectParser.ParsePredicates(query);

            predicateStep = _selectParser.GetPredicateTrailers(predicateStep, query);

            var predicateOperations = _predicateParser.BuildPredicateOperations(tableDef, predicateStep.Predicates);

            var readTransaction = new ReadTransaction
            {
                TableDefinition     = tableDef,
                Selects             = selects,
                PredicateOperations = predicateOperations
            };

            var rows = _lockManager.ProcessReadTransaction(readTransaction).Rows;

            if (predicateStep.PredicateTrailer != null && predicateStep.PredicateTrailer.Any())
            {
                rows = ApplyGroupByOperation(selects, predicateStep, rows);
                rows = ProcessPostPredicateOrderBy(selects, predicateStep, rows);
            }

            return(rows);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// check if the partner has a link to a cost centre (eg. a worker)
        /// </summary>
        /// <param name="APartnerKey"></param>
        /// <param name="ACostCentreCode"></param>
        /// <returns></returns>
        public static Boolean HasPartnerCostCentreLink(Int64 APartnerKey, out String ACostCentreCode)
        {
            Boolean                 ReturnValue;
            TDBTransaction          ReadTransaction;
            Boolean                 NewTransaction;
            StringCollection        RequiredColumns;
            AValidLedgerNumberTable ValidLedgerNumberTable;

            ACostCentreCode = "";

            RequiredColumns = new StringCollection();
            RequiredColumns.Add(AValidLedgerNumberTable.GetCostCentreCodeDBName());

            TDataBase db = DBAccess.Connect("HasPartnerCostCentreLink");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                             out NewTransaction);
            try
            {
                ValidLedgerNumberTable = AValidLedgerNumberAccess.LoadViaPPartnerPartnerKey(
                    APartnerKey,
                    RequiredColumns,
                    ReadTransaction,
                    null,
                    0,
                    0);

                if (ValidLedgerNumberTable.Rows.Count != 0)
                {
                    ACostCentreCode = ValidLedgerNumberTable[0].CostCentreCode;
                    ReturnValue     = true;
                }
                else
                {
                    ReturnValue = false;
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "HasPartnerCostCentreLink: committed own transaction.");
                }
            }
            return(ReturnValue);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Passes data as a Typed DataSet to the Supplier Edit Screen
        /// </summary>
        public AccountsPayableTDS GetData(Int64 APartnerKey)
        {
            TDBTransaction ReadTransaction;

            // create the DataSet that will later be passed to the Client
            AccountsPayableTDS MainDS = new AccountsPayableTDS();

            ReadTransaction = FDataBase.BeginTransaction(IsolationLevel.RepeatableRead, 5);

            try
            {
                try
                {
                    // Supplier
                    AApSupplierAccess.LoadByPrimaryKey(MainDS, APartnerKey, ReadTransaction);

                    if (MainDS.AApSupplier.Rows.Count == 0)
                    {
                        // Supplier does not exist
                        throw new Exception("supplier does not exist");
                    }
                }
                catch (Exception Exp)
                {
                    ReadTransaction.Rollback();
                    ReadTransaction = new TDBTransaction();
                    TLogging.Log("TSupplierEditUIConnector.LoadData exception: " + Exp.ToString(), TLoggingType.ToLogfile);
                    TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile);
                    throw;
                }
            }
            finally
            {
                if (ReadTransaction != null)
                {
                    ReadTransaction.Commit();
                }
            }

            // Accept row changes here so that the Client gets 'unmodified' rows
            MainDS.AcceptChanges();

            // Remove all Tables that were not filled with data before remoting them.
            MainDS.RemoveEmptyTables();

            return(MainDS);
        }
Ejemplo n.º 11
0
        public static PUnitTable GetOutreachOptions(Int64 AUnitKey)
        {
            String         ConferenceCodePrefix = "";
            PUnitTable     UnitTable            = new PUnitTable();
            PUnitRow       TemplateRow          = UnitTable.NewRowTyped(false);
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            TLogging.LogAtLevel(9, "TConferenceOptions.GetOutreachOptions called!");

            TDataBase db = DBAccess.Connect("GetOutreachOptions");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                /* Load data */
                UnitTable = PUnitAccess.LoadByPrimaryKey(AUnitKey, ReadTransaction);

                if (UnitTable.Rows.Count > 0)
                {
                    String ConferenceCode = ((PUnitRow)UnitTable.Rows[0]).OutreachCode;

                    if (ConferenceCode.Length >= 5)
                    {
                        ConferenceCodePrefix = ConferenceCode.Substring(0, 5) + "%";
                    }

                    StringCollection operators = new StringCollection();
                    operators.Add("LIKE");
                    TemplateRow.OutreachCode = ConferenceCodePrefix;

                    UnitTable = PUnitAccess.LoadUsingTemplate(TemplateRow, operators, null, ReadTransaction);
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetOutreachOptions: committed own transaction.");
                }
            }
            return(UnitTable);
        }
Ejemplo n.º 12
0
        private static String GetConferencePrefix(long AConferenceKey)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction   = false;
            String         ConferencePrefix = "-----";
            PUnitTable     UnitTable;

            TLogging.LogAtLevel(9, "TConferenceOptions.GetOutreachPrefix: called.");

            TDataBase db = DBAccess.Connect("GetConferencePrefix");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                UnitTable = PUnitAccess.LoadByPrimaryKey(AConferenceKey, ReadTransaction);

                if (UnitTable.Rows.Count > 0)
                {
                    if (UnitTable.Rows[0][PUnitTable.GetOutreachCodeDBName()] != System.DBNull.Value)
                    {
                        ConferencePrefix = (string)UnitTable.Rows[0][PUnitTable.GetOutreachCodeDBName()];

                        if (ConferencePrefix.Length > 5)
                        {
                            ConferencePrefix = ConferencePrefix.Substring(0, 5);
                        }
                    }
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetOutreachPrefix: committed own transaction.");
                }
            }

            return(ConferencePrefix);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// check if there is already a supplier record for the given partner
        /// </summary>
        /// <param name="APartnerKey"></param>
        /// <returns></returns>
        public bool CanFindSupplier(Int64 APartnerKey)
        {
            TDBTransaction ReadTransaction;
            bool           NewTransaction = false;
            bool           ReturnValue    = false;

            ReadTransaction = FDataBase.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                                    out NewTransaction);

            try
            {
                ReturnValue = AApSupplierAccess.Exists(APartnerKey, ReadTransaction);
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                }
            }
            return(ReturnValue);
        }
Ejemplo n.º 14
0
        private ReadTransaction DetermineTransaction(string[] columns)
        {
            ReadTransaction transaction = null;

            try {
                var amount = ParseAmount(columns[TransactionAmountColumnIndex].Replace("UAH", ""));
                transaction = new ReadTransaction {
                    Amount        = Math.Abs(amount),
                    DateIn        = DateTime.Parse(columns[TransactionDateColumnIndex]),
                    Comment       = columns[DescriptionColumnIndex],
                    DirectionType = amount < 0 ? DirectionType.Expense : DirectionType.Incoming,
                    Category      = null
                };
                if (TransferSignDetermineRules.Any(_ => transaction.Comment.Contains(_.Pattern)))
                {
                    transaction.IsTransfer = true;
                }
                transaction.Comment = transaction.Comment.Replace(DetailStandardPattern, "");
            } catch {
            }
            return(transaction);
        }
Ejemplo n.º 15
0
        private static bool GetReceivingFieldsForOneConference(long AConferenceKey, ref DataTable AFieldsTable)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            TLogging.LogAtLevel(9, "TConferenceOptions.GetReceivingFieldsForOneConference called!");

            TDataBase db = DBAccess.Connect("GetReceivingFieldsForOneConference");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                String           PartnerKeyDBName = PcAttendeeTable.GetPartnerKeyDBName();
                PcAttendeeTable  AttendeeTable;
                StringCollection FieldList = new StringCollection();
                FieldList.Add(PartnerKeyDBName);
                AttendeeTable = PcAttendeeAccess.LoadViaPcConference(AConferenceKey, FieldList, ReadTransaction);

                foreach (DataRow Row in AttendeeTable.Rows)
                {
                    long PartnerKey = (long)Row[PartnerKeyDBName];

                    GetReceivingFieldFromGiftDestination(PartnerKey, ref AFieldsTable);
                    GetReceivingFieldFromShortTermTable(PartnerKey, ref AFieldsTable);
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetReceivingFieldsForOneConference: committed own transaction.");
                }
            }
            return(true);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Adds the confirmed option code to the data table, using the values
        /// from the shorttermtable of the current partner
        /// </summary>
        /// <param name="APartnerKey"></param>
        /// <param name="AFieldsTable"></param>
        /// <returns></returns>
        private static bool GetReceivingFieldFromShortTermTable(long APartnerKey, ref DataTable AFieldsTable)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            TLogging.LogAtLevel(9, "TConferenceOptions.GetReceivingFieldFromShortTermTable called!");

            TDataBase db = DBAccess.Connect("GetReceivingFieldFromShortTermTable");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                PmShortTermApplicationTable ShortTermTable;

                ShortTermTable = PmShortTermApplicationAccess.LoadViaPPerson(APartnerKey, ReadTransaction);

                foreach (PmShortTermApplicationRow Row in ShortTermTable.Rows)
                {
                    if (!Row.IsStConfirmedOptionNull())
                    {
                        AddFieldToTable(Row.StConfirmedOption, ref AFieldsTable, ref ReadTransaction);
                    }
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetReceivingFieldFromShortTermTable: committed own transaction.");
                }
            }
            return(true);
        }
Ejemplo n.º 17
0
        // NEED: Method to map Customer, Account and Transaction table into corresponding objects in the program
        public void DownloadCustomerArray()
        {
            SqlConnection conn = new SqlConnection(ConnectionString);

            try
            {
                conn.Open();

                string CustomerQuery = "select * from customer";

                SqlDataReader ReadLogin;
                SqlCommand    LoginCmd;
                SqlDataReader ReadCustomer;
                SqlDataReader ReadAccount;
                SqlCommand    AccountCmd;
                SqlCommand    TransactionCmd;
                SqlDataReader ReadTransaction;

                using (SqlCommand CustomerCmd = new SqlCommand(CustomerQuery, conn))
                {
                    using (ReadCustomer = CustomerCmd.ExecuteReader())
                    {
                        while (ReadCustomer.Read())
                        {
                            Customer customer = new Customer(0, "", int.Parse(ReadCustomer["CustomerID"].ToString()), ReadCustomer["Name"].ToString(),
                                                             ReadCustomer["Address"].ToString(), ReadCustomer["City"].ToString(), ReadCustomer["PostCode"].ToString());

                            BankingSys.Instance().Customers.Add(customer);
                        }
                    }
                }

                foreach (var customer in BankingSys.Instance().Customers)
                {
                    using (LoginCmd = new SqlCommand("select loginID, passwordhash from login where customerID = " + customer.CustomerID, conn))
                    {
                        using (ReadLogin = LoginCmd.ExecuteReader())
                        {
                            while (ReadLogin.Read())
                            {
                                customer.LoginID  = int.Parse(ReadLogin["loginID"].ToString());
                                customer.Password = ReadLogin["PasswordHash"].ToString();
                            }
                        }
                    }
                }

                foreach (var customer in BankingSys.Instance().Customers)
                {
                    using (AccountCmd = new SqlCommand("select accountnumber, accounttype, balance from account where customerID = " + customer.CustomerID, conn))
                    {
                        using (ReadAccount = AccountCmd.ExecuteReader())
                        {
                            while (ReadAccount.Read())
                            {
                                Account account;

                                if (ReadAccount["AccountType"].ToString().Contains('S'))
                                {
                                    account = AccountFactory.Create('S') as SavingsAccount;
                                    account.AccountNumber = int.Parse(ReadAccount["AccountNumber"].ToString());
                                    account.CustomerID    = customer.CustomerID;
                                    account.Balance       = double.Parse(ReadAccount["Balance"].ToString());

                                    customer.Accounts.Add(account);
                                }
                                else if (ReadAccount["AccountType"].ToString().Contains('C'))
                                {
                                    account = AccountFactory.Create('C') as CheckingAccount;
                                    account.AccountNumber = int.Parse(ReadAccount["AccountNumber"].ToString());
                                    account.CustomerID    = customer.CustomerID;
                                    account.Balance       = double.Parse(ReadAccount["Balance"].ToString());

                                    customer.Accounts.Add(account);
                                }
                            }
                        }
                    }
                }


                foreach (var customer in BankingSys.Instance().Customers)
                {
                    foreach (var account in customer.Accounts)
                    {
                        using (TransactionCmd = new SqlCommand("select [transactionid], [transactiontype], [accountnumber], [destinationaccountnumber]," +
                                                               " [amount], [comment], [transactiontimeutc] from [transaction] where [accountnumber] = " + account.AccountNumber, conn))
                        {
                            using (ReadTransaction = TransactionCmd.ExecuteReader())
                            {
                                while (ReadTransaction.Read())
                                {
                                    Transaction transaction = new Transaction(int.Parse(ReadTransaction["TransactionID"].ToString()), Convert.ToChar(ReadTransaction["TransactionType"].ToString()),
                                                                              int.Parse(ReadTransaction["AccountNumber"].ToString()), int.Parse(ReadTransaction["DestinationAccountNumber"].ToString()),
                                                                              double.Parse(ReadTransaction["Amount"].ToString()), null, DateTime.Parse(ReadTransaction["TransactionTimeUTC"].ToString()));

                                    if (ReadTransaction["Comment"] != null)
                                    {
                                        transaction.Comment = ReadTransaction["Comment"].ToString();
                                    }

                                    account.Transactions.Add(transaction);
                                }
                            }
                        }
                    }
                }
            }
            catch (SqlException se)
            {
                Console.WriteLine("Exception: {0}", se.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Returns the Primary Key of the Location and the Location and PartnerLocation DataRows
        /// of the 'Best Address' of a Partner.
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of the Partner for which the 'Best Address'
        /// should be loaded for.</param>
        /// <param name="ABestAddressPK">Primary Key of the 'Best Address' Location</param>
        /// <param name="ALocationDR">DataRow containing the 'Best Address' Location</param>
        /// <param name="APartnerLocationDR">DataRow containing the 'Best Address' PartnerLocation</param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with a new Database connection</param>
        /// <returns>False if an invalid PartnerKey was passed in or if Petra Security
        /// denied access to the Partner or if Location/PartnerLocation Data could not be loaded for the
        /// Partner, otherwise true.</returns>
        public static bool GetPartnersBestLocationData(Int64 APartnerKey,
                                                       out TLocationPK ABestAddressPK,
                                                       out PLocationRow ALocationDR, out PPartnerLocationRow APartnerLocationDR, TDataBase ADataBase = null)
        {
            TDBTransaction        ReadTransaction;
            Boolean               NewTransaction;
            PPartnerLocationTable PartnerLocationDT;
            PLocationTable        LocationDT;

            ALocationDR        = null;
            APartnerLocationDR = null;
            ABestAddressPK     = null;

            if (APartnerKey > 0)
            {
                TDataBase db = DBAccess.Connect("GetPartnersBestLocationData", ADataBase);

                ReadTransaction = db.GetNewOrExistingTransaction(
                    IsolationLevel.ReadCommitted, out NewTransaction);

                try
                {
                    if (TMailing.GetPartnerLocations(APartnerKey, false,
                                                     true, true, true, out PartnerLocationDT, ADataBase))
                    {
                        TLogging.LogAtLevel(8,
                                            "TMailing.GetPartnersBestLocationData: processing " + PartnerLocationDT.Rows.Count.ToString() + " Locations...");

                        if (PartnerLocationDT.Rows.Count > 1)
                        {
                            Calculations.DeterminePartnerLocationsDateStatus(PartnerLocationDT, DateTime.Today);
                            ABestAddressPK = Calculations.DetermineBestAddress(PartnerLocationDT);
                        }
                        else if (PartnerLocationDT.Rows.Count == 1)
                        {
                            ABestAddressPK = new TLocationPK(PartnerLocationDT[0].SiteKey, PartnerLocationDT[0].LocationKey);
                        }
                        else
                        {
                            return(false);
                        }

//                      TLogging.LogAtLevel(8, "TMailing.GetPartnersBestLocationData: BestAddressPK: " + ABestAddressPK.SiteKey.ToString() + ", " + ABestAddressPK.LocationKey.ToString());
                        APartnerLocationDR = (PPartnerLocationRow)PartnerLocationDT.Rows.Find(
                            new object[] { APartnerKey, ABestAddressPK.SiteKey, ABestAddressPK.LocationKey });

                        LocationDT = TPPartnerAddressAggregate.LoadByPrimaryKey(
                            ABestAddressPK.SiteKey, ABestAddressPK.LocationKey, ReadTransaction);

                        if (LocationDT != null)
                        {
                            ALocationDR = LocationDT[0];
                        }
                        else
                        {
                            return(false);
                        }

                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                finally
                {
                    if (NewTransaction)
                    {
                        ReadTransaction.Commit();
                        TLogging.LogAtLevel(8, "TMailing.GetPartnersBestLocationData: committed own transaction.");
                    }
                }
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 19
0
        private static bool GetAllSendingFields(long AConferenceKey, ref DataTable AFieldsTable)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;
            PUnitTable     UnitTable;

            PcAttendeeTable AttendeeTable = new PcAttendeeTable();

            TLogging.LogAtLevel(9, "TConferenceOptions.GetAllSendingFields called!");

            TDataBase db = DBAccess.Connect("GetAllSendingFields");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                StringCollection FieldList = new StringCollection();
                FieldList.Add(PcAttendeeTable.GetHomeOfficeKeyDBName());

                AttendeeTable = PcAttendeeAccess.LoadAll(FieldList, ReadTransaction);

                long LastUnitKey = 0;
                long NewUnitKey  = 0;

                String HomeOfficeColumnName = PcAttendeeTable.GetHomeOfficeKeyDBName();

                foreach (DataRow AttendeeRow in AttendeeTable.Select("", HomeOfficeColumnName))
                {
                    if (AttendeeRow[HomeOfficeColumnName] != null)
                    {
                        NewUnitKey = (long)AttendeeRow[HomeOfficeColumnName];
                    }
                    else
                    {
                        continue;
                    }

                    if (LastUnitKey == NewUnitKey)
                    {
                        continue;
                    }

                    UnitTable = PUnitAccess.LoadByPrimaryKey(NewUnitKey, ReadTransaction);

                    if (UnitTable.Rows.Count > 0)
                    {
                        DataRow ResultRow = AFieldsTable.NewRow();

                        ResultRow[SELECTION]          = false;
                        ResultRow[UNIT_KEY]           = NewUnitKey;
                        ResultRow[UNIT_NAME]          = UnitTable[0][PUnitTable.GetUnitNameDBName()];
                        ResultRow[USED_IN_CONFERENCE] = true;

                        AFieldsTable.Rows.Add(ResultRow);
                        LastUnitKey = NewUnitKey;
                    }
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetAllSendingFields: committed own transaction.");
                }
            }
            return(true);
        }
Ejemplo n.º 20
0
        private object RunUpdateStatement(string sql)
        {
            List <KeyValuePair <string, string> > columnToValue = _updateParser.GetUpdates(sql);

            var tableName = _updateParser.GetTableName(sql);

            var tableDef = _schemaFetcher.GetTableDefinition(tableName);

            PredicateStep predicateStep = _updateParser.ParsePredicates(sql);

            var predicateOperations = _predicateParser.BuildPredicateOperations(tableDef, predicateStep.Predicates);

            var selects = tableDef.ColumnDefinitions
                          .Select(x => new SelectColumnDto(x)).OrderBy(x => x.Index).ToList();

            selects.ForEach(x => x.IsInSelect = true);

            var readTransaction = new ReadTransaction
            {
                TableDefinition     = tableDef,
                Selects             = selects,
                PredicateOperations = predicateOperations
            };

            var selectData = _lockManager.ProcessReadTransaction(readTransaction);

            var columnDefs = new List <ColumnDefinition>();

            foreach (var col in columnToValue)
            {
                var colDef = tableDef.ColumnDefinitions.Where(x => x.ColumnName.ToLower() == col.Key).Single();

                columnDefs.Add(colDef);
            }

            Dictionary <int, IComparable> indexToValue = new Dictionary <int, IComparable>();

            foreach (var columnNameToValue in columnToValue)
            {
                var colDef = tableDef.ColumnDefinitions.Single(x => x.ColumnName.ToLower() == columnNameToValue.Key);

                indexToValue[colDef.Index] = _stringParser.ConvertToType(columnNameToValue.Value, colDef.Type);
            }

            foreach (var colDef in columnDefs)
            {
                foreach (var row in selectData.Rows)
                {
                    row[colDef.Index] = indexToValue[colDef.Index];
                }
            }

            //each row is updated as its own transaction - not ideal for update - not atomic
            for (int i = 0; i < selectData.Rows.Count; i++)
            {
                var writeTransaction = new WriteTransaction
                {
                    Data              = selectData.Rows[i].ToArray(),
                    TableDefinition   = tableDef,
                    AddressToWriteTo  = selectData.RowLocations[i],
                    Query             = sql,
                    UpdateObjectCount = false
                };

                _lockManager.ProcessWriteTransaction(writeTransaction);
            }

            return(new object());
        }
Ejemplo n.º 21
0
        public static bool GetEarliestAndLatestDate(Int64 AConferenceKey, out DateTime AEarliestArrivalDate,
                                                    out DateTime ALatestDepartureDate, out DateTime AStartDate, out DateTime AEndDate)
        {
            AEarliestArrivalDate = DateTime.Today;
            ALatestDepartureDate = DateTime.Today;
            AStartDate           = DateTime.Today;
            AEndDate             = DateTime.Today;
            PmShortTermApplicationTable ShortTermerTable;
            PcConferenceTable           ConferenceTable;

            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            TLogging.LogAtLevel(9, "TConferenceOptions.GetEarliestAndLatestDates called!");

            TDataBase db = DBAccess.Connect("GetEarliestAndLatestDate");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                /* Load data */
                if (AConferenceKey == -1)
                {
                    ShortTermerTable = PmShortTermApplicationAccess.LoadAll(ReadTransaction);
                    ConferenceTable  = PcConferenceAccess.LoadAll(ReadTransaction);
                }
                else
                {
                    ShortTermerTable = PmShortTermApplicationAccess.LoadViaPUnitStConfirmedOption(AConferenceKey, ReadTransaction);
                    ConferenceTable  = PcConferenceAccess.LoadByPrimaryKey(AConferenceKey, ReadTransaction);
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetEarliestAndLatestDates: committed own transaction.");
                }
            }

            DateTime TmpEarliestArrivalTime = DateTime.MaxValue;
            DateTime TmpLatestDepartureTime = DateTime.MinValue;
            DateTime TmpStartTime           = DateTime.MaxValue;
            DateTime TmpEndTime             = DateTime.MinValue;

            foreach (PmShortTermApplicationRow ShortTermerRow in ShortTermerTable.Rows)
            {
                if ((!ShortTermerRow.IsArrivalNull()) &&
                    (ShortTermerRow.Arrival < TmpEarliestArrivalTime))
                {
                    TmpEarliestArrivalTime = ShortTermerRow.Arrival.Value;
                }

                if ((!ShortTermerRow.IsDepartureNull()) &&
                    (ShortTermerRow.Departure > TmpLatestDepartureTime))
                {
                    TmpLatestDepartureTime = ShortTermerRow.Departure.Value;
                }
            }

            foreach (PcConferenceRow ConferenceRow in ConferenceTable.Rows)
            {
                if ((!ConferenceRow.IsStartNull()) &&
                    (ConferenceRow.Start.Value < TmpStartTime))
                {
                    TmpStartTime = ConferenceRow.Start.Value;
                }

                if ((!ConferenceRow.IsEndNull()) &&
                    (ConferenceRow.End.Value > TmpEndTime))
                {
                    TmpEndTime = ConferenceRow.End.Value;
                }
            }

            if (TmpEarliestArrivalTime != DateTime.MaxValue)
            {
                AEarliestArrivalDate = TmpEarliestArrivalTime;
            }

            if (TmpLatestDepartureTime != DateTime.MinValue)
            {
                ALatestDepartureDate = TmpLatestDepartureTime;
            }

            if (TmpStartTime != DateTime.MaxValue)
            {
                AStartDate = TmpStartTime;
            }

            if (TmpEndTime != DateTime.MinValue)
            {
                AEndDate = TmpEndTime;
            }

            return(true);
        }
Ejemplo n.º 22
0
        public static SelectConferenceTDS GetConferences(String AConferenceName, String APrefix)
        {
            SelectConferenceTDS ResultTable = new SelectConferenceTDS();

            PcConferenceTable ConferenceTable = new PcConferenceTable();
            PcConferenceRow   TemplateRow     = (PcConferenceRow)ConferenceTable.NewRow();

            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            if (APrefix == "*")
            {
                APrefix = "";
            }

            if (AConferenceName == "*")
            {
                AConferenceName = "";
            }
            else if (AConferenceName.EndsWith("*"))
            {
                AConferenceName = AConferenceName.Substring(0, AConferenceName.Length - 1);
            }

            TLogging.LogAtLevel(9, "TConferenceOptions.GetConferences called!");

            TDataBase db = DBAccess.Connect("GetConferences");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                /* Load data */

                if (APrefix.Length > 0)
                {
                    APrefix = APrefix.Replace('*', '%') + "%";
                    TemplateRow.OutreachPrefix = APrefix;

                    StringCollection Operators = new StringCollection();
                    Operators.Add("LIKE");

                    ConferenceTable = PcConferenceAccess.LoadUsingTemplate(TemplateRow, Operators, null, ReadTransaction);
                }
                else
                {
                    ConferenceTable = PcConferenceAccess.LoadAll(ReadTransaction);
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetConferences: committed own transaction.");
                }
            }

            String        ShortName;
            TPartnerClass PartnerClass;

            foreach (PcConferenceRow ConferenceRow in ConferenceTable.Rows)
            {
                TPartnerServerLookups.GetPartnerShortName(ConferenceRow.ConferenceKey, out ShortName, out PartnerClass);

                if ((AConferenceName.Length > 0) &&
                    (!ShortName.StartsWith(AConferenceName, true, null)))
                {
                    continue;
                }

                ResultTable.PcConference.ImportRow(ConferenceRow);

                DataRow NewRow = ResultTable.PPartner.NewRow();
                NewRow[PPartnerTable.GetPartnerShortNameDBName()] = ShortName;
                NewRow[PPartnerTable.GetPartnerKeyDBName()]       = ConferenceRow.ConferenceKey;

                ResultTable.PPartner.Rows.Add(NewRow);
            }

            return(ResultTable);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// this checks if the new key is still available,
        /// and makes sure it will not be used as a default key anymore
        /// </summary>
        /// <param name="AFieldPartnerKey"></param>
        /// <param name="AOriginalDefaultKey">this has been previously retrieved from GetNewPartnerKey</param>
        /// <param name="ANewPartnerKey">the user proposes this key for a new partner; the function can change it and return a valid value, or -1</param>
        /// <param name="ADataBase"></param>
        /// <returns>whether or not ANewPartnerKey has a valid new partner key;
        /// if it cannot be assigned, the function returns false, and ANewPartnerKey is -1
        /// </returns>
        public static bool SubmitNewPartnerKey(System.Int64 AFieldPartnerKey, System.Int64 AOriginalDefaultKey, ref System.Int64 ANewPartnerKey, TDataBase ADataBase = null)
        {
            bool                ReturnValue = true;
            TDBTransaction      ReadTransaction;
            TDBTransaction      WriteTransaction;
            Boolean             NewTransaction;
            PPartnerLedgerTable PartnerLedgerDT;

            TDataBase db = DBAccess.Connect("SubmitNewPartnerKey", ADataBase);

            System.Int64 CurrentDefaultPartnerKey;

            if (ANewPartnerKey == AOriginalDefaultKey)
            {
                // The user has selected the default
                ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                                 out NewTransaction);

                try
                {
                    // Fetch the partner ledger record to update the last key

                    PartnerLedgerDT          = PPartnerLedgerAccess.LoadByPrimaryKey(AFieldPartnerKey, ReadTransaction);
                    CurrentDefaultPartnerKey = PartnerLedgerDT[0].PartnerKey + PartnerLedgerDT[0].LastPartnerId + 1;

                    if (ANewPartnerKey != CurrentDefaultPartnerKey)
                    {
                        // Someone else has updated this since, so we will use the new default
                        ANewPartnerKey = CurrentDefaultPartnerKey;
                    }

                    // Now check that this does not exist, and increment until we
                    // find one which does not
                    while (PPartnerAccess.Exists(ANewPartnerKey, ReadTransaction))
                    {
                        ANewPartnerKey = ANewPartnerKey + 1;
                    }
                }
                finally
                {
                    if (NewTransaction)
                    {
                        ReadTransaction.Rollback();

                        if (TLogging.DebugLevel >= TLogging.DEBUGLEVEL_TRACE)
                        {
                            Console.WriteLine("TNewPartnerKey.SubmitNewPartnerKey: rolled back own transaction.");
                        }
                    }
                }

                PartnerLedgerDT[0].LastPartnerId = (int)(ANewPartnerKey - PartnerLedgerDT[0].PartnerKey);

                WriteTransaction = db.GetNewOrExistingTransaction(IsolationLevel.Serializable,
                                                                  out NewTransaction);

                try
                {
                    PPartnerLedgerAccess.SubmitChanges(PartnerLedgerDT, WriteTransaction);

                    if (NewTransaction)
                    {
                        WriteTransaction.Commit();
                    }
                }
                catch (Exception Exc)
                {
                    TLogging.Log("An Exception occured during the submission of a new PartnerKey:" + Environment.NewLine + Exc.ToString());

                    if (NewTransaction)
                    {
                        WriteTransaction.Rollback();
                    }

                    throw;
                }
            }
            // end of: The user has selected the default
            else
            {
                ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                                 out NewTransaction);

                try
                {
                    // check if the Partner Key is already being used
                    if (PPartnerAccess.Exists(ANewPartnerKey, ReadTransaction))
                    {
                        ANewPartnerKey = -1;
                        ReturnValue    = false;
                    }
                }
                finally
                {
                    if (NewTransaction)
                    {
                        ReadTransaction.Rollback();

                        if (TLogging.DebugLevel >= TLogging.DEBUGLEVEL_TRACE)
                        {
                            Console.WriteLine("TNewPartnerKey.SubmitNewPartnerKey: rolled back own transaction.");
                        }
                    }
                }
            }

            if (ADataBase == null)
            {
                db.CloseDBConnection();
            }

            return(ReturnValue);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates a list of locations for a given Partner.
        /// </summary>
        /// <remarks>Corresponds in parts with with Progress 4GL Method
        /// 'GetPartnerLocations' in partner/maillib.p.</remarks>
        /// <param name="APartnerKey">PartnerKey of the Partner being processed.</param>
        /// <param name="AMailingAddressesOnly">If true: only include addresses with mailing flag set.</param>
        /// <param name="AIncludeCurrentAddresses">If true: include current addresses.</param>
        /// <param name="AIncludeFutureAddresses">If true: include future addresses.</param>
        /// <param name="AIncludeExpiredAddresses">If true: include expired addresses.</param>
        /// <param name="APartnerLocations">The Locations of the Partner being processed.</param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with a new Database connection</param>
        /// <returns>False if an invalid PartnerKey was passed in or if Petra Security
        /// denied access to the Partner, otherwise true.</returns>
        public static bool GetPartnerLocations(Int64 APartnerKey,
                                               bool AMailingAddressesOnly,
                                               bool AIncludeCurrentAddresses,
                                               bool AIncludeFutureAddresses,
                                               bool AIncludeExpiredAddresses,
                                               out PPartnerLocationTable APartnerLocations,
                                               TDataBase ADataBase = null)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction;

            String  SelectSQL;
            DataSet FillDataSet;

            OdbcParameter param;

            // Initialise out Argument
            APartnerLocations = null;

            if (APartnerKey > 0)
            {
                TLogging.LogAtLevel(8, "TMailing.GetPartnerLocations: Checking access to Partner.");

                if (TSecurity.CanAccessPartnerByKey(APartnerKey, false, ADataBase) ==
                    TPartnerAccessLevelEnum.palGranted)
                {
                    TDataBase db = DBAccess.Connect("GetPartnerLocations", ADataBase);

                    ReadTransaction = db.GetNewOrExistingTransaction(
                        IsolationLevel.ReadCommitted,
                        out NewTransaction);

                    // Load Partner Locations, taking passed in restrictions into account.
                    try
                    {
                        SelectSQL =
                            "SELECT *" +
                            "  FROM PUB_" + PPartnerLocationTable.GetTableDBName() +
                            " WHERE " + PPartnerLocationTable.GetPartnerKeyDBName() + " = ?" +
                            "   AND (NOT ? = true OR (? = true AND " + PPartnerLocationTable.GetSendMailDBName() + " = true))" +
                            "   AND ((? = true AND ((" + PPartnerLocationTable.GetDateEffectiveDBName() + " <= ?" +
                            "          OR " + PPartnerLocationTable.GetDateEffectiveDBName() + " IS NULL)" +
                            "     AND (" + PPartnerLocationTable.GetDateGoodUntilDBName() + " >= ?" +
                            "          OR " + PPartnerLocationTable.GetDateGoodUntilDBName() + " IS NULL)))" +
                            "     OR (? = true AND " + PPartnerLocationTable.GetDateEffectiveDBName() + " > ?)" +
                            "     OR (? = true AND " + PPartnerLocationTable.GetDateGoodUntilDBName() + " < ?))";

                        List <OdbcParameter> parameters = new List <OdbcParameter>();
                        param       = new OdbcParameter("PartnerKey", OdbcType.Decimal, 10);
                        param.Value = APartnerKey;
                        parameters.Add(param);
                        param       = new OdbcParameter("MailingAddressOnly1", OdbcType.Bit);
                        param.Value = AMailingAddressesOnly;
                        parameters.Add(param);
                        param       = new OdbcParameter("MailingAddressOnly2", OdbcType.Bit);
                        param.Value = AMailingAddressesOnly;
                        parameters.Add(param);
                        param       = new OdbcParameter("IncludeCurrentAddresses", OdbcType.Bit);
                        param.Value = AIncludeCurrentAddresses;
                        parameters.Add(param);
                        param       = new OdbcParameter("TodaysDate1", OdbcType.Date);
                        param.Value = DateTime.Now;
                        parameters.Add(param);
                        param       = new OdbcParameter("TodaysDate2", OdbcType.Date);
                        param.Value = DateTime.Now;
                        parameters.Add(param);
                        param       = new OdbcParameter("IncludeFutureAddresses", OdbcType.Bit);
                        param.Value = AIncludeFutureAddresses;
                        parameters.Add(param);
                        param       = new OdbcParameter("TodaysDate3", OdbcType.Date);
                        param.Value = DateTime.Now;
                        parameters.Add(param);
                        param       = new OdbcParameter("IncludeExpiredAddresses", OdbcType.Bit);
                        param.Value = AIncludeExpiredAddresses;
                        parameters.Add(param);
                        param       = new OdbcParameter("TodaysDate4", OdbcType.Date);
                        param.Value = DateTime.Now;
                        parameters.Add(param);

                        /*
                         * Our out Argument 'APartnerLocations' is a Typed DataTable, but SelectDT
                         * returns an untyped DataTable, therefore we need to create a Typed DataTable
                         * that contains the data of the returned untyped DataTable!
                         */
                        FillDataSet       = new DataSet();
                        APartnerLocations = new PPartnerLocationTable(PPartnerLocationTable.GetTableDBName());
                        FillDataSet.Tables.Add(APartnerLocations);

                        db.Select(FillDataSet, SelectSQL,
                                  PPartnerLocationTable.GetTableDBName(),
                                  ReadTransaction,
                                  parameters.ToArray());
//                      TLogging.LogAtLevel(7, "TMailing.GetPartnerLocations:  FillDataSet.Tables.Count: " + FillDataSet.Tables.Count.ToString());
                        FillDataSet.Tables.Remove(APartnerLocations);

                        if (APartnerLocations.Rows.Count > 0)
                        {
//                          TLogging.LogAtLevel(7, "TMailing.GetPartnerLocations: Found " + APartnerLocations.Rows.Count.ToString() + " PartnerLocations found for Partner " + APartnerKey.ToString() + ".");
                        }
                        else
                        {
                            /*
                             * /* No Rows returned = no PartnerLocations for Partner.
                             * That shouldn't happen with existing Partners, but if it does (eg. non-existing
                             * PartnerKey passed in) we return an empty Typed DataTable.
                             */
//                          TLogging.LogAtLevel(7, "TMailing.GetPartnerLocations: No PartnerLocations found for Partner " + APartnerKey.ToString() + "!");
                            APartnerLocations = new PPartnerLocationTable();
                        }
                    }
                    finally
                    {
                        if (NewTransaction)
                        {
                            ReadTransaction.Commit();
                            TLogging.LogAtLevel(7, "TMailing.GetPartnerLocations: committed own transaction.");
                        }
                    }

                    return(true);
                }
                else
                {
                    TLogging.LogAtLevel(8, "TMailing.GetPartnerLocations: Access to Partner DENIED!");

                    // Petra Security prevents us from accessing this Partner -> return false;
                    return(false);
                }
            }
            else
            {
                // Invalid PartnerKey -> return false;
                return(false);
            }
        }
Ejemplo n.º 25
0
        public static bool GetFieldUnits(Int64 AConferenceKey, TUnitTypeEnum AFieldTypes, out DataTable AFieldsTable, out String AConferencePrefix)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            AFieldsTable      = new DataTable("Field Units");
            AConferencePrefix = "";
            PUnitTable UnitTable;
            DataTable  TmpTable;

            PmShortTermApplicationTable ShortTermerTable = new PmShortTermApplicationTable();

            AFieldsTable.Columns.Add("Selection", System.Type.GetType("System.Boolean"));
            AFieldsTable.Columns.Add("Unit_Key", System.Type.GetType("System.Int64"));
            AFieldsTable.Columns.Add("Unit_Name", System.Type.GetType("System.String"));
            AFieldsTable.Columns.Add("Outreach_Code", System.Type.GetType("System.String"));
            AFieldsTable.Columns.Add("Used_in_Conference", System.Type.GetType("System.Boolean"));

            AConferencePrefix = TConferenceOptions.GetConferencePrefix(AConferenceKey);

            switch (AFieldTypes)
            {
            case TUnitTypeEnum.utSendingFields:
                return(TConferenceOptions.GetSendingFields(AConferenceKey, ref AFieldsTable));

            case TUnitTypeEnum.utReceivingFields:
                return(TConferenceOptions.GetReceivingFields(AConferenceKey, ref AFieldsTable));

            case TUnitTypeEnum.utOutreachOptions:

                if (TConferenceOptions.GetOutreachOptions(AConferenceKey, out TmpTable))
                {
                    foreach (DataRow Row in TmpTable.Rows)
                    {
                        DataRow NewRow = AFieldsTable.NewRow();

                        NewRow[SELECTION]          = false;
                        NewRow[UNIT_KEY]           = Row["Partner Key"];
                        NewRow[UNIT_NAME]          = Row["Unit Name"];
                        NewRow[CAMPAIGN_CODE]      = Row["Outreach Code"];
                        NewRow[USED_IN_CONFERENCE] = true;

                        AFieldsTable.Rows.Add(NewRow);
                    }

                    return(true);
                }

                return(false);

            default:
                break;
            }

            TLogging.LogAtLevel(9, "TConferenceOptions.GetFieldUnits called!");

            TDataBase db = DBAccess.Connect("GetFieldUnits");

            ReadTransaction = db.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                             out NewTransaction);

            try
            {
                StringCollection FieldList = new StringCollection();
                FieldList.Add(PmShortTermApplicationTable.GetStFieldChargedDBName());
                FieldList.Add(PmShortTermApplicationTable.GetConfirmedOptionCodeDBName());
                FieldList.Add(PmShortTermApplicationTable.GetRegistrationOfficeDBName());

                ShortTermerTable = PmShortTermApplicationAccess.LoadAll(FieldList, ReadTransaction);

                long LastUnitKey           = 0;
                long NewUnitKey            = 0;
                bool IsUsedInOneConference = false;

                String      ConfirmedOptionCode = "";
                System.Type StringType          = System.Type.GetType("System.String");

                String SearchedColumnName = "";

                switch (AFieldTypes)
                {
                case TUnitTypeEnum.utChargedFields:
                    SearchedColumnName = PmShortTermApplicationTable.GetStFieldChargedDBName();
                    break;

                case TUnitTypeEnum.utRegisteringFields:
                    SearchedColumnName = PmShortTermApplicationTable.GetRegistrationOfficeDBName();
                    break;

                default:
                    break;
                }

                foreach (DataRow ShortTermerRow in ShortTermerTable.Select("", SearchedColumnName))
                {
                    if ((ShortTermerRow[SearchedColumnName] != null) &&
                        (ShortTermerRow[SearchedColumnName].ToString().Length > 0))
                    {
                        NewUnitKey = (long)ShortTermerRow[SearchedColumnName];
                    }
                    else
                    {
                        continue;
                    }

                    if (LastUnitKey != NewUnitKey)
                    {
                        if ((AFieldsTable.Rows.Count > 0) &&
                            (IsUsedInOneConference))
                        {
                            AFieldsTable.Rows[AFieldsTable.Rows.Count - 1][USED_IN_CONFERENCE] = true;
                        }

                        IsUsedInOneConference = false;
                    }

                    // We have to check from every shorttermer if the charged field is used
                    // in this conference
                    if (IsUsedInOneConference)
                    {
                        continue;
                    }

                    if (ShortTermerRow[PmShortTermApplicationTable.GetConfirmedOptionCodeDBName()].GetType() == StringType)
                    {
                        ConfirmedOptionCode = (string)ShortTermerRow[PmShortTermApplicationTable.GetConfirmedOptionCodeDBName()];
                    }
                    else
                    {
                        ConfirmedOptionCode = "";
                    }

                    if (ConfirmedOptionCode.StartsWith(AConferencePrefix))
                    {
                        IsUsedInOneConference = true;
                    }

                    if (LastUnitKey == NewUnitKey)
                    {
                        continue;
                    }

                    UnitTable = PUnitAccess.LoadByPrimaryKey(NewUnitKey, ReadTransaction);

                    if (UnitTable.Rows.Count > 0)
                    {
                        DataRow ResultRow = AFieldsTable.NewRow();

                        ResultRow[SELECTION]          = false;
                        ResultRow[UNIT_KEY]           = NewUnitKey;
                        ResultRow[UNIT_NAME]          = UnitTable[0][PUnitTable.GetUnitNameDBName()];
                        ResultRow[CAMPAIGN_CODE]      = ConfirmedOptionCode;
                        ResultRow[USED_IN_CONFERENCE] = IsUsedInOneConference;

                        AFieldsTable.Rows.Add(ResultRow);
                        LastUnitKey = NewUnitKey;
                    }
                }

                // Check for the previous entry the "IsUsedInConference" field
                if ((AFieldsTable.Rows.Count > 0) &&
                    (IsUsedInOneConference))
                {
                    AFieldsTable.Rows[AFieldsTable.Rows.Count - 1][USED_IN_CONFERENCE] = true;
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    ReadTransaction.Commit();
                    TLogging.LogAtLevel(7, "TConferenceOptions.GetFieldUnits: committed own transaction.");
                }
            }
            return(true);
        }
Ejemplo n.º 26
0
        private void JournalAnalyze(List <string> lsFile_Journal)
        {
            try
            {
                readtran = new ReadTransaction();
                tre_LstTrans.Nodes.Clear();
                propertyGrid1.SelectedObject = null;
                fctxt_FullLog.Text           = string.Empty;
                if (!cb_FullTime.Checked)
                {
                    readtran.StartDate = dateTimePicker_Start.Value;
                    readtran.EndDate   = dateTimePicker_End.Value;
                }
                if (readtran.Reads(lsFile_Journal))
                {
                    string day;
                    foreach (KeyValuePair <string, Dictionary <DateTime, object> > kTerminal in readtran.ListTransaction)
                    {
                        int      countCycle            = kTerminal.Value.Where(x => (x.Value is Cycle)).ToList().Count;
                        int      countTransaction      = kTerminal.Value.Where(x => (x.Value is Transaction)).ToList().Count;
                        int      countTransactionEvent = kTerminal.Value.Where(x => (x.Value is TransactionEvent)).ToList().Count;
                        TreeNode ndTerminal            = tre_LstTrans.Nodes.Add(kTerminal.Key, String.Format("Terminal ID: {0} - Total: {1} transactions", kTerminal.Key, kTerminal.Value.Count), "Terminal", "Terminal");

                        foreach (KeyValuePair <DateTime, object> kTransaction in kTerminal.Value.OrderBy(x => x.Key))
                        {
                            day = String.Format("{0:" + readtran.FormatDate + "}", kTransaction.Key);
                            TreeNode ndDay = new TreeNode(day);
                            if (ndTerminal.Nodes.ContainsKey(day))
                            {
                                ndDay = ndTerminal.Nodes[day];
                            }
                            else
                            {
                                ndDay = ndTerminal.Nodes.Add(day, day, "Date", "DateOpen");
                            }
                            string   textDisplay   = kTransaction.Value.ToString();
                            TreeNode ndTransaction = ndDay.Nodes.Add(textDisplay, textDisplay);
                            ndTransaction.Tag = kTransaction.Value;
                            if (ndTransaction.Tag is Transaction)
                            {
                                ndTransaction.ImageKey         = "Flag";
                                ndTransaction.SelectedImageKey = "Flag_Success";
                            }
                            else if (ndTransaction.Tag is TransactionEvent)
                            {
                                ndTransaction.ImageKey         = "Device";
                                ndTransaction.SelectedImageKey = "Device";
                            }
                            else
                            {
                                ndTransaction.ImageKey         = "Cycle";
                                ndTransaction.SelectedImageKey = "Cycle";
                            }
                            ndDay.Text = day + " Total: " + ndDay.Nodes.Count + " transactions";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                InitParametar.Send_Error(ex.ToString(), MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name);
            }
        }