private void InitUserControlsManually()
        {
            // set controls in filter to default values
            ucoFilter.InitialiseUserControl();

            // Hook up EventFilterChanged Event to be able to react to changed filter
            ucoFilter.EventFilterChanged += new TEventHandlerEventFilterChanged(this.EventFilterChanged);

            //grdEvent.AutoSizeCells();

            // now the filter is initialized we can load the initial data
            LoadEventListData();

            grdEvent.Columns.Clear();

            grdEvent.AddTextColumn("Event Name", FEventTable.Columns[PPartnerTable.GetPartnerShortNameDBName()]);
            grdEvent.AddTextColumn("Event Code", FEventTable.Columns[PUnitTable.GetOutreachCodeDBName()]);
            grdEvent.AddTextColumn("Country", FEventTable.Columns[PCountryTable.GetCountryNameDBName()]);
            grdEvent.AddDateColumn("Start Date", FEventTable.Columns[PPartnerLocationTable.GetDateEffectiveDBName()]);
            grdEvent.AddDateColumn("End Date", FEventTable.Columns[PPartnerLocationTable.GetDateGoodUntilDBName()]);
            grdEvent.AddPartnerKeyColumn("Event Key", FEventTable.Columns[PPartnerTable.GetPartnerKeyDBName()]);
            grdEvent.AddTextColumn("Event Type", FEventTable.Columns[PUnitTable.GetUnitTypeCodeDBName()]);

            FEventTable.DefaultView.AllowDelete = false;
            FEventTable.DefaultView.AllowEdit   = false;
            FEventTable.DefaultView.AllowNew    = false;

            grdEvent.Selection.EnableMultiSelection = false;
            grdEvent.AutoResizeGrid();
            grdEvent.Selection.SelectRow(1, true);
        }
        private void LoadEventListData()
        {
            string    CheckedMember   = "CHECKED";
            string    ValueMember     = PPartnerTable.GetPartnerKeyDBName();
            string    DisplayMember   = PPartnerTable.GetPartnerShortNameDBName();
            string    EventCodeMember = PUnitTable.GetOutreachCodeDBName();
            DataTable Table;

            Table = TRemote.MPartner.Partner.WebConnectors.GetEventUnits
                        (ucoFilter.IncludeConferenceUnits, ucoFilter.IncludeOutreachUnits,
                        ucoFilter.NameFilter, false, ucoFilter.CurrentAndFutureEventsOnly);

            DataView view = new DataView(Table);

            DataTable NewTable = view.ToTable(true, new string[] { DisplayMember, ValueMember, EventCodeMember });

            NewTable.Columns.Add(new DataColumn(CheckedMember, typeof(bool)));

            clbEvent.Columns.Clear();
            clbEvent.AddCheckBoxColumn("", NewTable.Columns[CheckedMember], 17, false);
            clbEvent.AddTextColumn(Catalog.GetString("Event Name"), NewTable.Columns[DisplayMember], 240);
            clbEvent.AddPartnerKeyColumn(Catalog.GetString("Partner Key"), NewTable.Columns[ValueMember], 100);

            // outreach/event code column only needed in case of displaying Outreaches
            if (ucoFilter.IncludeOutreachUnits)
            {
                clbEvent.AddTextColumn(Catalog.GetString("Event Code"), NewTable.Columns[EventCodeMember], 110);
            }

            clbEvent.DataBindGrid(NewTable, DisplayMember, CheckedMember, ValueMember, false, true, false);

            //TODO: only temporarily until settings file exists
            clbEvent.SetCheckedStringList("");
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns the Family Members of a Family.
        /// </summary>
        /// <param name="AFamilyPartnerKey">PartnerKey of the FAMILY.</param>
        /// <param name="AReadTransaction">Open DB Transaction.</param>
        /// <returns>An Instance of <see cref="PartnerInfoTDSFamilyMembersTable" />.
        /// If there were Family Members, there will be one DataRow for each Family Member.</returns>
        private static PartnerInfoTDSFamilyMembersTable GetFamilyMembers(Int64 AFamilyPartnerKey,
                                                                         TDBTransaction AReadTransaction)
        {
            OdbcParameter[] ParametersArray;
            DataSet         TmpDS;
            PPersonTable    FamilyPersonsDT;
            PartnerInfoTDSFamilyMembersRow   NewRow;
            PartnerInfoTDSFamilyMembersTable FamilyMembersDT;

            FamilyMembersDT = new PartnerInfoTDSFamilyMembersTable();

            ParametersArray          = new OdbcParameter[1];
            ParametersArray[0]       = new OdbcParameter("", OdbcType.Decimal, 10);
            ParametersArray[0].Value = (System.Object)AFamilyPartnerKey;

            TmpDS = new DataSet();

            FamilyPersonsDT = new PPersonTable();
            TmpDS.Tables.Add(FamilyPersonsDT);

            AReadTransaction.DataBaseObj.Select(TmpDS,
                                                "SELECT " + "PUB_" + PPartnerTable.GetTableDBName() + '.' +
                                                PPartnerTable.GetPartnerKeyDBName() + ", " +
                                                PPersonTable.GetFamilyNameDBName() + ", " +
                                                PPersonTable.GetTitleDBName() + ", " +
                                                PPersonTable.GetFirstNameDBName() + ", " +
                                                PPersonTable.GetMiddleName1DBName() + ", " +
                                                PPersonTable.GetFamilyIdDBName() + ' ' +
                                                "FROM PUB_" + PPersonTable.GetTableDBName() +
                                                " INNER JOIN " + "PUB_" + PPartnerTable.GetTableDBName() + " ON " +
                                                "PUB_" + PPersonTable.GetTableDBName() + '.' +
                                                PPartnerTable.GetPartnerKeyDBName() + " = " +
                                                "PUB_" + PPartnerTable.GetTableDBName() + '.' +
                                                PPartnerTable.GetPartnerKeyDBName() + ' ' +
                                                "WHERE " + PPersonTable.GetFamilyKeyDBName() + " = ? " +
                                                "AND " + PPartnerTable.GetStatusCodeDBName() + " <> '" +
                                                SharedTypes.StdPartnerStatusCodeEnumToString(TStdPartnerStatusCode.spscMERGED) + "' " + // Make sure we don't load MERGED Partners (shouldn't have a p_family_key_n, but just in case.)
                                                "ORDER BY " + PPersonTable.GetFamilyIdDBName() + " ASC",
                                                PPersonTable.GetTableName(), AReadTransaction, ParametersArray, 0, 0);

            // Add Persons to Table
            for (Int32 Counter = 0; Counter <= FamilyPersonsDT.Rows.Count - 1; Counter += 1)
            {
                NewRow                  = FamilyMembersDT.NewRowTyped(false);
                NewRow.PartnerKey       = FamilyPersonsDT[Counter].PartnerKey;
                NewRow.PartnerShortName =
                    Calculations.DeterminePartnerShortName(TSaveConvert.StringColumnToString(FamilyPersonsDT.ColumnFamilyName,
                                                                                             FamilyPersonsDT[Counter]), TSaveConvert.StringColumnToString(FamilyPersonsDT.ColumnTitle,
                                                                                                                                                          FamilyPersonsDT[Counter]), TSaveConvert.StringColumnToString(FamilyPersonsDT.ColumnFirstName,
                                                                                                                                                                                                                       FamilyPersonsDT[Counter]),
                                                           TSaveConvert.StringColumnToString(FamilyPersonsDT.ColumnMiddleName1, FamilyPersonsDT[Counter]));
                NewRow.FamilyId = FamilyPersonsDT[Counter].FamilyId;

                FamilyMembersDT.Rows.Add(NewRow);
            }

            return(FamilyMembersDT);
        }
Exemplo n.º 4
0
        public static bool SaveSiteKeys(List <Int64> ASiteKeysSetUpForUse, List <Int64> ASiteKeysToRemove)
        {
            TDBTransaction      Transaction        = new TDBTransaction();
            bool                SubmissionOK       = true;
            PPartnerLedgerTable PartnerLedgerTable = new PPartnerLedgerTable();
            PPartnerLedgerRow   PartnerLedgerRow;

            // save site keys that can be used in p_partner_ledger

            DBAccess.WriteTransaction(
                ref Transaction, ref SubmissionOK,
                delegate
            {
                // create new records in p_partner_ledger if not there yet
                foreach (Int64 SiteKey in ASiteKeysSetUpForUse)
                {
                    if (PPartnerLedgerAccess.CountViaPUnit(SiteKey, Transaction) == 0)
                    {
                        PartnerLedgerRow            = PartnerLedgerTable.NewRowTyped();
                        PartnerLedgerRow.PartnerKey = SiteKey;

                        // calculate last partner id, from older uses of this ledger number
                        object MaxExistingPartnerKeyObj = Transaction.DataBaseObj.ExecuteScalar(
                            String.Format("SELECT MAX(" + PPartnerTable.GetPartnerKeyDBName() + ") FROM " + PPartnerTable.GetTableDBName() +
                                          " WHERE " + PPartnerTable.GetPartnerKeyDBName() + " > {0} AND " + PPartnerTable.GetPartnerKeyDBName() +
                                          " < {1}",
                                          SiteKey,
                                          SiteKey + 500000), Transaction);

                        if (MaxExistingPartnerKeyObj.GetType() != typeof(DBNull))
                        {
                            // found a partner key for this site already: set it to last used value
                            PartnerLedgerRow.LastPartnerId = Convert.ToInt32(Convert.ToInt64(MaxExistingPartnerKeyObj) - SiteKey);
                        }
                        else
                        {
                            // in this case there was no partner key for this site yet
                            PartnerLedgerRow.LastPartnerId = 0;
                        }

                        PartnerLedgerTable.Rows.Add(PartnerLedgerRow);
                    }
                }

                // delete records from p_partner_ledger that are no longer needed
                foreach (Int64 SiteKey in ASiteKeysToRemove)
                {
                    PPartnerLedgerAccess.DeleteByPrimaryKey(SiteKey, Transaction);
                }

                PPartnerLedgerAccess.SubmitChanges(PartnerLedgerTable, Transaction);
            });

            // make sure SitesList will be refreshed when called next time
            TPartnerCacheableWebConnector.RefreshCacheableTable(TCacheablePartnerTablesEnum.InstalledSitesList);

            return(SubmissionOK);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Create a Partner and a Person having this FamilyKey, living at this address.
        /// </summary>
        /// <param name="AFamilyKey"></param>
        /// <param name="ALocationKey"></param>
        /// <param name="ANode"></param>
        /// <param name="AMainDS"></param>
        /// <param name="ATransaction"></param>
        private static Int64 CreateNewPerson(Int64 AFamilyKey, int ALocationKey, XmlNode ANode,
                                             ref PartnerImportExportTDS AMainDS, TDBTransaction ATransaction)
        {
            AMainDS.PFamily.DefaultView.RowFilter = String.Format("{0}={1}", PFamilyTable.GetPartnerKeyDBName(), AFamilyKey);
            PFamilyRow FamilyRow = (PFamilyRow)AMainDS.PFamily.DefaultView[0].Row;

            AMainDS.PPartner.DefaultView.RowFilter = String.Format("{0}={1}", PPartnerTable.GetPartnerKeyDBName(), AFamilyKey);
            PPartnerRow PartnerRow = (PPartnerRow)AMainDS.PPartner.DefaultView[0].Row;

            PPartnerRow newPartner = AMainDS.PPartner.NewRowTyped();

            AMainDS.PPartner.Rows.Add(newPartner);

            newPartner.PartnerKey        = (AMainDS.PPartner.Rows.Count + 1) * -1;
            newPartner.PartnerClass      = MPartnerConstants.PARTNERCLASS_PERSON;
            newPartner.AddresseeTypeCode = PartnerRow.AddresseeTypeCode;
            newPartner.PartnerShortName  = PartnerRow.PartnerShortName;
            newPartner.LanguageCode      = PartnerRow.LanguageCode;
            newPartner.Comment           = TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_NOTES);
            newPartner.AcquisitionCode   = PartnerRow.AcquisitionCode;
            newPartner.StatusCode        = MPartnerConstants.PARTNERSTATUS_ACTIVE;

            PPersonRow newPerson = AMainDS.PPerson.NewRowTyped();

            AMainDS.PPerson.Rows.Add(newPerson);

            newPerson.PartnerKey = newPartner.PartnerKey;
            newPerson.FamilyKey  = AFamilyKey;
            // When this record is imported, newPerson.FamilyId must be unique for this family!
            newPerson.FirstName     = FamilyRow.FirstName;
            newPerson.FamilyName    = FamilyRow.FamilyName;
            newPerson.Title         = FamilyRow.Title;
            newPerson.Gender        = GetGenderCode(ANode);
            newPerson.MaritalStatus = FamilyRow.MaritalStatus;

            PPartnerLocationRow newPartnerLocation = AMainDS.PPartnerLocation.NewRowTyped();

            AMainDS.PPartnerLocation.Rows.Add(newPartnerLocation);

            newPartnerLocation.LocationKey   = ALocationKey; // This person lives at the same address as the family.
            newPartnerLocation.SiteKey       = 0;
            newPartnerLocation.PartnerKey    = newPartner.PartnerKey;
            newPartnerLocation.DateEffective = DateTime.Now.Date;
            newPartnerLocation.LocationType  = MPartnerConstants.LOCATIONTYPE_HOME;
            newPartnerLocation.SendMail      = true;

            newPartnerLocation["p_email_address_c"] =
                TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_EMAIL);        // Important: Do not use 'newPartnerLocation.EmailAddress' as this Column will get removed once Contact Details conversion is finished!
            newPartnerLocation["p_telephone_number_c"] =
                TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_PHONE);        // Important: Do not use 'newPartnerLocation.TelephoneNumber' as this Column will get removed once Contact Details conversion is finished!
            newPartnerLocation["p_mobile_number_c"] =
                TXMLParser.GetAttribute(ANode, MPartnerConstants.PARTNERIMPORT_MOBILEPHONE);  // Important: Do not use 'newPartnerLocation.MobileNumber' as this Column will get removed once Contact Details conversion is finished!

            AddVerificationResult("Person Record Created.", TResultSeverity.Resv_Status);

            return(newPerson.PartnerKey);
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
        /// <summary>
        /// get the number and name of the registration offices that the current user has access for
        /// </summary>
        /// <returns></returns>
        public static PPartnerTable GetRegistrationOffices()
        {
            bool           NewTransaction;
            TDataBase      db          = DBAccess.Connect("GetRegistrationOffices");
            TDBTransaction Transaction = db.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out NewTransaction);

            PPartnerTable result = new PPartnerTable();

            try
            {
                List <Int64> offices = GetRegistrationOfficeKeysOfUser(Transaction);

                StringCollection FieldList = new StringCollection();
                FieldList.Add(PPartnerTable.GetPartnerKeyDBName());
                FieldList.Add(PPartnerTable.GetPartnerShortNameDBName());

                // get the short names of the registration offices
                foreach (Int64 OfficeKey in offices)
                {
                    PPartnerTable partnerTable = PPartnerAccess.LoadByPrimaryKey(OfficeKey, FieldList, Transaction);

                    result.Merge(partnerTable);
                }

                // remove unwanted columns
                List <string> ColumnNames = new List <string>();

                foreach (DataColumn column in result.Columns)
                {
                    ColumnNames.Add(column.ColumnName);
                }

                foreach (string columnName in ColumnNames)
                {
                    if (!FieldList.Contains(columnName))
                    {
                        result.Columns.Remove(columnName.ToString());
                    }
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    Transaction.Rollback();
                }
            }

            result.DefaultView.Sort = PPartnerTable.GetPartnerKeyDBName();

            return(result);
        }
Exemplo n.º 8
0
        private DataTable GetConferenceListTable(TDBTransaction AReadTransaction, string ATableName)
        {
            DataTable Table;

            DataColumn[] Key = new DataColumn[1];

            // Used eg. Select Event Dialog
            Table = DBAccess.GetDBAccessObj(AReadTransaction).SelectDT(
                "SELECT DISTINCT " +
                PPartnerTable.GetPartnerShortNameDBName() +
                ", " + PPartnerTable.GetPartnerClassDBName() +
                ", " + PUnitTable.GetOutreachCodeDBName() +
                ", " + PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryNameDBName() +
                ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateEffectiveDBName() +
                ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateGoodUntilDBName() +
                ", " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() +
                ", " + PUnitTable.GetUnitTypeCodeDBName() +

                " FROM PUB." + PPartnerTable.GetTableDBName() +
                ", PUB." + PUnitTable.GetTableDBName() +
                ", PUB." + PLocationTable.GetTableDBName() +
                ", PUB." + PPartnerLocationTable.GetTableDBName() +
                ", PUB." + PCountryTable.GetTableDBName() +

                " WHERE " +
                PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() + " AND " +
                PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetPartnerKeyDBName() + " AND " +

                PLocationTable.GetTableDBName() + "." + PLocationTable.GetSiteKeyDBName() + " = " +
                PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetSiteKeyDBName() + " AND " +
                PLocationTable.GetTableDBName() + "." + PLocationTable.GetLocationKeyDBName() + " = " +
                PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetLocationKeyDBName() + " AND " +
                PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryCodeDBName() + " = " +
                PLocationTable.GetTableDBName() + "." + PLocationTable.GetCountryCodeDBName() + " AND " +


                PPartnerTable.GetStatusCodeDBName() + " = 'ACTIVE' AND " +
                PPartnerTable.GetPartnerClassDBName() + " = 'UNIT' AND (" +
                PUnitTable.GetUnitTypeCodeDBName() + " LIKE '%CONF%' OR " +
                PUnitTable.GetUnitTypeCodeDBName() + " LIKE '%CONG%')"
                ,
                ATableName, AReadTransaction);

            Key[0]           = Table.Columns[PPartnerTable.GetPartnerKeyDBName()];
            Table.PrimaryKey = Key;

            return(Table);
        }
Exemplo n.º 9
0
        /// <summary>
        /// This Procedure will get called when the event filter criteria are changed
        /// </summary>
        /// <param name="sender">The Object that throws this Event</param>
        /// <param name="e">Event Arguments.
        /// </param>
        /// <returns>void</returns>
        private void EventFilterChanged(System.Object sender, System.EventArgs e)
        {
            DataView view = new DataView(FOutreachUnitsTable);

            view.AllowNew  = false;
            view.RowFilter = ucoFilter.GetFilterCriteria();

            clbEvent.DataBindGrid(
                view.ToTable(), PPartnerTable.GetPartnerShortNameDBName() + " DESC", "CHECKED",
                PPartnerTable.GetPartnerKeyDBName(), false, true, false);
            clbEvent.SetCheckedStringList("");

            clbEvent.AutoStretchColumnsToFitWidth = true;
            clbEvent.AutoResizeGrid();
        }
Exemplo n.º 10
0
 /// <summary>
 /// Loads all available Ledgers and their names into a DataTable
 ///
 /// </summary>
 /// <returns>void</returns>
 public static DataTable GetData(String ATableName, TDBTransaction AReadTransaction)
 {
     return(DBAccess.GDBAccessObj.SelectDT(
                String.Format(
                    "SELECT {0} AS LedgerNumber, {1} AS LedgerName FROM pub_{2}, pub_{3} " +
                    "WHERE pub_{2}.{4} = pub_{3}.{4} " + "AND   pub_{2}.{5} = 1",
                    ALedgerTable.GetLedgerNumberDBName(),
                    PPartnerTable.GetPartnerShortNameDBName(),
                    ALedgerTable.GetTableDBName(),
                    PPartnerTable.GetTableDBName(),
                    PPartnerTable.GetPartnerKeyDBName(),
                    ALedgerTable.GetLedgerStatusDBName()),
                ATableName,
                AReadTransaction));
 }
Exemplo n.º 11
0
        /// <summary>
        /// Retrieves the ShortName of a Partner.
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of the Partner.</param>
        /// <param name="ATransaction">Database transaction to use.</param>
        /// <returns>ShortName of the specified Partner.</returns>
        private static string GetPartnerShortName(long APartnerKey, TDBTransaction ATransaction)
        {
            // Can't use TPartnerServerLookups from here:
            // TPartnerServerLookups.GetPartnerShortName(APartnerKey, out ShortName, out PartnerClass);

            PPartnerTable PartnerTable;
            var           Columns = new StringCollection();

            Columns.Add(PPartnerTable.GetPartnerKeyDBName());
            Columns.Add(PPartnerTable.GetPartnerShortNameDBName());

            PartnerTable = PPartnerAccess.LoadByPrimaryKey(APartnerKey, Columns, ATransaction);

            return(PartnerTable[0].PartnerShortName);
        }
Exemplo n.º 12
0
        private void AcceptSelection(System.Object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;

            if (grdEvent.SelectedDataRows.Length == 1)
            {
                this.DialogResult = DialogResult.OK;

                FSelectedUnitName     = (((DataRowView)grdEvent.SelectedDataRows[0]).Row[PPartnerTable.GetPartnerShortNameDBName()]).ToString();
                FSelectedOutreachCode = (((DataRowView)grdEvent.SelectedDataRows[0]).Row[PUnitTable.GetOutreachCodeDBName()]).ToString();
                String PartnerKey = ((DataRowView)grdEvent.SelectedDataRows[0]).Row[PPartnerTable.GetPartnerKeyDBName()].ToString();
                FSelectedPartnerKey = Convert.ToInt64(PartnerKey);
            }

            this.Close();
        }
        /// <summary>
        /// todoComment
        /// </summary>
        /// <returns></returns>
        public Int64 DetermineCurrentPartnerKey()
        {
            DataRow CurrentDR = this.CurrentDataRow;

            if (CurrentDR != null)
            {
                // get PartnerKey of current DataRow
                FPartnerKey = Convert.ToInt64(CurrentDR[PPartnerTable.GetPartnerKeyDBName()]);
            }
            else
            {
                FPartnerKey = -1;
            }

            // MessageBox.Show(FPartnerKey.ToString);
            return(FPartnerKey);
        }
Exemplo n.º 14
0
        public static PUnitTable GetActiveFieldUnits()
        {
            PUnitTable UnitTable = new PUnitTable();
            PUnitRow   UnitRow;

            TLogging.LogAtLevel(9, "TPartnerDataReaderWebConnector.GetActiveFieldUnits called!");

            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                           ref Transaction,
                                                           delegate
            {
                // Load data
                string SqlStmt = "SELECT pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() +
                                 ", pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetUnitNameDBName() +
                                 " FROM " + PUnitTable.GetTableDBName() + ", " + PPartnerTable.GetTableDBName() +
                                 " WHERE ((" + PUnitTable.GetOutreachCodeDBName() + " IS NULL)" +
                                 "        OR(" + PUnitTable.GetOutreachCodeDBName() + " = ''))" +
                                 " AND " + PUnitTable.GetUnitTypeCodeDBName() + " <> 'KEY-MIN'" +
                                 " AND pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() +
                                 " = pub_" + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() +
                                 " AND " + PPartnerTable.GetStatusCodeDBName() + " = 'ACTIVE'";

                // sort rows according to name
                SqlStmt = SqlStmt + " ORDER BY " + PUnitTable.GetUnitNameDBName();

                DataTable events = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "fields", Transaction);

                foreach (DataRow eventRow in events.Rows)
                {
                    UnitRow            = (PUnitRow)UnitTable.NewRow();
                    UnitRow.PartnerKey = Convert.ToInt64(eventRow[0]);
                    UnitRow.UnitName   = Convert.ToString(eventRow[1]);
                    UnitTable.Rows.Add(UnitRow);
                }
            });

            return(UnitTable);
        }
        private void LoadEventListData()
        {
            string CheckedMember   = "CHECKED";
            string ValueMember     = PPartnerTable.GetPartnerKeyDBName();
            string DisplayMember   = PPartnerTable.GetPartnerShortNameDBName();
            string EventCodeMember = PUnitTable.GetOutreachCodeDBName();

            FOutreachUnitsTable = TRemote.MPartner.Partner.WebConnectors.GetEventUnits();
            FOutreachUnitsTable.Columns.Add(new DataColumn("CHECKED", typeof(bool)));

            clbEvent.Columns.Clear();
            clbEvent.AddCheckBoxColumn("", FOutreachUnitsTable.Columns[CheckedMember], 17, false);
            clbEvent.AddTextColumn(Catalog.GetString("Event Name"), FOutreachUnitsTable.Columns[DisplayMember]);
            clbEvent.AddPartnerKeyColumn(Catalog.GetString("Partner Key"), FOutreachUnitsTable.Columns[ValueMember]);

            // outreach/event code column only needed in case of displaying Outreaches
            if (ucoFilter.IncludeOutreachUnits)
            {
                clbEvent.AddTextColumn(Catalog.GetString("Event Code"), FOutreachUnitsTable.Columns[EventCodeMember]);
            }

            EventFilterChanged(this, null);
        }
Exemplo n.º 16
0
        private static void ParsePartners(ref PartnerImportExportTDS AMainDS,
                                          XmlNode ACurNode,
                                          TDBTransaction ATransaction,
                                          ref TVerificationResultCollection AVerificationResult)
        {
            XmlNode LocalNode = ACurNode;

            while (LocalNode != null)
            {
                if (LocalNode.Name.StartsWith("PartnerGroup"))
                {
                    ParsePartners(ref AMainDS, LocalNode.FirstChild, ATransaction, ref AVerificationResult);
                }
                else if (LocalNode.Name.StartsWith("Partner"))
                {
                    PPartnerRow PartnerRow        = AMainDS.PPartner.NewRowTyped();
                    Boolean     IsExistingPartner = false;

                    if (!TYml2Xml.HasAttributeRecursive(LocalNode, "SiteKey"))
                    {
                        throw new Exception(Catalog.GetString("Missing SiteKey Attribute"));
                    }

                    if (!TYml2Xml.HasAttributeRecursive(LocalNode, "status"))
                    {
                        throw new Exception(Catalog.GetString("Missing status Attribute"));
                    }

                    // get a new partner key
                    if (TYml2Xml.HasAttribute(LocalNode, "PartnerKey"))
                    {
                        PartnerRow.PartnerKey = Convert.ToInt64(TYml2Xml.GetAttribute(LocalNode, "PartnerKey"));

                        if (PPartnerAccess.Exists(PartnerRow.PartnerKey, ATransaction))
                        {
                            AMainDS.Merge(PPartnerAccess.LoadByPrimaryKey(PartnerRow.PartnerKey, ATransaction));

                            AMainDS.PPartner.DefaultView.RowFilter = String.Format("{0} = '{1}'",
                                                                                   PPartnerTable.GetPartnerKeyDBName(),
                                                                                   PartnerRow.PartnerKey);
                            PartnerRow        = (PPartnerRow)AMainDS.PPartner.DefaultView[0].Row;
                            IsExistingPartner = true;
                        }
                        else
                        {
                            AMainDS.PPartner.Rows.Add(PartnerRow);
                        }
                    }
                    else
                    {
                        PartnerRow.PartnerKey = TImportExportYml.NewPartnerKey;
                        TImportExportYml.NewPartnerKey--;
                    }

                    String PartnerClass = TYml2Xml.GetAttributeRecursive(LocalNode, "class");
                    TLogging.LogAtLevel(TLogging.DEBUGLEVEL_TRACE,
                                        PartnerClass + " " +
                                        LocalNode.Name + " " +
                                        "PartnerKey=" + PartnerRow.PartnerKey
                                        );

                    if (IsExistingPartner && (PartnerClass != PartnerRow.PartnerClass))
                    {
                        throw new Exception(String.Format("Error: Yml contains Existing Partner {0} with a different partner class {1}!",
                                                          PartnerRow.PartnerKey, PartnerClass));
                    }

                    PartnerRow.PartnerClass = PartnerClass;

                    if (PartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY)
                    {
                        PFamilyRow FamilyRow;

                        if (IsExistingPartner)
                        {
                            AMainDS.Merge(PFamilyAccess.LoadByPrimaryKey(PartnerRow.PartnerKey, ATransaction));

                            AMainDS.PFamily.DefaultView.RowFilter = String.Format("{0} = '{1}'",
                                                                                  PFamilyTable.GetPartnerKeyDBName(),
                                                                                  PartnerRow.PartnerKey);
                            FamilyRow = (PFamilyRow)AMainDS.PFamily.DefaultView[0].Row;
                        }
                        else
                        {
                            FamilyRow               = AMainDS.PFamily.NewRowTyped();
                            FamilyRow.PartnerKey    = PartnerRow.PartnerKey;
                            PartnerRow.PartnerClass = MPartnerConstants.PARTNERCLASS_FAMILY;
                            AMainDS.PFamily.Rows.Add(FamilyRow);
                        }

                        FamilyRow.FamilyName = TYml2Xml.GetAttributeRecursive(LocalNode, "LastName");
                        FamilyRow.FirstName  = TYml2Xml.GetAttribute(LocalNode, "FirstName");
                        FamilyRow.Title      = TYml2Xml.GetAttribute(LocalNode, "Title");

                        if (TYml2Xml.HasAttribute(LocalNode, "CreatedAt"))
                        {
                            FamilyRow.DateCreated = Convert.ToDateTime(TYml2Xml.GetAttribute(LocalNode, "CreatedAt"));
                        }

                        PartnerRow.AddresseeTypeCode = MPartnerConstants.PARTNERCLASS_FAMILY;

                        PartnerRow.PartnerShortName =
                            Calculations.DeterminePartnerShortName(FamilyRow.FamilyName, FamilyRow.Title, FamilyRow.FirstName);
                    }

                    if (PartnerClass == MPartnerConstants.PARTNERCLASS_PERSON)
                    {
                        PPersonRow PersonRow;

                        if (IsExistingPartner)
                        {
                            AMainDS.Merge(PPersonAccess.LoadByPrimaryKey(PartnerRow.PartnerKey, ATransaction));

                            AMainDS.PPerson.DefaultView.RowFilter = String.Format("{0} = '{1}'",
                                                                                  PPersonTable.GetPartnerKeyDBName(),
                                                                                  PartnerRow.PartnerKey);
                            PersonRow = (PPersonRow)AMainDS.PPerson.DefaultView[0].Row;
                        }
                        else
                        {
                            PersonRow            = AMainDS.PPerson.NewRowTyped();
                            PersonRow.PartnerKey = PartnerRow.PartnerKey;
                            AMainDS.PPerson.Rows.Add(PersonRow);
                        }

                        PersonRow.FamilyName = TYml2Xml.GetAttributeRecursive(LocalNode, "LastName");
                        PersonRow.FirstName  = TYml2Xml.GetAttribute(LocalNode, "FirstName");
                        PersonRow.Title      = TYml2Xml.GetAttribute(LocalNode, "Title");

                        if (TYml2Xml.HasAttribute(LocalNode, "CreatedAt"))
                        {
                            PersonRow.DateCreated = Convert.ToDateTime(TYml2Xml.GetAttribute(LocalNode, "CreatedAt"));
                        }

                        // PersonRow.Sp
                        PartnerRow.PartnerShortName =
                            Calculations.DeterminePartnerShortName(PersonRow.FamilyName, PersonRow.Title, PersonRow.FirstName);
                    }
                    else if (PartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION)
                    {
                        POrganisationRow OrganisationRow;

                        if (IsExistingPartner)
                        {
                            AMainDS.Merge(POrganisationAccess.LoadByPrimaryKey(PartnerRow.PartnerKey, ATransaction));

                            AMainDS.POrganisation.DefaultView.RowFilter = String.Format("{0} = '{1}'",
                                                                                        POrganisationTable.GetPartnerKeyDBName(),
                                                                                        PartnerRow.PartnerKey);
                            OrganisationRow = (POrganisationRow)AMainDS.POrganisation.DefaultView[0].Row;
                        }
                        else
                        {
                            OrganisationRow            = AMainDS.POrganisation.NewRowTyped();
                            OrganisationRow.PartnerKey = PartnerRow.PartnerKey;
                            AMainDS.POrganisation.Rows.Add(OrganisationRow);
                        }

                        OrganisationRow.OrganisationName = TYml2Xml.GetAttributeRecursive(LocalNode, "Name");

                        PartnerRow.PartnerShortName = OrganisationRow.OrganisationName;
                    }
                    else if (PartnerClass == MPartnerConstants.PARTNERCLASS_UNIT)
                    {
                        PUnitRow UnitRow;

                        if (IsExistingPartner)
                        {
                            AMainDS.Merge(PUnitAccess.LoadByPrimaryKey(PartnerRow.PartnerKey, ATransaction));

                            AMainDS.PUnit.DefaultView.RowFilter = String.Format("{0} = '{1}'",
                                                                                PUnitTable.GetPartnerKeyDBName(),
                                                                                PartnerRow.PartnerKey);
                            UnitRow = (PUnitRow)AMainDS.PUnit.DefaultView[0].Row;
                        }
                        else
                        {
                            UnitRow            = AMainDS.PUnit.NewRowTyped();
                            UnitRow.PartnerKey = PartnerRow.PartnerKey;
                            AMainDS.PUnit.Rows.Add(UnitRow);
                        }

                        UnitRow.UnitTypeCode = TYml2Xml.GetAttributeRecursive(LocalNode, "UnitTypeCode");
                        UnitRow.UnitName     = TYml2Xml.GetAttributeRecursive(LocalNode, "Name");

                        if (PartnerRow.PartnerKey < -1)
                        {
                            throw new Exception("Invalid Partner Key or No Partner Key - and no proper handling implemented");
                            // from here...

                            /*
                             * AVerificationResult.Add(new TVerificationResult(
                             *  String.Format(Catalog.GetString("Importing Unit {0}"), UnitRow.UnitName),
                             *  Catalog.GetString("You need to provide a partner key for the unit"),
                             *  TResultSeverity.Resv_Critical));
                             */
                            // ...to here: throws Exception in case of a illegal import file?
                            // The above code must have a glitch
                        }

                        if (!TYml2Xml.HasAttribute(LocalNode, "ParentUnitKey"))
                        {
                            throw new Exception(
                                      "The currently being processed unit (PartnerKey " +
                                      PartnerRow.PartnerKey +
                                      ") requires a ParentUnitKey.");
                        }

                        Int64 ParentKey = Convert.ToInt64(TYml2Xml.GetAttributeRecursive(LocalNode, "ParentUnitKey"));
                        UmUnitStructureRow UnitStructureRow = null;

                        if (IsExistingPartner)
                        {
                            AMainDS.Merge(UmUnitStructureAccess.LoadViaPUnitChildUnitKey(PartnerRow.PartnerKey, ATransaction));

                            AMainDS.UmUnitStructure.DefaultView.RowFilter = String.Format("{0} = '{1}'",
                                                                                          UmUnitStructureTable.GetChildUnitKeyDBName(),
                                                                                          PartnerRow.PartnerKey);

                            if (AMainDS.UmUnitStructure.DefaultView.Count > 0)
                            {
                                UnitStructureRow = (UmUnitStructureRow)AMainDS.UmUnitStructure.DefaultView[0].Row;
                            }
                        }

                        if (UnitStructureRow == null)
                        {
                            UnitStructureRow = AMainDS.UmUnitStructure.NewRowTyped();
                            UnitStructureRow.ParentUnitKey = ParentKey;
                            UnitStructureRow.ChildUnitKey  = PartnerRow.PartnerKey;
                            AMainDS.UmUnitStructure.Rows.Add(UnitStructureRow);
                        }
                        else
                        {
                            UnitStructureRow.ParentUnitKey = ParentKey;
                            UnitStructureRow.ChildUnitKey  = PartnerRow.PartnerKey;
                        }

                        PartnerRow.PartnerShortName = UnitRow.UnitName;
                    }
                    else if (PartnerClass == MPartnerConstants.PARTNERCLASS_BANK)
                    {
                        PBankRow BankRow;

                        if (IsExistingPartner)
                        {
                            AMainDS.Merge(PBankAccess.LoadByPrimaryKey(PartnerRow.PartnerKey, ATransaction));

                            AMainDS.PBank.DefaultView.RowFilter = String.Format("{0} = '{1}'",
                                                                                PBankTable.GetPartnerKeyDBName(),
                                                                                PartnerRow.PartnerKey);
                            BankRow = (PBankRow)AMainDS.PBank.DefaultView[0].Row;
                        }
                        else
                        {
                            BankRow            = AMainDS.PBank.NewRowTyped();
                            BankRow.PartnerKey = PartnerRow.PartnerKey;
                            AMainDS.PBank.Rows.Add(BankRow);
                        }

                        BankRow.BranchName   = TYml2Xml.GetAttribute(LocalNode, "BranchName");
                        BankRow.BranchCode   = TYml2Xml.GetAttribute(LocalNode, "BranchCode");
                        BankRow.Bic          = TYml2Xml.GetAttribute(LocalNode, "BranchBic");
                        BankRow.EpFormatFile = TYml2Xml.GetAttribute(LocalNode, "EpFormatFile");

                        if (TYml2Xml.HasAttribute(LocalNode, "CreatedAt"))
                        {
                            BankRow.DateCreated = Convert.ToDateTime(TYml2Xml.GetAttribute(LocalNode, "CreatedAt"));
                        }
                    }
                    else
                    {
                        /*
                         * throw new Exception(
                         *  "Unknown Partner Class" +
                         *  TYml2Xml.GetAttributeRecursive(LocalNode, "class"));
                         */
                        // TODO AVerificationResult add failing problem: unknown partner class
                    }

                    PartnerRow.StatusCode = TYml2Xml.GetAttributeRecursive(LocalNode, "status");

                    // import special types
                    StringCollection SpecialTypes = StringHelper.StrSplit(TYml2Xml.GetAttributeRecursive(LocalNode, "SpecialTypes"), ",");

                    if (IsExistingPartner)
                    {
                        PPartnerTypeAccess.LoadViaPPartner(AMainDS, PartnerRow.PartnerKey, ATransaction);
                    }

                    foreach (string SpecialType in SpecialTypes)
                    {
                        PPartnerTypeRow PartnerTypeRow = null;
                        AMainDS.PPartnerType.DefaultView.RowFilter = String.Format("{0}={1} AND {2}='{3}'",
                                                                                   PPartnerTypeTable.GetPartnerKeyDBName(),
                                                                                   PartnerRow.PartnerKey,
                                                                                   PPartnerTypeTable.GetTypeCodeDBName(),
                                                                                   SpecialType
                                                                                   );

                        if (AMainDS.PPartnerType.DefaultView.Count > 0)
                        {
                            PartnerTypeRow = (PPartnerTypeRow)AMainDS.PPartnerType.DefaultView[0].Row;
                        }
                        else
                        {
                            PartnerTypeRow            = AMainDS.PPartnerType.NewRowTyped();
                            PartnerTypeRow.PartnerKey = PartnerRow.PartnerKey;
                            PartnerTypeRow.TypeCode   = SpecialType.Trim();
                            AMainDS.PPartnerType.Rows.Add(PartnerTypeRow);
                        }

                        // Check Partner type exists, or create it
                        bool TypeIsKnown = PTypeAccess.Exists(PartnerTypeRow.TypeCode, ATransaction);

                        if (!TypeIsKnown)
                        {
                            Int32 RowIdx = AMainDS.PType.DefaultView.Find(PartnerTypeRow.TypeCode); // I might have created it a second ago..

                            if (RowIdx < 0)
                            {
                                PTypeRow TypeRow = AMainDS.PType.NewRowTyped();
                                TypeRow.TypeCode        = PartnerTypeRow.TypeCode;
                                TypeRow.TypeDescription = "Created from YAML import";
                                AMainDS.PType.Rows.Add(TypeRow);
                            }
                        }
                    }

                    // import subscriptions
                    StringCollection Subscriptions = StringHelper.StrSplit(TYml2Xml.GetAttributeRecursive(LocalNode, "Subscriptions"), ",");

                    foreach (string publicationCode in Subscriptions)
                    {
                        PSubscriptionRow subscription = AMainDS.PSubscription.NewRowTyped();
                        subscription.PartnerKey          = PartnerRow.PartnerKey;
                        subscription.PublicationCode     = publicationCode.Trim();
                        subscription.ReasonSubsGivenCode = "FREE";
                        AMainDS.PSubscription.Rows.Add(subscription);
                    }

                    // import address
                    XmlNode addressNode = TYml2Xml.GetChild(LocalNode, "Address");

                    if ((addressNode == null) || (TYml2Xml.GetAttributeRecursive(addressNode, "Street").Length == 0))
                    {
                        if (!IsExistingPartner)
                        {
                            // add the empty location
                            PPartnerLocationRow partnerlocation = AMainDS.PPartnerLocation.NewRowTyped(true);
                            partnerlocation.SiteKey         = 0;
                            partnerlocation.PartnerKey      = PartnerRow.PartnerKey;
                            partnerlocation.DateEffective   = DateTime.Now;
                            partnerlocation.LocationType    = "HOME";
                            partnerlocation.SendMail        = false;
                            partnerlocation.EmailAddress    = TYml2Xml.GetAttributeRecursive(addressNode, "Email");
                            partnerlocation.TelephoneNumber = TYml2Xml.GetAttributeRecursive(addressNode, "Phone");
                            partnerlocation.MobileNumber    = TYml2Xml.GetAttributeRecursive(addressNode, "MobilePhone");
                            AMainDS.PPartnerLocation.Rows.Add(partnerlocation);
                        }
                    }
                    else
                    {
                        PLocationRow location = AMainDS.PLocation.NewRowTyped(true);
                        location.LocationKey = (AMainDS.PLocation.Rows.Count + 1) * -1;
                        location.SiteKey     = 0;

                        if (!TYml2Xml.HasAttributeRecursive(LocalNode, "Country"))
                        {
                            throw new Exception(Catalog.GetString("Missing Country Attribute"));
                        }

                        location.CountryCode = TYml2Xml.GetAttributeRecursive(addressNode, "Country");
                        location.StreetName  = TYml2Xml.GetAttributeRecursive(addressNode, "Street");
                        location.City        = TYml2Xml.GetAttributeRecursive(addressNode, "City");
                        location.PostalCode  = TYml2Xml.GetAttributeRecursive(addressNode, "PostCode");
                        AMainDS.PLocation.Rows.Add(location);

                        PPartnerLocationRow partnerlocation = AMainDS.PPartnerLocation.NewRowTyped(true);
                        partnerlocation.SiteKey         = 0;
                        partnerlocation.LocationKey     = location.LocationKey;
                        partnerlocation.PartnerKey      = PartnerRow.PartnerKey;
                        partnerlocation.SendMail        = true;
                        partnerlocation.DateEffective   = DateTime.Now;
                        partnerlocation.LocationType    = "HOME";
                        partnerlocation.EmailAddress    = TYml2Xml.GetAttributeRecursive(addressNode, "Email");
                        partnerlocation.TelephoneNumber = TYml2Xml.GetAttributeRecursive(addressNode, "Phone");
                        partnerlocation.MobileNumber    = TYml2Xml.GetAttributeRecursive(addressNode, "MobilePhone");
                        AMainDS.PPartnerLocation.Rows.Add(partnerlocation);
                    }

                    // import finance details (bank account number)
                    XmlNode financialDetailsNode = TYml2Xml.GetChild(LocalNode, "FinancialDetails");

                    ParseFinancialDetails(AMainDS, financialDetailsNode, PartnerRow.PartnerKey, ATransaction);
                }

                LocalNode = LocalNode.NextSibling;
            }
        }
Exemplo n.º 17
0
        public static DataTable GetEventUnits()
        {
            List <OdbcParameter> SqlParameterList = new List <OdbcParameter>();

            DataColumn[] Key    = new DataColumn[3];
            DataTable    Events = new DataTable();

            if (TLogging.DL >= 9)
            {
                Console.WriteLine("GetEventUnits called!");
            }

            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                           ref Transaction,
                                                           delegate
            {
                string SqlStmt =
                    "SELECT DISTINCT " +
                    PPartnerTable.GetPartnerShortNameDBName() +
                    ", " + PPartnerTable.GetPartnerClassDBName() +
                    ", " + PUnitTable.GetOutreachCodeDBName() +
                    ", " + PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryNameDBName() +
                    ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetSiteKeyDBName() +
                    ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetLocationKeyDBName() +
                    ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateEffectiveDBName() +
                    ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateGoodUntilDBName() +

                    ", " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() +
                    ", " + PUnitTable.GetUnitTypeCodeDBName() +
                    ", " + PUnitTable.GetUnitNameDBName() +

                    " FROM pub_" + PPartnerTable.GetTableDBName() +
                    ", pub_" + PUnitTable.GetTableDBName() +
                    ", pub_" + PLocationTable.GetTableDBName() +
                    ", pub_" + PPartnerLocationTable.GetTableDBName() +
                    ", pub_" + PCountryTable.GetTableDBName() +

                    " WHERE " +
                    PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                    PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() + " AND " +

                    PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                    PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetPartnerKeyDBName() + " AND " +
                    PLocationTable.GetTableDBName() + "." + PLocationTable.GetSiteKeyDBName() + " = " +
                    PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetSiteKeyDBName() + " AND " +
                    PLocationTable.GetTableDBName() + "." + PLocationTable.GetLocationKeyDBName() + " = " +
                    PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetLocationKeyDBName() + " AND " +
                    PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryCodeDBName() + " = " +
                    PLocationTable.GetTableDBName() + "." + PLocationTable.GetCountryCodeDBName() + " AND " +

                    PPartnerTable.GetStatusCodeDBName() + " = 'ACTIVE' " + " AND " +
                    PPartnerTable.GetPartnerClassDBName() + " = 'UNIT' ";

                // sort rows according to name
                SqlStmt = SqlStmt + " ORDER BY " + PPartnerTable.GetPartnerShortNameDBName();

                Events = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "events",
                                                        Transaction, SqlParameterList.ToArray());

                Key[0]            = Events.Columns[PPartnerTable.GetPartnerKeyDBName()];
                Key[1]            = Events.Columns[PPartnerLocationTable.GetSiteKeyDBName()];
                Key[2]            = Events.Columns[PPartnerLocationTable.GetLocationKeyDBName()];
                Events.PrimaryKey = Key;
            });

            return(Events);
        }
        /// <summary>
        /// First loads the extractTable needed. Goes throught all the Partners in the extract,  If the partner already has the subscription, returns all those partners back to client.  If the partner doesn't have the subscription, saves this
        /// subscription to those partners.
        /// </summary>
        /// <returns>void</returns>
        private void SubmitChangesInternal()
        {
            TDBTransaction       SubmitChangesTransaction = null;
            TSubmitChangesResult SubmissionResult         = TSubmitChangesResult.scrNothingToBeSaved;
            MExtractTable        ExtractDT;
            PSubscriptionTable   SubscriptionTable;

            PPartnerTable    PartnerTable;
            Int32            RowCounter;
            Int32            PartnersInExtract;
            StringCollection RequiredColumns;
            StringCollection RequiredColumns2;

            if (FInspectDT != null)
            {
                // Initialisations
                FVerificationResult = new TVerificationResultCollection();
                ExtractDT           = new MExtractTable();
                SubscriptionTable   = new PSubscriptionTable();
                FSubmissionDT       = SubscriptionTable.Clone();
                ((TTypedDataTable)FSubmissionDT).InitVars();
                PartnerTable    = new PPartnerTable();
                RequiredColumns = new StringCollection();
                RequiredColumns.Add(MExtractTable.GetPartnerKeyDBName());
                RequiredColumns2 = new StringCollection();
                RequiredColumns2.Add(PPartnerTable.GetPartnerKeyDBName());
                RequiredColumns2.Add(PPartnerTable.GetPartnerShortNameDBName());
                RowCounter = 0;

                // Set up asynchronous execution
                TProgressTracker.SetCurrentState(FProgressID, "Checking Partners' Subscriptions...", 0.0m);


                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction,
                                                           ref SubmissionResult,
                                                           delegate
                {
                    try
                    {
                        //                  TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: loading Subscriptions for ExtractID " + FExtractID.ToString() + "...");
                        ExtractDT         = MExtractAccess.LoadViaMExtractMaster(FExtractID, RequiredColumns, SubmitChangesTransaction);
                        PartnersInExtract = ExtractDT.Rows.Count;
                        //                  TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: ExtractID has " + PartnersInExtract.ToString() + " Partners.");

                        // Go throught all the Partners in the extract
                        foreach (MExtractRow ExtractRow in ExtractDT.Rows)
                        {
                            RowCounter = RowCounter + 1;

                            // Calculate how much Partners we have checked. Let all Partners be a maximum of 70%.
                            TProgressTracker.SetCurrentState(
                                FProgressID,
                                string.Empty,
                                Convert.ToInt16((((double)RowCounter / (double)PartnersInExtract) * 100) * (MAX_PERCENTAGE_CHECKS / 100.0)));
                            TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: loadbyPrimaryKey");

                            SubscriptionTable = PSubscriptionAccess.LoadByPrimaryKey(
                                FInspectDT[0].PublicationCode,
                                ExtractRow.PartnerKey,
                                SubmitChangesTransaction);

                            // if the Partner does not yet have the subscription, add the subscription to this partner.
                            if (SubscriptionTable.Rows.Count == 0)
                            {
                                TLogging.LogAtLevel(
                                    7,
                                    "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: will add Subscription to Partner with PartnerKey "
                                    +
                                    ExtractRow.PartnerKey.ToString());
                                FInspectDT[0].PartnerKey = ExtractRow.PartnerKey;
                                TLogging.LogAtLevel(7,
                                                    "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: importing Row into FSubmissionDT...");
                                FSubmissionDT.ImportRow(FInspectDT[0]);
                            }
                            else
                            {
                                // The partner already has this Subscription: add the partner to the ResponseTable
                                //                          TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: won't add Subscription to Partner with PartnerKey " + ExtractRow.PartnerKey.ToString());
                                PartnerTable = PPartnerAccess.LoadByPrimaryKey(ExtractRow.PartnerKey, RequiredColumns2, SubmitChangesTransaction);

                                if (FResponseDT == null)
                                {
                                    FResponseDT = PartnerTable.Clone();
                                }

                                FResponseDT.ImportRow(PartnerTable[0]);
                            }
                        }

                        TLogging.LogAtLevel(7,
                                            "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Finished checking Partner's Subscriptions.");

                        if (FSubmissionDT.Rows.Count > 0)
                        {
                            // Submit the Partners with new Subscriptions to the PSubscription Table.
                            TProgressTracker.SetCurrentState(
                                FProgressID,
                                "Adding Subscriptions to " + FSubmissionDT.Rows.Count.ToString() + " Partners...",
                                MAX_PERCENTAGE_CHECKS);
                            //                      TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: " + FAsyncExecProgress.ProgressInformation);

                            PSubscriptionAccess.SubmitChanges((PSubscriptionTable)FSubmissionDT, SubmitChangesTransaction);
                        }
                        else
                        {
                            TLogging.LogAtLevel(
                                7,
                                "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: no Subscriptions were added to Partners because all the Partners in the Extract already had this Subscription.");
                        }

                        SubmissionResult = TSubmitChangesResult.scrOK;
                    }
                    catch (Exception Exp)
                    {
                        TLogging.LogAtLevel(7,
                                            "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Exception occured, Transaction will get ROLLED BACK. Exception: "
                                            +
                                            Exp.ToString());

                        SubmissionResult = TSubmitChangesResult.scrError;
                        FSubmitResult    = SubmissionResult;
                        FSubmitException = Exp;
                        TProgressTracker.CancelJob(FProgressID);

                        return;
                    }
                });
            }

            // if no values at response table, it needs to be created. If not creates, will raise exeption at client side.
            if (FResponseDT == null)
            {
                FResponseDT = new DataTable();
            }

            TProgressTracker.FinishJob(FProgressID);
            FSubmitResult = SubmissionResult;
        }
        public static PUnitTable GetActiveFieldUnits(string AFieldName)
        {
            PUnitTable UnitTable = new PUnitTable();
            PUnitRow   UnitRow;

            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

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

            TLogging.LogAtLevel(9, "TPartnerDataReaderWebConnector.GetActiveFieldUnits called!");

            ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                                                TEnforceIsolationLevel.eilMinimum,
                                                                                out NewTransaction);

            try
            {
                // Load data
                string SqlStmt = "SELECT pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() +
                                 ", pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetUnitNameDBName() +
                                 " FROM " + PUnitTable.GetTableDBName() + ", " + PPartnerTable.GetTableDBName() +
                                 " WHERE ((" + PUnitTable.GetOutreachCodeDBName() + " IS NULL)" +
                                 "        OR(" + PUnitTable.GetOutreachCodeDBName() + " = ''))" +
                                 " AND " + PUnitTable.GetUnitTypeCodeDBName() + " <> 'KEY-MIN'" +
                                 " AND pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() +
                                 " = pub_" + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() +
                                 " AND " + PPartnerTable.GetStatusCodeDBName() + " = 'ACTIVE'";

                if (AFieldName.Length > 0)
                {
                    // in case there is a filter set for the event name
                    AFieldName = AFieldName.Replace('*', '%') + "%";
                    SqlStmt    = SqlStmt + " AND " + PUnitTable.GetUnitNameDBName() +
                                 " LIKE '" + AFieldName + "'";
                }

                // sort rows according to name
                SqlStmt = SqlStmt + " ORDER BY " + PUnitTable.GetUnitNameDBName();

                DataTable events = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "fields", ReadTransaction);

                foreach (DataRow eventRow in events.Rows)
                {
                    UnitRow            = (PUnitRow)UnitTable.NewRow();
                    UnitRow.PartnerKey = Convert.ToInt64(eventRow[0]);
                    UnitRow.UnitName   = Convert.ToString(eventRow[1]);
                    UnitTable.Rows.Add(UnitRow);
                }
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "TPartnerDataReaderWebConnector.GetActiveFieldUnits: committed own transaction.");
                }
            }

            return(UnitTable);
        }
        public static DataTable GetEventUnits(bool AIncludeConferenceUnits, bool AIncludeOutreachUnits,
                                              string AEventName, bool AIncludeLocationData, bool ACurrentAndFutureEventsOnly)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;

            List <OdbcParameter> SqlParameterList = new List <OdbcParameter>();

            DataColumn[] Key    = new DataColumn[1];
            DataTable    Events = new DataTable();

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

            if (TLogging.DL >= 9)
            {
                Console.WriteLine("GetEventUnits called!");
            }

            ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                                                                                TEnforceIsolationLevel.eilMinimum,
                                                                                out NewTransaction);

            try
            {
                string SqlStmt =
                    "SELECT DISTINCT " +
                    PPartnerTable.GetPartnerShortNameDBName() +
                    ", " + PPartnerTable.GetPartnerClassDBName() +
                    ", " + PUnitTable.GetOutreachCodeDBName();

                if (AIncludeLocationData || ACurrentAndFutureEventsOnly)
                {
                    SqlStmt = SqlStmt +
                              ", " + PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryNameDBName() +
                              ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateEffectiveDBName() +
                              ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateGoodUntilDBName();
                }

                SqlStmt = SqlStmt +
                          ", " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() +
                          ", " + PUnitTable.GetUnitTypeCodeDBName() +

                          " FROM pub_" + PPartnerTable.GetTableDBName() +
                          ", pub_" + PUnitTable.GetTableDBName();

                if (AIncludeLocationData || ACurrentAndFutureEventsOnly)
                {
                    SqlStmt = SqlStmt +
                              ", pub_" + PLocationTable.GetTableDBName() +
                              ", pub_" + PPartnerLocationTable.GetTableDBName() +
                              ", pub_" + PCountryTable.GetTableDBName();
                }

                SqlStmt = SqlStmt +
                          " WHERE " +
                          PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                          PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() + " AND ";

                if (AIncludeLocationData || ACurrentAndFutureEventsOnly)
                {
                    SqlStmt = SqlStmt +
                              PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                              PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetPartnerKeyDBName() + " AND " +
                              PLocationTable.GetTableDBName() + "." + PLocationTable.GetSiteKeyDBName() + " = " +
                              PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetSiteKeyDBName() + " AND " +
                              PLocationTable.GetTableDBName() + "." + PLocationTable.GetLocationKeyDBName() + " = " +
                              PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetLocationKeyDBName() + " AND " +
                              PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryCodeDBName() + " = " +
                              PLocationTable.GetTableDBName() + "." + PLocationTable.GetCountryCodeDBName() + " AND ";
                }

                SqlStmt = SqlStmt +
                          PPartnerTable.GetStatusCodeDBName() + " = 'ACTIVE' " + " AND " +
                          PPartnerTable.GetPartnerClassDBName() + " = 'UNIT' ";

                // add criteria for conference and/or outreach
                String ConferenceWhereClause = "(" +
                                               PUnitTable.GetUnitTypeCodeDBName() + " LIKE '%CONF%' OR " +
                                               PUnitTable.GetUnitTypeCodeDBName() + " LIKE '%CONG%')";

                String OutreachWhereClause = PUnitTable.GetOutreachCodeDBName() + " IS NOT NULL AND " +
                                             PUnitTable.GetOutreachCodeDBName() + " <> '' AND (" +
                                             PUnitTable.GetUnitTypeCodeDBName() + " NOT LIKE '%CONF%' AND " +
                                             PUnitTable.GetUnitTypeCodeDBName() + " NOT LIKE '%CONG%')";

                if (AIncludeConferenceUnits &&
                    AIncludeOutreachUnits)
                {
                    SqlStmt = SqlStmt + " AND ((" + ConferenceWhereClause + ") OR (" + OutreachWhereClause + "))";
                }
                else if (AIncludeConferenceUnits)
                {
                    SqlStmt = SqlStmt + " AND (" + ConferenceWhereClause + ")";
                }
                else if (AIncludeOutreachUnits)
                {
                    SqlStmt = SqlStmt + " AND (" + OutreachWhereClause + ")";
                }

                // add criteria for event name filter
                if (AEventName.Length > 0)
                {
                    // in case there is a filter set for the event name
                    AEventName = AEventName.Replace('*', '%') + "%";
                    SqlStmt    = SqlStmt + " AND " + PUnitTable.GetUnitNameDBName() +
                                 " LIKE '" + AEventName + "'";
                }

                if (ACurrentAndFutureEventsOnly)
                {
                    SqlStmt = SqlStmt + " AND " + PPartnerLocationTable.GetDateGoodUntilDBName() + " >= ?";

                    SqlParameterList.Add(new OdbcParameter("param_date", OdbcType.Date)
                    {
                        Value = DateTime.Today.Date
                    });
                }

                // sort rows according to name
                SqlStmt = SqlStmt + " ORDER BY " + PPartnerTable.GetPartnerShortNameDBName();

                Events = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "events",
                                                        ReadTransaction, SqlParameterList.ToArray());

                Key[0]            = Events.Columns[PPartnerTable.GetPartnerKeyDBName()];
                Events.PrimaryKey = Key;
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();

                    if (TLogging.DL >= 7)
                    {
                        Console.WriteLine("GetEventUnits: committed own transaction.");
                    }
                }
            }

            return(Events);
        }
Exemplo n.º 21
0
        /// <summary>
        /// This report considers gifts given between the two specified dates, and can include all gifts or, if
        /// selected, those to a particular motivation, motivation detail or recipient. For the defined set of gifts
        /// and its total value, the donors are sorted into a list, starting with those who gave most, and showing
        /// the percentage that their gifts contributed to the total received (for this motivation or recipient, if
        /// specified) and the cumulative percentage, moving down the list starting with the top donor.
        /// </summary>
        /// <param name="ATotalAmount">Pre calculated value of the total gifts given with these parameters</param>
        /// <param name="ATopXPercent">Upper limit of the percentage to show in the report</param>
        /// <param name="ABottomXPercent">Lower limit of the percentage to show in the report</param>
        /// <param name="AExtract">true to use only partners from an extract</param>
        /// <param name="AExtractName">extract name</param>
        /// <param name="AStartDate">Start date of the gifts given</param>
        /// <param name="AEndDate">End date of the gifts given</param>
        /// <param name="ARecipientKey">Partner key of a specific recipient. If 0 then use all recipients</param>
        /// <param name="AMotivationGroup">Limit gifts to this motivation group. If % use all motivation groups</param>
        /// <param name="AMotivationDetail">Limit gifts to this motivation detail. If % use all motivation details</param>
        /// <returns></returns>
        private bool MakeTopDonor(decimal ATotalAmount, decimal ATopXPercent, decimal ABottomXPercent,
                                  bool AExtract, String AExtractName, DateTime AStartDate, DateTime AEndDate,
                                  Int64 ARecipientKey, String AMotivationGroup, String AMotivationDetail)
        {
            Int64         LedgerNumber = situation.GetParameters().Get("param_ledger_number_i").ToInt64();
            String        CurrencyType = situation.GetParameters().Get("param_currency").ToString();
            StringBuilder SqlString    = new StringBuilder();

            SqlString.Append("SELECT DISTINCT ");
            SqlString.Append("gift.p_donor_key_n AS DonorKey, ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerShortNameDBName() + " AS ShortName, ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerClassDBName() + " AS PartnerClass, ");

            if (CurrencyType == "Base")
            {
                SqlString.Append("SUM(detail." + AGiftDetailTable.GetGiftAmountDBName() + ") AS Amount ");
            }
            else
            {
                SqlString.Append("SUM(detail." + AGiftDetailTable.GetGiftAmountIntlDBName() + ") AS Amount ");
            }

            SqlString.Append(
                " FROM " + AGiftTable.GetTableDBName() + " as gift, " + AGiftDetailTable.GetTableDBName() + " as detail, " +
                PPartnerTable.GetTableDBName() + ", " + AGiftBatchTable.GetTableDBName() + " ");

            if (AExtract)
            {
                SqlString.Append(", " + MExtractTable.GetTableDBName() + ", " + MExtractMasterTable.GetTableDBName());
                SqlString.Append(
                    " WHERE gift." + AGiftTable.GetDonorKeyDBName() + " = " + MExtractTable.GetTableDBName() + "." +
                    MExtractTable.GetPartnerKeyDBName());
                SqlString.Append(
                    " AND " + MExtractTable.GetTableDBName() + "." + MExtractTable.GetExtractIdDBName() + " = " +
                    MExtractMasterTable.GetTableDBName() +
                    "." + MExtractMasterTable.GetExtractIdDBName());
                SqlString.Append(" AND " + MExtractMasterTable.GetTableDBName() + "." + MExtractMasterTable.GetExtractNameDBName() + " = '");
                SqlString.Append(AExtractName);
                SqlString.Append("' AND ");
            }
            else
            {
                SqlString.Append(" WHERE ");
            }

            SqlString.Append(" detail." + AGiftDetailTable.GetLedgerNumberDBName() + " = gift." + AGiftTable.GetLedgerNumberDBName());
            SqlString.Append(" AND detail." + AGiftDetailTable.GetBatchNumberDBName() + " = gift." + AGiftTable.GetBatchNumberDBName());
            SqlString.Append(
                " AND detail." + AGiftDetailTable.GetGiftTransactionNumberDBName() + " = gift." + AGiftTable.GetGiftTransactionNumberDBName());
            SqlString.Append(" AND gift." + AGiftTable.GetDateEnteredDBName() + " BETWEEN '");
            SqlString.Append(AStartDate.ToString("yyyy-MM-dd"));
            SqlString.Append("' AND '");
            SqlString.Append(AEndDate.ToString("yyyy-MM-dd"));
            SqlString.Append("' AND gift." + AGiftTable.GetLedgerNumberDBName() + " = ");
            SqlString.Append(LedgerNumber.ToString());
            SqlString.Append(" AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetLedgerNumberDBName() + " = ");
            SqlString.Append(LedgerNumber.ToString());
            SqlString.Append(
                " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchNumberDBName() + " = gift." +
                AGiftTable.GetBatchNumberDBName());
            SqlString.Append(" AND ( " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'Posted' OR ");
            SqlString.Append(AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'posted' ) ");
            SqlString.Append(
                " AND " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = gift." + AGiftTable.GetDonorKeyDBName());

            if (ARecipientKey != 0)
            {
                SqlString.Append(" AND detail." + AGiftDetailTable.GetRecipientKeyDBName() + " = ");
                SqlString.Append(ARecipientKey.ToString());
            }

            if (AMotivationGroup != "%")
            {
                SqlString.Append(" AND  detail." + AGiftDetailTable.GetMotivationGroupCodeDBName() + " LIKE '");
                SqlString.Append(AMotivationGroup);
                SqlString.Append("' ");
            }

            if (AMotivationDetail != "%")
            {
                SqlString.Append(" AND  detail." + AGiftDetailTable.GetMotivationDetailCodeDBName() + " LIKE '");
                SqlString.Append(AMotivationDetail);
                SqlString.Append("' ");
            }

            SqlString.Append(" GROUP BY gift." + AGiftTable.GetDonorKeyDBName() + ", ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerShortNameDBName() + ", ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerClassDBName());
            SqlString.Append(" ORDER BY Amount DESC");

            DataTable Table = situation.GetDatabaseConnection().SelectDT(SqlString.ToString(), "table",
                                                                         situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            decimal CummulativeAmount = 0;
            decimal TopAmount         = ATotalAmount * ATopXPercent / 100;
            decimal BottomAmount      = ATotalAmount * ABottomXPercent / 100;

            int NumColumns = 7;
            int ChildRow   = 1;

            situation.GetResults().Clear();

            for (int Counter = 0; Counter < Table.Rows.Count; ++Counter)
            {
                decimal CurrentAmount = Convert.ToDecimal(Table.Rows[Counter]["Amount"]);

                if (CurrentAmount < 0)
                {
                    continue;
                }

                if ((CummulativeAmount <= TopAmount) &&
                    (CummulativeAmount >= BottomAmount))
                {
                    Int64  DonorKey     = Convert.ToInt64(Table.Rows[Counter]["DonorKey"]);
                    String ShortName    = (String)Table.Rows[Counter]["ShortName"];
                    String PartnerClass = (String)Table.Rows[Counter]["PartnerClass"];

                    CummulativeAmount += CurrentAmount;

                    // Transfer to results
                    TVariant[] Header      = new TVariant[NumColumns];
                    TVariant[] Description =
                    {
                        new TVariant(), new TVariant()
                    };
                    TVariant[] Columns = new TVariant[NumColumns];

                    for (int Counter2 = 0; Counter2 < NumColumns; ++Counter2)
                    {
                        Header[Counter2]  = new TVariant();
                        Columns[Counter2] = new TVariant();
                    }

                    StringBuilder       PartnerAddress = new StringBuilder();
                    PPartnerLocationRow AddressRow;

                    if (Ict.Petra.Server.MReporting.MPartner.TRptUserFunctionsPartner.GetPartnerBestAddressRow(DonorKey, situation, out AddressRow))
                    {
                        PLocationTable LocationTable = PLocationAccess.LoadByPrimaryKey(AddressRow.SiteKey,
                                                                                        AddressRow.LocationKey, situation.GetDatabaseConnection().Transaction);

                        if (LocationTable.Rows.Count > 0)
                        {
                            PLocationRow LocationRow = (PLocationRow)LocationTable.Rows[0];

                            PartnerAddress.Append(LocationRow.Locality);

                            if (LocationRow.Locality.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.StreetName);

                            if (PartnerAddress.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.Address3);

                            if (PartnerAddress.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.PostalCode);
                            PartnerAddress.Append(" ");
                            PartnerAddress.Append(LocationRow.City);

                            if (LocationRow.County.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                                PartnerAddress.Append(LocationRow.County);
                            }

                            PartnerAddress.Append(", ");
                            PartnerAddress.Append(LocationRow.CountryCode);
                        }
                    }

                    Columns[0] = new TVariant(DonorKey.ToString("0000000000"));
                    Columns[1] = new TVariant(PartnerClass);
                    Columns[2] = new TVariant(ShortName);
                    Columns[3] = new TVariant(CurrentAmount, "-#,##0.00;#,##0.00");
                    Columns[4] = new TVariant((CurrentAmount * 100 / ATotalAmount), "-#,##0.00;#,##0.00");
                    Columns[5] = new TVariant((CummulativeAmount * 100 / ATotalAmount), "-#,##0.00;#,##0.00");
                    Columns[6] = new TVariant(PartnerAddress.ToString());

                    situation.GetResults().AddRow(0, ChildRow++, true, 2, "", "", false,
                                                  Header, Description, Columns);
                }
                else
                {
                    CummulativeAmount += CurrentAmount;
                }
            }

            return(true);
        }
Exemplo n.º 22
0
        /// <summary>
        /// export all posted invoices of other suppliers in this year
        /// </summary>
        public static void Export(string AOutputPath,
                                  char ACSVSeparator,
                                  string ANewLine,
                                  Int32 ALedgerNumber,
                                  Int32 AFinancialYear,
                                  string ACostCentres)
        {
            string filename = Path.GetFullPath(Path.Combine(AOutputPath, "accountspayable.csv"));

            Console.WriteLine("Writing file: " + filename);

            StringBuilder sb = new StringBuilder();

            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            // get all posted or paid ap_documents by their date issued
            string sql =
                String.Format(
                    "SELECT * FROM PUB_{0} " +
                    "WHERE {1} = {2} AND " +
                    "({3} = '{4}' OR {3} = '{5}' OR {3} = '{6}') AND " +
                    "{7} >= ? AND {7} <= ?",
                    AApDocumentTable.GetTableDBName(),
                    AApDocumentTable.GetLedgerNumberDBName(),
                    ALedgerNumber,
                    AApDocumentTable.GetDocumentStatusDBName(),
                    MFinanceConstants.AP_DOCUMENT_POSTED,
                    MFinanceConstants.AP_DOCUMENT_PARTIALLY_PAID,
                    MFinanceConstants.AP_DOCUMENT_PAID,
                    AApDocumentTable.GetDateIssuedDBName());

            List <OdbcParameter> Parameters = new List <OdbcParameter>();
            OdbcParameter        param      = new OdbcParameter("startdate", OdbcType.DateTime);

            param.Value = TAccountingPeriodsWebConnector.GetPeriodStartDate(ALedgerNumber, AFinancialYear, 0, 1);
            Parameters.Add(param);
            param       = new OdbcParameter("enddate", OdbcType.DateTime);
            param.Value = TAccountingPeriodsWebConnector.GetPeriodEndDate(ALedgerNumber, AFinancialYear, 0, 12);
            Parameters.Add(param);

            AApDocumentTable apDocuments = new AApDocumentTable();

            DBAccess.GDBAccessObj.SelectDT(apDocuments, sql, Transaction, Parameters.ToArray(), 0, 0);

            // get all ap details
            sql =
                String.Format(
                    "SELECT Detail.* FROM PUB_{0} AS Doc, PUB_{8} AS Detail " +
                    "WHERE Doc.{1} = {2} AND " +
                    "({3} = '{4}' OR {3} = '{5}' OR {3} = '{6}') AND " +
                    "{7} >= ? AND {7} <= ? AND " +
                    "Detail.{1} = Doc.{1} AND Detail.{9} = Doc.{9} AND " +
                    "Detail.{10} IN ({11})",
                    AApDocumentTable.GetTableDBName(),
                    AApDocumentTable.GetLedgerNumberDBName(),
                    ALedgerNumber,
                    AApDocumentTable.GetDocumentStatusDBName(),
                    MFinanceConstants.AP_DOCUMENT_POSTED,
                    MFinanceConstants.AP_DOCUMENT_PARTIALLY_PAID,
                    MFinanceConstants.AP_DOCUMENT_PAID,
                    AApDocumentTable.GetDateIssuedDBName(),
                    AApDocumentDetailTable.GetTableDBName(),
                    AApDocumentTable.GetApDocumentIdDBName(),
                    AApDocumentDetailTable.GetCostCentreCodeDBName(),
                    "'" + ACostCentres.Replace(",", "','") + "'");

            AApDocumentDetailTable apDetails = new AApDocumentDetailTable();

            DBAccess.GDBAccessObj.SelectDT(apDetails, sql, Transaction, Parameters.ToArray(), 0, 0);

            apDetails.DefaultView.Sort = AApDocumentDetailTable.GetApDocumentIdDBName();

            // get all ap payments
            sql =
                String.Format(
                    "SELECT DP.{0}, DP.{1}, P.{2} AS {3}, DP.{7}, DP.{15} FROM PUB_{4} AS Doc, PUB_{5} AS DP, PUB_{6} AS P " +
                    "WHERE Doc.{7} = {8} AND " +
                    "({9} = '{10}' OR {9} = '{11}' OR {9} = '{12}') AND " +
                    "{13} >= ? AND {13} <= ? AND " +
                    "DP.{7} = Doc.{7} AND DP.{14} = Doc.{14} AND " +
                    "P.{7} = Doc.{7} AND P.{15} = DP.{15}",

                    AApDocumentPaymentTable.GetApDocumentIdDBName(),
                    AApDocumentPaymentTable.GetAmountDBName(),
                    AApPaymentTable.GetPaymentDateDBName(),
                    AApDocumentPaymentTable.GetDateCreatedDBName(),
                    AApDocumentTable.GetTableDBName(),
                    AApDocumentPaymentTable.GetTableDBName(),
                    AApPaymentTable.GetTableDBName(),

                    AApDocumentTable.GetLedgerNumberDBName(),
                    ALedgerNumber,
                    AApDocumentTable.GetDocumentStatusDBName(),
                    MFinanceConstants.AP_DOCUMENT_POSTED,
                    MFinanceConstants.AP_DOCUMENT_PARTIALLY_PAID,
                    MFinanceConstants.AP_DOCUMENT_PAID,
                    AApDocumentTable.GetDateIssuedDBName(),

                    AApDocumentTable.GetApDocumentIdDBName(),
                    AApPaymentTable.GetPaymentNumberDBName());

            AApDocumentPaymentTable apPayments = new AApDocumentPaymentTable();

            DBAccess.GDBAccessObj.SelectDT(apPayments, sql, Transaction, Parameters.ToArray(), 0, 0);

            apPayments.DefaultView.Sort = AApDocumentPaymentTable.GetApDocumentIdDBName();

            // get the analysis attributes for the taxes
            sql =
                String.Format(
                    "SELECT Attrib.* FROM PUB_{0} AS Doc, PUB_{8} AS Attrib " +
                    "WHERE Doc.{1} = {2} AND " +
                    "({3} = '{4}' OR {3} = '{5}' OR {3} = '{6}') AND " +
                    "{7} >= ? AND {7} <= ? AND " +
                    "Attrib.{1} = Doc.{1} AND Attrib.{9} = Doc.{9}",
                    AApDocumentTable.GetTableDBName(),
                    AApDocumentTable.GetLedgerNumberDBName(),
                    ALedgerNumber,
                    AApDocumentTable.GetDocumentStatusDBName(),
                    MFinanceConstants.AP_DOCUMENT_POSTED,
                    MFinanceConstants.AP_DOCUMENT_PARTIALLY_PAID,
                    MFinanceConstants.AP_DOCUMENT_PAID,
                    AApDocumentTable.GetDateIssuedDBName(),
                    AApAnalAttribTable.GetTableDBName(),
                    AApDocumentTable.GetApDocumentIdDBName());

            AApAnalAttribTable apAttrib = new AApAnalAttribTable();

            DBAccess.GDBAccessObj.SelectDT(apAttrib, sql, Transaction, Parameters.ToArray(), 0, 0);

            apAttrib.DefaultView.Sort = AApAnalAttribTable.GetApDocumentIdDBName() + "," + AApAnalAttribTable.GetDetailNumberDBName();

            // get the supplier name
            sql =
                String.Format(
                    "SELECT DISTINCT p.* FROM PUB_{0} AS Doc, PUB_{8} AS p " +
                    "WHERE Doc.{1} = {2} AND " +
                    "({3} = '{4}' OR {3} = '{5}' OR {3} = '{6}') AND " +
                    "{7} >= ? AND {7} <= ? AND " +
                    "p.{9} = Doc.{10}",
                    AApDocumentTable.GetTableDBName(),
                    AApDocumentTable.GetLedgerNumberDBName(),
                    ALedgerNumber,
                    AApDocumentTable.GetDocumentStatusDBName(),
                    MFinanceConstants.AP_DOCUMENT_POSTED,
                    MFinanceConstants.AP_DOCUMENT_PARTIALLY_PAID,
                    MFinanceConstants.AP_DOCUMENT_PAID,
                    AApDocumentTable.GetDateIssuedDBName(),
                    PPartnerTable.GetTableDBName(),
                    PPartnerTable.GetPartnerKeyDBName(),
                    AApDocumentTable.GetPartnerKeyDBName());

            PPartnerTable suppliers = new PPartnerTable();

            DBAccess.GDBAccessObj.SelectDT(suppliers, sql, Transaction, Parameters.ToArray(), 0, 0);

            foreach (AApDocumentRow doc in apDocuments.Rows)
            {
                PPartnerRow supplier = (PPartnerRow)suppliers.Rows.Find(doc.PartnerKey);

                DataRowView[] detailsRV = apDetails.DefaultView.FindRows(doc.ApDocumentId);

                foreach (DataRowView rv in detailsRV)
                {
                    AApDocumentDetailRow detail = (AApDocumentDetailRow)rv.Row;

                    if (doc.CreditNoteFlag)
                    {
                        detail.Amount *= -1.0m;
                    }

                    DataRowView[] payments = apPayments.DefaultView.FindRows(doc.ApDocumentId);

                    string DatePaid = string.Empty;

                    if (payments.Length > 1)
                    {
                        DatePaid = "Several Payments: ";

                        foreach (DataRowView rvPayment in payments)
                        {
                            AApDocumentPaymentRow payment = ((AApDocumentPaymentRow)rvPayment.Row);
                            DatePaid += payment.DateCreated.Value.ToString("yyyyMMdd") + " ";
                            DatePaid += payment.PaymentNumber.ToString() + "; ";
                        }

                        // for gdpdu, only write dates to this column
                        DatePaid = string.Empty;
                    }
                    else if (payments.Length == 1)
                    {
                        AApDocumentPaymentRow payment = ((AApDocumentPaymentRow)payments[0].Row);
                        DatePaid = payment.DateCreated.Value.ToString("yyyyMMdd");
                    }

                    sb.Append(StringHelper.StrMerge(
                                  new string[] {
                        doc.ApNumber.ToString(),
                        detail.DetailNumber.ToString(),
                        doc.DateIssued.ToString("yyyyMMdd"),
                        DatePaid,
                        doc.PartnerKey.ToString(),
                        supplier.PartnerShortName,
                        detail.CostCentreCode,
                        detail.AccountCode,
                        String.Format("{0:N}", detail.Amount),
                        detail.Narrative
                    }, ACSVSeparator));
                    sb.Append(ANewLine);
                }
            }

            DBAccess.GDBAccessObj.RollbackTransaction();

            StreamWriter sw = new StreamWriter(filename, false, Encoding.GetEncoding(1252));

            sw.Write(sb.ToString());
            sw.Close();
        }
Exemplo n.º 23
0
        public static ArrayList GetUnitHeirarchy()
        {
            const Int64 THE_ORGANISATION = 1000000;

            ArrayList Ret = new ArrayList();

            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction,
                                                           delegate
            {
                PPartnerTable PartnerTbl         = PPartnerAccess.LoadViaPPartnerClasses("UNIT", Transaction);
                PartnerTbl.DefaultView.RowFilter = "p_status_code_c <> 'MERGED'";
                PartnerTbl.DefaultView.Sort      = PPartnerTable.GetPartnerKeyDBName();

                PUnitTable UnitTbl           = PUnitAccess.LoadAll(Transaction);
                UUnitTypeTable UnitTypeTbl   = UUnitTypeAccess.LoadAll(Transaction);
                UnitTypeTbl.DefaultView.Sort = UUnitTypeTable.GetUnitTypeCodeDBName();

                UmUnitStructureTable HierarchyTbl = UmUnitStructureAccess.LoadAll(Transaction);
                HierarchyTbl.DefaultView.Sort     = UmUnitStructureTable.GetChildUnitKeyDBName();

                UnitTbl.DefaultView.Sort         = PUnitTable.GetPartnerKeyDBName();
                UnitHierarchyNode RootNode       = new UnitHierarchyNode();
                UnitHierarchyNode UnassignedNode = new UnitHierarchyNode();

                RootNode.MyUnitKey     = THE_ORGANISATION;
                RootNode.ParentUnitKey = THE_ORGANISATION;
                RootNode.Description   = "The Organisation";
                RootNode.TypeCode      = "Root";

                Int32 RootUnitIdx = UnitTbl.DefaultView.Find(THE_ORGANISATION);

                if (RootUnitIdx >= 0)
                {
                    RootNode.Description = ((PUnitRow)UnitTbl.DefaultView[RootUnitIdx].Row).UnitName;
                    UnitTbl.DefaultView.Delete(RootUnitIdx);
                }

                Ret.Add(RootNode);

                UnassignedNode.MyUnitKey     = 0;
                UnassignedNode.ParentUnitKey = 0;
                UnassignedNode.Description   = Catalog.GetString("Unassigned Units");
                Ret.Add(UnassignedNode);

                foreach (DataRowView rv in UnitTbl.DefaultView)
                {
                    PUnitRow UnitRow = (PUnitRow)rv.Row;

                    if (PartnerTbl.DefaultView.Find(UnitRow.PartnerKey) < 0)
                    {
                        // skip all merged units
                        continue;
                    }

                    UnitHierarchyNode Node = new UnitHierarchyNode();
                    Node.Description       = UnitRow.UnitName + " " + UnitRow.Description;

                    if (Node.Description == "")
                    {
                        Node.Description = "[" + UnitRow.PartnerKey.ToString("D10") + "]";
                    }

                    Node.MyUnitKey = UnitRow.PartnerKey;

                    //
                    // Retrieve parent..
                    Int32 HierarchyTblIdx = HierarchyTbl.DefaultView.Find(Node.MyUnitKey);

                    if (HierarchyTblIdx >= 0)
                    {
                        Node.ParentUnitKey = ((UmUnitStructureRow)HierarchyTbl.DefaultView[HierarchyTblIdx].Row).ParentUnitKey;
                    }
                    else
                    {
                        Node.ParentUnitKey = UnassignedNode.MyUnitKey;
                    }

                    //
                    // Retrieve TypeCode..
                    Int32 TypeTblIndex = UnitTypeTbl.DefaultView.Find(UnitRow.UnitTypeCode);

                    if (TypeTblIndex >= 0)
                    {
                        Node.TypeCode = ((UUnitTypeRow)UnitTypeTbl.DefaultView[TypeTblIndex].Row).UnitTypeName;
                    }
                    else
                    {
                        Node.TypeCode = "Type: " + UnitRow.UnitTypeCode;
                    }

                    Ret.Add(Node);
                }
            });

            return(Ret);
        }
Exemplo n.º 24
0
        /// <summary>
        /// return an XmlDocument with all partner info;
        /// the partners are grouped by class, country, status, and sitekey
        /// </summary>
        /// <returns></returns>
        public static string ExportPartners()
        {
            PartnerEditTDS MainDS = new PartnerEditTDS();

            LoadDataFromDB(ref MainDS);

            // Group partners into categories.
            //
            // A partner's category is defined by his: class, country, status, and sitekey
            // It is stored as a string e.g. "FAMILY,DE,ACTIVE,0".
            //
            SortedList <string, List <long> > PartnerCategories = GroupPartnersIntoCategories(MainDS);

            // create XML structure for each category
            XmlDocument PartnerData = TYml2Xml.CreateXmlDocument();
            XmlNode     rootNode    = PartnerData.FirstChild.NextSibling;

            Int32 groupCounter = 0;

            foreach (string category in PartnerCategories.Keys)
            {
                // get category data
                groupCounter++;
                XmlElement groupNode = PartnerData.CreateElement("PartnerGroup" + groupCounter.ToString());
                rootNode.AppendChild(groupNode);

                Int32    partnerCounter  = 0;
                string[] categoryDetails = category.Split(new char[] { ',' });
                // may want to skip the categories with sitekey = -1
                // right now, we still export them and ignore the partners 0 and 1000000 later

                groupNode.SetAttribute("class", categoryDetails[0]);
                groupNode.SetAttribute("Country", categoryDetails[1]);
                groupNode.SetAttribute("status", categoryDetails[2]);
                groupNode.SetAttribute("SiteKey", categoryDetails[3]);

                List <long> partnerKeys = PartnerCategories[category];

                foreach (long partnerKey in partnerKeys)
                {
                    if ((partnerKey != 0) && (partnerKey != 1000000)) // skip organization root and the 0 when exporting
                    {
                        MainDS.PPartner.DefaultView.RowFilter = PPartnerTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                        PPartnerRow partnerRow = (PPartnerRow)MainDS.PPartner.DefaultView[0].Row;

                        PFamilyRow familyRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY)
                        {
                            MainDS.PFamily.DefaultView.RowFilter = PFamilyTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            familyRow = (PFamilyRow)MainDS.PFamily.DefaultView[0].Row;
                        }

                        PPersonRow personRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_PERSON)
                        {
                            MainDS.PPerson.DefaultView.RowFilter = PPersonTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            personRow = (PPersonRow)MainDS.PPerson.DefaultView[0].Row;
                        }

                        POrganisationRow organisationRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION)
                        {
                            MainDS.POrganisation.DefaultView.RowFilter = POrganisationTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            organisationRow = (POrganisationRow)MainDS.POrganisation.DefaultView[0].Row;
                        }

                        PUnitRow           unitRow          = null;
                        UmUnitStructureRow unitStructureRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_UNIT)
                        {
                            MainDS.PUnit.DefaultView.RowFilter = PUnitTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            unitRow = (PUnitRow)MainDS.PUnit.DefaultView[0].Row;
                            MainDS.UmUnitStructure.DefaultView.RowFilter = UmUnitStructureTable.GetChildUnitKeyDBName() + " = " + partnerKey.ToString();

                            long numParents = MainDS.UmUnitStructure.DefaultView.Count;

                            if (numParents == 1)
                            {
                                unitStructureRow = (UmUnitStructureRow)MainDS.UmUnitStructure.DefaultView[0].Row;
                            }
                            else
                            {
                                throw new Exception(
                                          "Units must have exactly one ParentUnit. " +
                                          "The unit with partnerKey " + partnerKey.ToString() + " has " +
                                          numParents.ToString() + ".");
                            }
                        }

                        PBankRow BankRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_BANK)
                        {
                            MainDS.PBank.DefaultView.RowFilter = PBankTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            BankRow = (PBankRow)MainDS.PBank.DefaultView[0].Row;
                        }

                        partnerCounter++;
                        XmlElement partnerNode = PartnerData.CreateElement("Partner" + partnerCounter.ToString());
                        groupNode.AppendChild(partnerNode);

                        partnerNode.SetAttribute("PartnerKey", partnerRow.PartnerKey.ToString());

                        //groupNode.SetAttribute("ShortName", partnerRow.PartnerShortName.ToString());

                        if (personRow != null)
                        {
                            partnerNode.SetAttribute("FirstName", personRow.FirstName.ToString());
                            partnerNode.SetAttribute("LastName", personRow.FamilyName.ToString());
                            partnerNode.SetAttribute("Title", personRow.Title.ToString());
                        }
                        else if (familyRow != null)
                        {
                            partnerNode.SetAttribute("FirstName", familyRow.FirstName.ToString());
                            partnerNode.SetAttribute("LastName", familyRow.FamilyName.ToString());
                            partnerNode.SetAttribute("Title", familyRow.Title.ToString());
                        }
                        else if (organisationRow != null)
                        {
                            partnerNode.SetAttribute("Name", organisationRow.OrganisationName.ToString());
                        }
                        else if (unitRow != null)
                        {
                            partnerNode.SetAttribute("Name", unitRow.UnitName.ToString());
                            partnerNode.SetAttribute("UnitTypeCode", unitRow.UnitTypeCode.ToString());

                            if (unitStructureRow != null)
                            {
                                partnerNode.SetAttribute("ParentUnitKey", unitStructureRow.ParentUnitKey.ToString());
                            }
                        }

                        if (BankRow != null)
                        {
                            partnerNode.SetAttribute("BranchName", BankRow.BranchName);
                            partnerNode.SetAttribute("BranchCode", BankRow.BranchCode);
                            partnerNode.SetAttribute("BranchBic", BankRow.Bic);
                            partnerNode.SetAttribute("EpFormatFile", BankRow.EpFormatFile);
                        }

                        partnerNode.SetAttribute("CreatedAt", partnerRow.DateCreated.Value.ToString("yyyy-MM-dd HH:mm:ss"));

                        // special types
                        string specialTypes = "";
                        MainDS.PPartnerType.DefaultView.RowFilter = PPartnerTypeTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();

                        foreach (DataRowView rv in MainDS.PPartnerType.DefaultView)
                        {
                            if (specialTypes.Length > 0)
                            {
                                specialTypes += ", ";
                            }

                            specialTypes += ((PPartnerTypeRow)rv.Row).TypeCode;
                        }

                        if (specialTypes.Length > 0)
                        {
                            partnerNode.SetAttribute("SpecialTypes", specialTypes);
                        }

                        // addresses
                        DataView partnerLocationView = MainDS.PPartnerLocation.DefaultView;
                        partnerLocationView.RowFilter =
                            PPartnerLocationTable.GetPartnerKeyDBName() + " = " + partnerRow.PartnerKey.ToString() +
                            "AND " + PPartnerLocationTable.GetLocationKeyDBName() + " <> 0 "; // ignore invalid addresses
                        Int32 addressCounter = 0;

                        foreach (DataRowView rv in partnerLocationView)
                        {
                            XmlElement addressNode = PartnerData.CreateElement("Address" + (addressCounter > 0 ? addressCounter.ToString() : ""));
                            addressCounter++;
                            partnerNode.AppendChild(addressNode);

                            PPartnerLocationRow partnerLocationRow = (PPartnerLocationRow)rv.Row;

                            DataView locationView = MainDS.PLocation.DefaultView;
                            locationView.RowFilter =
                                PLocationTable.GetSiteKeyDBName() + "=" + partnerLocationRow.SiteKey.ToString() + " AND " +
                                PLocationTable.GetLocationKeyDBName() + "=" + partnerLocationRow.LocationKey.ToString();

                            if (locationView.Count > 0)
                            {
                                PLocationRow locationRow = (PLocationRow)locationView[0].Row;

                                addressNode.SetAttribute("Street", locationRow.StreetName);
                                addressNode.SetAttribute("City", locationRow.City);
                                addressNode.SetAttribute("PostCode", locationRow.PostalCode);
                            }

                            addressNode.SetAttribute("Email", partnerLocationRow.EmailAddress);
                            addressNode.SetAttribute("Phone", partnerLocationRow.TelephoneNumber);
                            addressNode.SetAttribute("MobilePhone", partnerLocationRow.MobileNumber);
                        }

                        // TODO: notes
                        // TODO: This doesn't export as much data as it should?
                    }
                }
            }

            return(TXMLParser.XmlToString(PartnerData));
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
0
        public static DataTable GetAvailableSites()
        {
            TDBTransaction ReadTransaction = new TDBTransaction();

            DataTable SitesTable       = new DataTable();
            DataTable UnusedSitesTable = new DataTable();
            DataTable UsedSitesTable   = new DataTable();
            DataRow   SitesRow;
            string    IsPartnerLedger = SharedConstants.SYSMAN_AVAILABLE_SITES_COLUMN_IS_PARTNER_LEDGER;
            string    SiteKey         = PUnitTable.GetPartnerKeyDBName();
            string    SiteShortName   = PUnitTable.GetUnitNameDBName();
            Int64     PartnerKey;

            SitesTable.Columns.Add(new DataColumn(IsPartnerLedger, typeof(bool)));
            SitesTable.Columns.Add(new DataColumn(SiteKey, typeof(Int64)));
            SitesTable.Columns.Add(new DataColumn(SiteShortName, typeof(string)));

            UnusedSitesTable.Columns.Add(new DataColumn(IsPartnerLedger, typeof(bool)));
            UnusedSitesTable.Columns.Add(new DataColumn(SiteKey, typeof(Int64)));
            UnusedSitesTable.Columns.Add(new DataColumn(SiteShortName, typeof(string)));

            UsedSitesTable.Columns.Add(new DataColumn(IsPartnerLedger, typeof(bool)));
            UsedSitesTable.Columns.Add(new DataColumn(SiteKey, typeof(Int64)));
            UsedSitesTable.Columns.Add(new DataColumn(SiteShortName, typeof(string)));

            DBAccess.ReadTransaction(
                ref ReadTransaction,
                delegate
            {
                try
                {
                    // Load data
                    string SqlStmt = "SELECT pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() +
                                     ", pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetUnitNameDBName() +
                                     " FROM " + PUnitTable.GetTableDBName() + ", " + PPartnerTable.GetTableDBName() +
                                     " WHERE ((" + PUnitTable.GetUnitTypeCodeDBName() + " = 'F')" +
                                     "        OR(" + PUnitTable.GetUnitTypeCodeDBName() + " = 'A'))" +
                                     " AND pub_" + PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() +
                                     " = pub_" + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() +
                                     " AND " + PPartnerTable.GetStatusCodeDBName() + " = 'ACTIVE'";

                    // sort rows according to name
                    SqlStmt = SqlStmt + " ORDER BY " + PUnitTable.GetUnitNameDBName();

                    DataTable sites = ReadTransaction.DataBaseObj.SelectDT(SqlStmt, "fields", ReadTransaction);

                    foreach (DataRow tempSiteRow in sites.Rows)
                    {
                        PartnerKey = Convert.ToInt64(tempSiteRow[0]);

                        // check if a site is already used in table p_partner_ledger
                        if (PPartnerLedgerAccess.CountViaPUnit(PartnerKey, ReadTransaction) > 0)
                        {
                            SitesRow = UsedSitesTable.NewRow();
                            SitesRow[IsPartnerLedger] = true;
                            SitesRow[SiteKey]         = PartnerKey;
                            SitesRow[SiteShortName]   = Convert.ToString(tempSiteRow[1]);
                            UsedSitesTable.Rows.Add(SitesRow);
                        }
                        else
                        {
                            SitesRow = UnusedSitesTable.NewRow();
                            SitesRow[IsPartnerLedger] = false;
                            SitesRow[SiteKey]         = PartnerKey;
                            SitesRow[SiteShortName]   = Convert.ToString(tempSiteRow[1]);
                            UnusedSitesTable.Rows.Add(SitesRow);
                        }
                    }

                    // first add used sites to table
                    foreach (DataRow tempSiteRow in UsedSitesTable.Rows)
                    {
                        SitesRow = SitesTable.NewRow();
                        SitesRow[IsPartnerLedger] = tempSiteRow[IsPartnerLedger];
                        SitesRow[SiteKey]         = tempSiteRow[SiteKey];
                        SitesRow[SiteShortName]   = tempSiteRow[SiteShortName];
                        SitesTable.Rows.Add(SitesRow);
                    }

                    // and now add unused sites to table
                    foreach (DataRow tempSiteRow in UnusedSitesTable.Rows)
                    {
                        SitesRow = SitesTable.NewRow();
                        SitesRow[IsPartnerLedger] = tempSiteRow[IsPartnerLedger];
                        SitesRow[SiteKey]         = tempSiteRow[SiteKey];
                        SitesRow[SiteShortName]   = tempSiteRow[SiteShortName];
                        SitesTable.Rows.Add(SitesRow);
                    }
                }
                catch (Exception e)
                {
                    TLogging.Log(e.ToString());
                }
            });

            return(SitesTable);
        }