コード例 #1
0
        /// <summary>
        /// Verify and if necessary update partner data in an extract
        /// </summary>
        public static void VerifyAndUpdateExtract(System.Windows.Forms.Form AForm, int AExtractId)
        {
            ExtractTDSMExtractTable ExtractTable;
            bool ChangesMade;

            // retrieve contents of extract from server
            ExtractTable = TRemote.MPartner.Partner.WebConnectors.GetExtractRowsWithPartnerData(AExtractId);

            VerifyAndUpdateExtract(AForm, ref ExtractTable, out ChangesMade);

            foreach (DataRow InspectDR in ExtractTable.Rows)
            {
                InspectDR.EndEdit();
            }

            TSubmitChangesResult SubmissionResult;

            MExtractTable SubmitDT = new MExtractTable();

            if (ExtractTable.GetChangesTyped() != null)
            {
                SubmitDT.Merge(ExtractTable.GetChangesTyped());
            }

            if ((SubmitDT.Rows.Count == 0) ||
                !ChangesMade)
            {
                MessageBox.Show(Catalog.GetString("Extract was already up to date"),
                                Catalog.GetString("Verify and Update Extract"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                // return if no changes were made
                return;
            }

            // Submit changes to the PETRAServer
            SubmissionResult = TRemote.MPartner.Partner.WebConnectors.SaveExtract
                                   (AExtractId, ref SubmitDT);

            if (SubmissionResult == TSubmitChangesResult.scrError)
            {
                MessageBox.Show(Catalog.GetString("Verify and Update of Extract failed"),
                                Catalog.GetString("Verify and Update Extract"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show(Catalog.GetString("Verification and Update of Extract was successful"),
                                Catalog.GetString("Verify and Update Extract"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }
コード例 #2
0
        /// <summary>
        /// Verify and if necessary update partner data in an extract
        /// </summary>
        public static void VerifyAndUpdateExtract(System.Windows.Forms.Form AForm, int AExtractId)
        {
            ExtractTDSMExtractTable ExtractTable;
            bool ChangesMade;

            // retrieve contents of extract from server
            ExtractTable = TRemote.MPartner.Partner.WebConnectors.GetExtractRowsWithPartnerData(AExtractId);

            VerifyAndUpdateExtract(AForm, ref ExtractTable, out ChangesMade);

            foreach (DataRow InspectDR in ExtractTable.Rows)
            {
                InspectDR.EndEdit();
            }

            TSubmitChangesResult SubmissionResult;

            MExtractTable SubmitDT = new MExtractTable();

            if (ExtractTable.GetChangesTyped() != null)
            {
                SubmitDT.Merge(ExtractTable.GetChangesTyped());
            }

            if ((SubmitDT.Rows.Count == 0)
                || !ChangesMade)
            {
                MessageBox.Show(Catalog.GetString("Extract was already up to date"),
                    Catalog.GetString("Verify and Update Extract"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                // return if no changes were made
                return;
            }

            // Submit changes to the PETRAServer
            SubmissionResult = TRemote.MPartner.Partner.WebConnectors.SaveExtract
                                   (AExtractId, ref SubmitDT);

            if (SubmissionResult == TSubmitChangesResult.scrError)
            {
                MessageBox.Show(Catalog.GetString("Verify and Update of Extract failed"),
                    Catalog.GetString("Verify and Update Extract"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show(Catalog.GetString("Verification and Update of Extract was successful"),
                    Catalog.GetString("Verify and Update Extract"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
        }
コード例 #3
0
ファイル: Extracts.cs プロジェクト: merbst/openpetra
        /// <summary>
        /// Adds a Partner to an Extract, if they are not already present
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of Partner</param>
        /// <param name="ALocationPK">Location PK of a Partner's PartnerLocation
        /// (usually the LocationPK of the 'Best Address' of the Partner).</param>
        /// <param name="AExtractId">ExtractId of the Extract that the Partner should
        /// get added to.</param>
        /// <returns>True if the Partner was added to the Extract, otherwise false.</returns>
        public static bool AddPartnerToExtract(Int64 APartnerKey,
                                               TLocationPK ALocationPK, int AExtractId)
        {
            TDBTransaction Transaction  = null;
            bool           SubmissionOK = false;
            MExtractTable  TemplateTable;
            MExtractRow    TemplateRow;
            MExtractRow    NewRow;

            if (APartnerKey > 0)
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK,
                                                                      delegate
                {
                    /*
                     * First check whether the Partner isn't already in that Extract
                     */
                    TemplateTable          = new MExtractTable();
                    TemplateRow            = TemplateTable.NewRowTyped(false);
                    TemplateRow.ExtractId  = AExtractId;
                    TemplateRow.PartnerKey = APartnerKey;

                    if (MExtractAccess.CountUsingTemplate(TemplateRow, null, Transaction) == 0)
                    {
                        /*
                         * Add Partner to Extract.
                         */
                        NewRow             = TemplateTable.NewRowTyped(false);
                        NewRow.ExtractId   = AExtractId;
                        NewRow.PartnerKey  = APartnerKey;
                        NewRow.SiteKey     = ALocationPK.SiteKey;
                        NewRow.LocationKey = ALocationPK.LocationKey;
                        TemplateTable.Rows.Add(NewRow);

                        MExtractAccess.SubmitChanges(TemplateTable, Transaction);

                        SubmissionOK = true;
                    }
                    else
                    {
                        // Partner is already in that Extract -> Partner does not get added.
                        SubmissionOK = false;
                    }
                });
            }
            else
            {
                // Invalid PartnerKey -> return false;
                SubmissionOK = false;
            }

            return(SubmissionOK);
        }
コード例 #4
0
ファイル: Extracts.cs プロジェクト: Davincier/openpetra
        /// <summary>
        /// Adds a Partner to an Extract, if they are not already present
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of Partner</param>
        /// <param name="ALocationPK">Location PK of a Partner's PartnerLocation
        /// (usually the LocationPK of the 'Best Address' of the Partner).</param>
        /// <param name="AExtractId">ExtractId of the Extract that the Partner should
        /// get added to.</param>
        /// <returns>True if the Partner was added to the Extract, otherwise false.</returns>
        public static bool AddPartnerToExtract(Int64 APartnerKey,
            TLocationPK ALocationPK, int AExtractId)
        {
            TDBTransaction Transaction = null;
            bool SubmissionOK = false;
            MExtractTable TemplateTable;
            MExtractRow TemplateRow;
            MExtractRow NewRow;

            if (APartnerKey > 0)
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK,
                    delegate
                    {
                        /*
                         * First check whether the Partner isn't already in that Extract
                         */
                        TemplateTable = new MExtractTable();
                        TemplateRow = TemplateTable.NewRowTyped(false);
                        TemplateRow.ExtractId = AExtractId;
                        TemplateRow.PartnerKey = APartnerKey;

                        if (MExtractAccess.CountUsingTemplate(TemplateRow, null, Transaction) == 0)
                        {
                            /*
                             * Add Partner to Extract.
                             */
                            NewRow = TemplateTable.NewRowTyped(false);
                            NewRow.ExtractId = AExtractId;
                            NewRow.PartnerKey = APartnerKey;
                            NewRow.SiteKey = ALocationPK.SiteKey;
                            NewRow.LocationKey = ALocationPK.LocationKey;
                            TemplateTable.Rows.Add(NewRow);

                            MExtractAccess.SubmitChanges(TemplateTable, Transaction);

                            SubmissionOK = true;
                        }
                        else
                        {
                            // Partner is already in that Extract -> Partner does not get added.
                            SubmissionOK = false;
                        }
                    });
            }
            else
            {
                // Invalid PartnerKey -> return false;
                SubmissionOK = false;
            }

            return SubmissionOK;
        }
コード例 #5
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);
        }
コード例 #6
0
ファイル: ImportExport.cs プロジェクト: js1987/openpetragit
        public static String ExportExtractPartnersExt(int AExtractId, Boolean AIncludeFamilyMembers)
        {
            TDBTransaction ReadTransaction = null;
            String ExtText = GetExtFileHeader();
            TPartnerFileExport Exporter = new TPartnerFileExport();
            PartnerImportExportTDS MainDS;
            MExtractTable ExtractPartners = new MExtractTable();

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum,
                ref ReadTransaction,
                delegate
                {
                    ExtractPartners = MExtractAccess.LoadViaMExtractMaster(AExtractId, ReadTransaction);
                });

            foreach (MExtractRow ExtractPartner in ExtractPartners.Rows)
            {
                if (ExtractPartner.PartnerKey != 0)
                {
                    MainDS = TExportAllPartnerData.ExportPartner(ExtractPartner.PartnerKey);
                    ExtText += Exporter.ExportPartnerExt(MainDS, /*ASiteKey*/ 0, /*ALocationKey*/ 0, null);
                }
            }

            ExtText += GetExtFileFooter();
            return ExtText;
        }
コード例 #7
0
ファイル: ImportExport.cs プロジェクト: Davincier/openpetra
        public static String ExportExtractPartnersExt(int AExtractId, Boolean AIncludeFamilyMembers)
        {
            TDBTransaction ReadTransaction = null;
            String ExtText = GetExtFileHeader();
            TPartnerFileExport Exporter = new TPartnerFileExport();
            PartnerImportExportTDS MainDS;
            DataTable ExtractPartners = new MExtractTable();

            ExtractPartners.Columns.Add("p_partner_class_c", typeof(string));

            TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Exporting Extract"));

            string Query = "SELECT m_extract.*, p_partner.p_partner_class_c" +
                           " FROM m_extract, p_partner" +
                           " WHERE m_extract.m_extract_id_i = " + AExtractId +
                           " AND p_partner.p_partner_key_n = m_extract.p_partner_key_n";

            DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted, ref ReadTransaction,
                delegate
                {
                    ExtractPartners = DBAccess.GDBAccessObj.SelectDT(Query, ExtractPartners.TableName, ReadTransaction);
                    int i = 0;
                    int Total = ExtractPartners.Rows.Count;
                    decimal PercentCompleted = 0;

                    foreach (DataRow ExtractPartner in ExtractPartners.Rows)
                    {
                        // stop if user cancels operation
                        if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob)
                        {
                            ExtText = null;
                            break;
                        }

                        if (i > 0)
                        {
                            PercentCompleted = decimal.Divide(i, Total) * 100;
                        }

                        i++;

                        TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                            string.Format(Catalog.GetString("Exporting partner {0} out of {1}."), i, Total),
                            PercentCompleted);

                        // get keys
                        Int64 PartnerKey = (Int64)ExtractPartner[MExtractTable.GetPartnerKeyDBName()];
                        Int64 SiteKey = (Int64)ExtractPartner[MExtractTable.GetSiteKeyDBName()];
                        int LocationKey = 0;

                        if ((ExtractPartner[MExtractTable.GetLocationKeyDBName()] != System.DBNull.Value)
                            && (ExtractPartner[MExtractTable.GetLocationKeyDBName()] != null))
                        {
                            LocationKey = (Int32)ExtractPartner[MExtractTable.GetLocationKeyDBName()];
                        }

                        if (PartnerKey != 0)
                        {
                            // if row is a family partner and the user wants to also export the family's person members
                            if (AIncludeFamilyMembers && (ExtractPartner["p_partner_class_c"].ToString() == MPartnerConstants.PARTNERCLASS_FAMILY))
                            {
                                // export the family partner in the extract
                                MainDS = TExportAllPartnerData.ExportPartner(PartnerKey, TPartnerClass.FAMILY);
                                ExtText += Exporter.ExportPartnerExt(MainDS, SiteKey, LocationKey, null);

                                PPersonTable Persons = PPersonAccess.LoadViaPFamily(PartnerKey, ReadTransaction);

                                foreach (PPersonRow Row in Persons.Rows)
                                {
                                    // do not export if already in extract
                                    if (ExtractPartners.Select(MExtractTable.GetPartnerKeyDBName() + " = " + Row.PartnerKey).Length > 0)
                                    {
                                        continue;
                                    }

                                    MainDS = TExportAllPartnerData.ExportPartner(Row.PartnerKey, TPartnerClass.PERSON);

                                    // if member has same address as family
                                    if (PPartnerLocationAccess.Exists(Row.PartnerKey, SiteKey, LocationKey, ReadTransaction))
                                    {
                                        // export the person member with the same address as family partner
                                        ExtText += Exporter.ExportPartnerExt(MainDS, SiteKey, LocationKey, null);
                                    }
                                    else
                                    {
                                        PLocationTable LocationTable;
                                        string CountryName;

                                        TAddressTools.GetBestAddress(Row.PartnerKey, out LocationTable, out CountryName, ReadTransaction);

                                        if ((LocationTable != null) && (LocationTable.Rows.Count > 0))
                                        {
                                            // export the person member with the person partner's best address
                                            ExtText += Exporter.ExportPartnerExt(MainDS, SiteKey, LocationKey, null);
                                        }
                                    }
                                }
                            }
                            else if (ExtractPartner["p_partner_class_c"].ToString() == MPartnerConstants.PARTNERCLASS_PERSON) // if person partner
                            {
                                PPersonRow PersonRecord = PPersonAccess.LoadByPrimaryKey(PartnerKey, ReadTransaction)[0];

                                // do not export family if already in extract
                                if (ExtractPartners.Select(MExtractTable.GetPartnerKeyDBName() + " = " + PersonRecord.FamilyKey).Length == 0)
                                {
                                    // export the family record first.
                                    MainDS = TExportAllPartnerData.ExportPartner(PersonRecord.FamilyKey, TPartnerClass.FAMILY);

                                    // if family has same address as person member
                                    if (PPartnerLocationAccess.Exists(PersonRecord.FamilyKey, SiteKey, LocationKey, ReadTransaction))
                                    {
                                        // export the family member with the same address as person member
                                        ExtText += Exporter.ExportPartnerExt(MainDS, SiteKey, LocationKey, null);
                                    }
                                    else
                                    {
                                        PLocationTable LocationTable;
                                        string CountryName;

                                        TAddressTools.GetBestAddress(PersonRecord.FamilyKey, out LocationTable, out CountryName, ReadTransaction);

                                        if ((LocationTable != null) && (LocationTable.Rows.Count > 0))
                                        {
                                            // export the family with the family partner's best address
                                            ExtText += Exporter.ExportPartnerExt(MainDS, SiteKey, LocationKey, null);
                                        }
                                    }
                                }

                                // export the person partner in the extract
                                MainDS = TExportAllPartnerData.ExportPartner(PartnerKey, TPartnerClass.PERSON);
                                ExtText += Exporter.ExportPartnerExt(MainDS, SiteKey, LocationKey, null);
                            }
                            else
                            {
                                // export the partner in the extract
                                MainDS =
                                    TExportAllPartnerData.ExportPartner(PartnerKey,
                                        SharedTypes.PartnerClassStringToEnum(ExtractPartner["p_partner_class_c"].ToString()));
                                ExtText += Exporter.ExportPartnerExt(MainDS, SiteKey, LocationKey, null);
                            }
                        }
                    }
                });

            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());

            if (ExtText != null) // if operation has been cancelled
            {
                ExtText += GetExtFileFooter();
            }

            return ExtText;
        }
コード例 #8
0
ファイル: Extracts.cs プロジェクト: jsuen123/openpetragit
        /// <summary>
        /// extend an extract from a list of best addresses
        /// </summary>
        /// <param name="AExtractId">Extract Id of the Extract to extend</param>
        /// <param name="APartnerKeysTable"></param>
        /// <param name="APartnerKeyColumn">number of the column that contains the partner keys</param>
        /// <param name="ASiteKeyColumn">number of the column that contains the site keys</param>
        /// <param name="ALocationKeyColumn">number of the column that contains the location keys</param>
        /// <param name="AIgnoreDuplicates">true if duplicates should be looked out for. Can be set to false if called only once and not several times per extract.</param>
        /// <param name="ACommitTransaction">true if transaction should be committed at end of method</param>
        public static void ExtendExtractFromListOfPartnerKeys(
            Int32 AExtractId,
            DataTable APartnerKeysTable,
            Int32 APartnerKeyColumn,
            Int32 ASiteKeyColumn,
            Int32 ALocationKeyColumn,
            bool AIgnoreDuplicates,
            bool ACommitTransaction)
        {
            Boolean NewTransaction;
            int     RecordCounter = 0;
            PPartnerLocationTable PartnerLocationKeysTable;
            Int64 PartnerKey;

            TDBTransaction WriteTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable,
                                                                                                TEnforceIsolationLevel.eilMinimum, out NewTransaction);

            try
            {
                MExtractTable ExtractTable = new MExtractTable();
                ExtractTable = MExtractAccess.LoadViaMExtractMaster(AExtractId, WriteTransaction);

                // Location Keys need to be determined as extracts do not only need partner keys but
                // also Location Keys.
                DetermineBestLocationKeys(APartnerKeysTable, APartnerKeyColumn, ASiteKeyColumn,
                                          ALocationKeyColumn, out PartnerLocationKeysTable,
                                          WriteTransaction);

                // use the returned table which contains partner and location keys to build the extract
                foreach (PPartnerLocationRow PartnerLocationRow in PartnerLocationKeysTable.Rows)
                {
                    PartnerKey = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetPartnerKeyDBName()]);

                    if (PartnerKey > 0)
                    {
                        RecordCounter += 1;
                        TLogging.Log("Preparing Partner " + PartnerKey.ToString() + " (Record Number " + RecordCounter.ToString() + ")");

                        // add row for partner to extract and fill with contents
                        MExtractRow NewRow = ExtractTable.NewRowTyped();
                        NewRow.ExtractId   = AExtractId;
                        NewRow.PartnerKey  = PartnerKey;
                        NewRow.SiteKey     = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetSiteKeyDBName()]);
                        NewRow.LocationKey = Convert.ToInt32(PartnerLocationRow[PPartnerLocationTable.GetLocationKeyDBName()]);

                        // only add row if it does not already exist for this partner
                        if (AIgnoreDuplicates || !ExtractTable.Rows.Contains(new object[] { NewRow.ExtractId, NewRow.PartnerKey, NewRow.SiteKey }))
                        {
                            ExtractTable.Rows.Add(NewRow);
                        }
                    }
                }

                if (ExtractTable.Rows.Count > 0)
                {
                    // update field in extract master for quick access to number of partners in extract
                    MExtractMasterTable ExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(AExtractId, WriteTransaction);
                    ExtractMaster[0].KeyCount = ExtractTable.Rows.Count;

                    ExtractTable.ThrowAwayAfterSubmitChanges = true; // no need to keep data as this increases speed significantly

                    MExtractAccess.SubmitChanges(ExtractTable, WriteTransaction);

                    MExtractMasterAccess.SubmitChanges(ExtractMaster, WriteTransaction);
                }

                if (ACommitTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured while extending an Extract from a list of Partner Keys:" + Environment.NewLine + Exc.ToString());

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }

                throw;
            }
        }
コード例 #9
0
ファイル: ExtractMaster.cs プロジェクト: Davincier/openpetra
        public static TSubmitChangesResult SaveExtract(int AExtractId, ref MExtractTable AExtractTable)
        {
            int CountExtractRows;
            MExtractMasterTable ExtractMasterDT;
            MExtractTable ExtractTable = AExtractTable;

            if (AExtractTable != null)
            {
                TDBTransaction Transaction = null;
                bool SubmissionOK = false;

                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable,
                    ref Transaction,
                    ref SubmissionOK,
                    delegate
                    {
                        MExtractAccess.SubmitChanges(ExtractTable, Transaction);

                        // update extract master record with the correct number of extract records
                        if (ExtractTable.Rows.Count > 0)
                        {
                            CountExtractRows = MExtractAccess.CountViaMExtractMaster(AExtractId, Transaction);
                            ExtractMasterDT = MExtractMasterAccess.LoadByPrimaryKey(AExtractId, Transaction);

                            if (ExtractMasterDT.Rows.Count != 0)
                            {
                                ((MExtractMasterRow)ExtractMasterDT.Rows[0]).KeyCount = CountExtractRows;

                                MExtractMasterAccess.SubmitChanges(ExtractMasterDT, Transaction);
                            }
                        }

                        SubmissionOK = true;
                    });

                AExtractTable = ExtractTable;
            }

            return TSubmitChangesResult.scrOK;
        }
コード例 #10
0
ファイル: ExtractMaster.cs プロジェクト: js1987/openpetragit
        public static Boolean CombineExtracts(String ANewExtractName,
            String ANewExtractDescription,
            List <Int32>ACombineExtractIdList,
            out Int32 ANewExtractId)
        {
            Boolean ResultValue = true;
            Boolean ExtractAlreadyExists = false;
            MExtractTable ExtractTable;
            MExtractTable CombinedExtractTable = new MExtractTable();
            MExtractRow TemplateRow;
            Boolean NewTransaction;

            TDBTransaction WriteTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable,
                TEnforceIsolationLevel.eilMinimum, out NewTransaction);

            ANewExtractId = -1;

            try
            {
                ResultValue = MPartner.Extracts.TExtractsHandling.CreateNewExtract(ANewExtractName,
                    ANewExtractDescription, out ANewExtractId, out ExtractAlreadyExists);

                if (ResultValue && !ExtractAlreadyExists)
                {
                    // loop through each extract and combine them
                    foreach (Int32 ExtractId in ACombineExtractIdList)
                    {
                        ExtractTable = MExtractAccess.LoadViaMExtractMaster(ExtractId, WriteTransaction);

                        foreach (DataRow ExtractRow in ExtractTable.Rows)
                        {
                            if (CombinedExtractTable.Rows.Find(new object[] { ANewExtractId,
                                                                              ((MExtractRow)ExtractRow).PartnerKey,
                                                                              ((MExtractRow)ExtractRow).SiteKey }) == null)
                            {
                                // create and add row to combined extract as it does not exist yet
                                TemplateRow = (MExtractRow)CombinedExtractTable.NewRowTyped(true);
                                TemplateRow.ExtractId = ANewExtractId;
                                TemplateRow.PartnerKey = ((MExtractRow)ExtractRow).PartnerKey;
                                TemplateRow.SiteKey = ((MExtractRow)ExtractRow).SiteKey;
                                TemplateRow.LocationKey = ((MExtractRow)ExtractRow).LocationKey;

                                CombinedExtractTable.Rows.Add(TemplateRow);
                            }
                        }
                    }

                    // update key count in master table
                    MExtractMasterTable CombinedExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(ANewExtractId, WriteTransaction);
                    CombinedExtractMaster[0].KeyCount = CombinedExtractTable.Rows.Count;

                    // submit changes in master and then in extract content table which refers to it
                    MExtractAccess.SubmitChanges(CombinedExtractTable, WriteTransaction);

                    MExtractMasterAccess.SubmitChanges(CombinedExtractMaster, WriteTransaction);
                }

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the combining of Extracts:" + Environment.NewLine + Exc.ToString());

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }

                throw;
            }

            return ResultValue;
        }
コード例 #11
0
ファイル: Extracts.cs プロジェクト: Kingefosa/openpetra
        /// <summary>
        /// extend an extract from a list of best addresses
        /// </summary>
        /// <param name="AExtractId">Extract Id of the Extract to extend</param>
        /// <param name="APartnerKeysTable"></param>
        /// <param name="APartnerKeyColumn">number of the column that contains the partner keys</param>
        /// <param name="ASiteKeyColumn">number of the column that contains the site keys</param>
        /// <param name="ALocationKeyColumn">number of the column that contains the location keys</param>
        /// <param name="AIgnoreDuplicates">true if duplicates should be looked out for. Can be set to false if called only once and not several times per extract.</param>
        public static void ExtendExtractFromListOfPartnerKeys(
            Int32 AExtractId,
            DataTable APartnerKeysTable,
            Int32 APartnerKeyColumn,
            Int32 ASiteKeyColumn,
            Int32 ALocationKeyColumn,
            bool AIgnoreDuplicates)
        {
            int RecordCounter = 0;
            PPartnerLocationTable PartnerLocationKeysTable;
            Int64 PartnerKey;

            TDBTransaction Transaction  = null;
            bool           SubmissionOK = true;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK,
                                                                  delegate
            {
                MExtractTable ExtractTable = new MExtractTable();
                ExtractTable = MExtractAccess.LoadViaMExtractMaster(AExtractId, Transaction);

                // Location Keys need to be determined as extracts do not only need partner keys but
                // also Location Keys.
                DetermineBestLocationKeys(APartnerKeysTable, APartnerKeyColumn, ASiteKeyColumn,
                                          ALocationKeyColumn, out PartnerLocationKeysTable,
                                          Transaction);

                // use the returned table which contains partner and location keys to build the extract
                foreach (PPartnerLocationRow PartnerLocationRow in PartnerLocationKeysTable.Rows)
                {
                    PartnerKey = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetPartnerKeyDBName()]);

                    if (PartnerKey > 0)
                    {
                        RecordCounter += 1;
                        TLogging.LogAtLevel(1, "Preparing Partner " + PartnerKey + " (Record Number " + RecordCounter + ")");

                        // add row for partner to extract and fill with contents
                        MExtractRow NewRow = ExtractTable.NewRowTyped();
                        NewRow.ExtractId   = AExtractId;
                        NewRow.PartnerKey  = PartnerKey;
                        NewRow.SiteKey     = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetSiteKeyDBName()]);
                        NewRow.LocationKey = Convert.ToInt32(PartnerLocationRow[PPartnerLocationTable.GetLocationKeyDBName()]);

                        // only add row if it does not already exist for this partner
                        if (AIgnoreDuplicates || !ExtractTable.Rows.Contains(new object[] { NewRow.ExtractId, NewRow.PartnerKey, NewRow.SiteKey }))
                        {
                            ExtractTable.Rows.Add(NewRow);
                        }
                    }
                }

                if (ExtractTable.Rows.Count > 0)
                {
                    // update field in extract master for quick access to number of partners in extract
                    MExtractMasterTable ExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(AExtractId, Transaction);
                    ExtractMaster[0].KeyCount         = ExtractTable.Rows.Count;

                    ExtractTable.ThrowAwayAfterSubmitChanges = true;     // no need to keep data as this increases speed significantly

                    MExtractAccess.SubmitChanges(ExtractTable, Transaction);

                    MExtractMasterAccess.SubmitChanges(ExtractMaster, Transaction);
                }
            });
        }
コード例 #12
0
        /// <summary>
        /// save the changes on the screen (code is copied from auto-generated code)
        /// </summary>
        /// <returns></returns>
        public bool SaveChanges()
        {
            FPetraUtilsObject.OnDataSavingStart(this, new System.EventArgs());

            if (FPetraUtilsObject.VerificationResultCollection.Count == 0)
            {
                foreach (DataRow InspectDR in FMainDS.MExtract.Rows)
                {
                    InspectDR.EndEdit();
                }

                if (!FPetraUtilsObject.HasChanges)
                {
                    return true;
                }
                else
                {
                    FPetraUtilsObject.WriteToStatusBar("Saving data...");
                    this.Cursor = Cursors.WaitCursor;

                    TSubmitChangesResult SubmissionResult;

                    //Ict.Common.Data.TTypedDataTable SubmitDT = FMainDS.MExtract.GetChangesTyped();
                    MExtractTable SubmitDT = new MExtractTable();
                    SubmitDT.Merge(FMainDS.MExtract.GetChangesTyped());

                    if (SubmitDT == null)
                    {
                        // There is nothing to be saved.
                        // Update UI
                        FPetraUtilsObject.WriteToStatusBar(Catalog.GetString("There is nothing to be saved."));
                        this.Cursor = Cursors.Default;

                        // We don't have unsaved changes anymore
                        FPetraUtilsObject.DisableSaveButton();

                        return true;
                    }

                    // Submit changes to the PETRAServer
                    try
                    {
                        SubmissionResult = TRemote.MPartner.Partner.WebConnectors.SaveExtract
                                               (FExtractId, ref SubmitDT);
                    }
                    catch (System.Net.Sockets.SocketException)
                    {
                        FPetraUtilsObject.WriteToStatusBar("Data could not be saved!");
                        this.Cursor = Cursors.Default;
                        MessageBox.Show("The PETRA Server cannot be reached! Data cannot be saved!",
                            "No Server response",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        bool ReturnValue = false;

                        // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return ReturnValue;
                    }
                    /* TODO ESecurityDBTableAccessDeniedException
                     *                  catch (ESecurityDBTableAccessDeniedException Exp)
                     *                  {
                     *                      FPetraUtilsObject.WriteToStatusBar("Data could not be saved!");
                     *                      this.Cursor = Cursors.Default;
                     *                      // TODO TMessages.MsgSecurityException(Exp, this.GetType());
                     *                      bool ReturnValue = false;
                     *                      // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                     *                      return ReturnValue;
                     *                  }
                     */
                    catch (EDBConcurrencyException)
                    {
                        FPetraUtilsObject.WriteToStatusBar("Data could not be saved!");
                        this.Cursor = Cursors.Default;

                        // TODO TMessages.MsgDBConcurrencyException(Exp, this.GetType());
                        bool ReturnValue = false;

                        // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return ReturnValue;
                    }
                    catch (Exception exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar("Data could not be saved!");
                        this.Cursor = Cursors.Default;
                        TLogging.Log(
                            Catalog.GetString(
                                "An error occurred while trying to connect to the OpenPetra Server!") + Environment.NewLine + exp.ToString(),
                            TLoggingType.ToLogfile);
                        MessageBox.Show(
                            Catalog.GetString("An error occurred while trying to connect to the OpenPetra Server!") + Environment.NewLine +
                            "For details see the log file: " + TLogging.GetLogFileName(),
                            "Server connection error",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);

                        // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return false;
                    }

                    switch (SubmissionResult)
                    {
                        case TSubmitChangesResult.scrOK:

                            // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server
                            FMainDS.MExtract.AcceptChanges();

                            // Merge back with data from the Server (eg. for getting Sequence values)
                            FMainDS.MExtract.Merge(SubmitDT, false);

                            // need to accept the new modification ID
                            FMainDS.MExtract.AcceptChanges();

                            // Update UI
                            FPetraUtilsObject.WriteToStatusBar("Data successfully saved.");
                            this.Cursor = Cursors.Default;

                            // TODO EnableSave(false);

                            // We don't have unsaved changes anymore
                            FPetraUtilsObject.DisableSaveButton();

                            SetPrimaryKeyReadOnly(true);

                            // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                            return true;

                        case TSubmitChangesResult.scrError:

                            // TODO scrError
                            this.Cursor = Cursors.Default;
                            break;

                        case TSubmitChangesResult.scrNothingToBeSaved:

                            // TODO scrNothingToBeSaved
                            this.Cursor = Cursors.Default;
                            return true;

                        case TSubmitChangesResult.scrInfoNeeded:

                            // TODO scrInfoNeeded
                            this.Cursor = Cursors.Default;
                            break;
                    }
                }
            }

            return false;
        }
コード例 #13
0
        /// <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;
            TSubmitChangesResult SubmissionResult = TSubmitChangesResult.scrOK;
            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
                FAsyncExecProgress.ProgressState = TAsyncExecProgressState.Aeps_Executing;
                FAsyncExecProgress.ProgressInformation = "Checking Partners' Subscriptions...";
                try
                {
                    SubmitChangesTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);
//                  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%.
                        FAsyncExecProgress.ProgressPercentage =
                            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.
                        FAsyncExecProgress.ProgressInformation = "Adding Subscriptions to " + FSubmissionDT.Rows.Count.ToString() + " Partners...";
                        FAsyncExecProgress.ProgressPercentage = 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.");
                    }

                    DBAccess.GDBAccessObj.CommitTransaction();
                }
                catch (Exception Exp)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();

                    TLogging.LogAtLevel(7,
                        "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Exception occured, Transaction ROLLED BACK. Exception: " +
                        Exp.ToString());

                    FSubmitResult = TSubmitChangesResult.scrError;
                    FSubmitException = Exp;
                    FAsyncExecProgress.ProgressState = TAsyncExecProgressState.Aeps_Stopped;

                    return;
                }
            }
            else
            {
                SubmissionResult = TSubmitChangesResult.scrNothingToBeSaved;
            }

            // 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();
            }

            FAsyncExecProgress.ProgressPercentage = 100;
            FAsyncExecProgress.ProgressState = TAsyncExecProgressState.Aeps_Finished;
            FSubmitResult = SubmissionResult;
        }
コード例 #14
0
        public static bool GetData(string ATablename, TSearchCriteria[] ASearchCriteria, out TTypedDataTable AResultTable)
        {
            // TODO: check access permissions for the current user

            bool           NewTransaction = false;
            TDBTransaction ReadTransaction;

            TTypedDataTable tempTable = null;

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

                // TODO: auto generate
                if (ATablename == AApSupplierTable.GetTableDBName())
                {
                    tempTable = AApSupplierAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == AApDocumentTable.GetTableDBName())
                {
                    tempTable = AApDocumentAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == ATransactionTypeTable.GetTableDBName())
                {
                    tempTable = ATransactionTypeAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == ACurrencyTable.GetTableDBName())
                {
                    tempTable = ACurrencyAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == ADailyExchangeRateTable.GetTableDBName())
                {
                    tempTable = ADailyExchangeRateAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == ACorporateExchangeRateTable.GetTableDBName())
                {
                    tempTable = ACorporateExchangeRateAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == ACurrencyLanguageTable.GetTableDBName())
                {
                    tempTable = ACurrencyLanguageAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == AFeesPayableTable.GetTableDBName())
                {
                    tempTable = AFeesPayableAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == AFeesReceivableTable.GetTableDBName())
                {
                    tempTable = AFeesReceivableAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == AAnalysisTypeTable.GetTableDBName())
                {
                    tempTable = AAnalysisTypeAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == AGiftBatchTable.GetTableDBName())
                {
                    tempTable = AGiftBatchAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == AJournalTable.GetTableDBName())
                {
                    tempTable = AJournalAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == ALedgerTable.GetTableDBName())
                {
                    tempTable = ALedgerAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == MExtractMasterTable.GetTableDBName())
                {
                    if (ASearchCriteria == null)
                    {
                        tempTable = MExtractMasterAccess.LoadAll(ReadTransaction);
                    }
                    else
                    {
                        tempTable = MExtractMasterAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                    }
                }
                else if (ATablename == MExtractTable.GetTableDBName())
                {
                    // it does not make sense to load ALL extract rows for all extract masters so search criteria needs to be set
                    if (ASearchCriteria != null)
                    {
                        tempTable = MExtractAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                    }
                }
                else if (ATablename == PcAttendeeTable.GetTableDBName())
                {
                    tempTable = PcAttendeeAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == PcConferenceCostTable.GetTableDBName())
                {
                    tempTable = PcConferenceCostAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == PcEarlyLateTable.GetTableDBName())
                {
                    tempTable = PcEarlyLateAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == PcSupplementTable.GetTableDBName())
                {
                    tempTable = PcSupplementAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == PcDiscountTable.GetTableDBName())
                {
                    tempTable = PcDiscountAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == PInternationalPostalTypeTable.GetTableDBName())
                {
                    tempTable = PInternationalPostalTypeAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == PtApplicationTypeTable.GetTableDBName())
                {
                    tempTable = PtApplicationTypeAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == PMailingTable.GetTableDBName())
                {
                    tempTable = PMailingAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName())
                {
                    tempTable = PPartnerGiftDestinationAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == PmDocumentTypeTable.GetTableDBName())
                {
                    tempTable = PmDocumentTypeAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == SGroupTable.GetTableDBName())
                {
                    tempTable = SGroupAccess.LoadAll(ReadTransaction);
                }
                else
                {
                    throw new Exception("TCommonDataReader.GetData: unknown table " + ATablename);
                }
            }
            catch (Exception Exp)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
                TLogging.Log("TCommonDataReader.GetData exception: " + Exp.ToString(), TLoggingType.ToLogfile);
                TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile);
                throw;
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "TCommonDataReader.GetData: committed own transaction.");
                }
            }

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

            // return the table
            AResultTable = tempTable;

            return(true);
        }
コード例 #15
0
        /// <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;
        }
コード例 #16
0
ファイル: ExtractMaster.cs プロジェクト: Davincier/openpetra
        public static Boolean SubtractExtracts(String ANewExtractName,
            String ANewExtractDescription,
            String ABaseExtractName,
            List <Int32>ASubtractExtractIdList,
            out Int32 ANewExtractId)
        {
            Boolean ResultValue = true;
            Boolean ExtractAlreadyExists = false;
            MExtractTable ExtractTable;
            MExtractMasterTable BaseExtractMasterTable;
            MExtractTable BaseExtractTable;
            MExtractTable SubtractedExtractTable = new MExtractTable();
            MExtractRow TemplateRow;
            Int32 NewExtractId;

            List <Int64>SubtractPartnerKeyList = new List <Int64>();

            NewExtractId = -1;

            TDBTransaction Transaction = null;
            bool SubmissionOK = false;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable,
                ref Transaction,
                ref SubmissionOK,
                delegate
                {
                    ResultValue = MPartner.Extracts.TExtractsHandling.CreateNewExtract(ANewExtractName,
                        ANewExtractDescription, out NewExtractId, out ExtractAlreadyExists);

                    if (ResultValue && !ExtractAlreadyExists)
                    {
                        // first create a table that contains all partners to be subtracted
                        foreach (Int32 ExtractId in ASubtractExtractIdList)
                        {
                            ExtractTable = MExtractAccess.LoadViaMExtractMaster(ExtractId, Transaction);

                            foreach (DataRow ExtractRow in ExtractTable.Rows)
                            {
                                if (!SubtractPartnerKeyList.Exists(item => item == ((MExtractRow)ExtractRow).PartnerKey))
                                {
                                    SubtractPartnerKeyList.Add(((MExtractRow)ExtractRow).PartnerKey);
                                }
                            }
                        }

                        if (ASubtractExtractIdList.Count > 0)
                        {
                            BaseExtractMasterTable = MExtractMasterAccess.LoadByUniqueKey(ABaseExtractName, Transaction);
                            BaseExtractTable = MExtractAccess.LoadViaMExtractMaster(((MExtractMasterRow)BaseExtractMasterTable.Rows[0]).ExtractId,
                                Transaction);

                            // iterate through all partners in base extract and check if this record also exists in extracts to be subtracted
                            foreach (DataRow ExtractRow in BaseExtractTable.Rows)
                            {
                                if (!SubtractPartnerKeyList.Exists(item => item == ((MExtractRow)ExtractRow).PartnerKey))
                                {
                                    // if partner key does not exist in list to subtract then add it to result extract
                                    TemplateRow = (MExtractRow)SubtractedExtractTable.NewRowTyped(true);
                                    TemplateRow.ExtractId = NewExtractId;
                                    TemplateRow.PartnerKey = ((MExtractRow)ExtractRow).PartnerKey;
                                    TemplateRow.SiteKey = ((MExtractRow)ExtractRow).SiteKey;
                                    TemplateRow.LocationKey = ((MExtractRow)ExtractRow).LocationKey;

                                    SubtractedExtractTable.Rows.Add(TemplateRow);
                                }
                            }
                        }

                        // update key count in master table
                        MExtractMasterTable IntersectedExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(NewExtractId, Transaction);
                        IntersectedExtractMaster[0].KeyCount = SubtractedExtractTable.Rows.Count;

                        // submit changes in master and then in extract content table which refers to it
                        MExtractAccess.SubmitChanges(SubtractedExtractTable, Transaction);

                        MExtractMasterAccess.SubmitChanges(IntersectedExtractMaster, Transaction);
                    }

                    SubmissionOK = true;
                });

            ResultValue = SubmissionOK;
            ANewExtractId = NewExtractId;

            return ResultValue;
        }
コード例 #17
0
ファイル: ExtractMaster.cs プロジェクト: js1987/openpetragit
        public static Boolean IntersectExtracts(String ANewExtractName,
            String ANewExtractDescription,
            List <Int32>AIntersectExtractIdList,
            out Int32 ANewExtractId)
        {
            Boolean ResultValue = true;
            Boolean ExtractAlreadyExists = false;
            Int32 ExtractIndex;
            MExtractTable FirstExtractTable;
            MExtractTable IntersectedExtractTable = new MExtractTable();
            MExtractRow TemplateRow;
            Boolean NewTransaction;
            Boolean PartnerExistsInAllExtracts;

            TDBTransaction WriteTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable,
                TEnforceIsolationLevel.eilMinimum, out NewTransaction);

            ANewExtractId = -1;

            try
            {
                ResultValue = MPartner.Extracts.TExtractsHandling.CreateNewExtract(ANewExtractName,
                    ANewExtractDescription, out ANewExtractId, out ExtractAlreadyExists);

                if (ResultValue && !ExtractAlreadyExists)
                {
                    if (AIntersectExtractIdList.Count > 0)
                    {
                        FirstExtractTable = MExtractAccess.LoadViaMExtractMaster(AIntersectExtractIdList[0], WriteTransaction);

                        // iterate through all partners in first extract and check if this record also exists in all other extracts
                        foreach (DataRow ExtractRow in FirstExtractTable.Rows)
                        {
                            PartnerExistsInAllExtracts = true;

                            // now check if this partner record exists in all other extracts as well
                            for (ExtractIndex = 1;
                                 ExtractIndex < AIntersectExtractIdList.Count && PartnerExistsInAllExtracts;
                                 ExtractIndex++)
                            {
                                if (!MExtractAccess.Exists(AIntersectExtractIdList[ExtractIndex], ((MExtractRow)ExtractRow).PartnerKey,
                                        ((MExtractRow)ExtractRow).SiteKey, WriteTransaction))
                                {
                                    // can stop here as there is at least one extract where partner does not exist
                                    PartnerExistsInAllExtracts = false;
                                }
                            }

                            // create and add row to intersected extract as it exists in all extracts
                            if (PartnerExistsInAllExtracts)
                            {
                                TemplateRow = (MExtractRow)IntersectedExtractTable.NewRowTyped(true);
                                TemplateRow.ExtractId = ANewExtractId;
                                TemplateRow.PartnerKey = ((MExtractRow)ExtractRow).PartnerKey;
                                TemplateRow.SiteKey = ((MExtractRow)ExtractRow).SiteKey;
                                TemplateRow.LocationKey = ((MExtractRow)ExtractRow).LocationKey;

                                IntersectedExtractTable.Rows.Add(TemplateRow);
                            }
                        }
                    }

                    // update key count in master table
                    MExtractMasterTable IntersectedExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(ANewExtractId, WriteTransaction);
                    IntersectedExtractMaster[0].KeyCount = IntersectedExtractTable.Rows.Count;

                    // submit changes in master and then in extract content table which refers to it
                    MExtractAccess.SubmitChanges(IntersectedExtractTable, WriteTransaction);

                    MExtractMasterAccess.SubmitChanges(IntersectedExtractMaster, WriteTransaction);
                }

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the intersecting of Extracts:" + Environment.NewLine + Exc.ToString());

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }

                throw;
            }

            return ResultValue;
        }
コード例 #18
0
ファイル: Extracts.cs プロジェクト: jsuen123/openpetragit
        /// <summary>
        /// Adds a Partner to an Extract, if they are not already present
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of Partner</param>
        /// <param name="ALocationPK">Location PK of a Partner's PartnerLocation
        /// (usually the LocationPK of the 'Best Address' of the Partner).</param>
        /// <param name="AExtractId">ExtractId of the Extract that the Partner should
        /// get added to.</param>
        /// <returns>True if the Partner was added to the Extract, otherwise false.</returns>
        public static bool AddPartnerToExtract(Int64 APartnerKey,
                                               TLocationPK ALocationPK, int AExtractId)
        {
            bool           ReturnValue;
            TDBTransaction WriteTransaction;
            MExtractTable  TemplateTable;
            MExtractRow    TemplateRow;
            MExtractRow    NewRow;
            Boolean        NewTransaction;

            if (APartnerKey > 0)
            {
                WriteTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(
                    IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum, out NewTransaction);

                try
                {
                    /*
                     * First check whether the Partner isn't already in that Extract
                     */
                    TemplateTable          = new MExtractTable();
                    TemplateRow            = TemplateTable.NewRowTyped(false);
                    TemplateRow.ExtractId  = AExtractId;
                    TemplateRow.PartnerKey = APartnerKey;

                    if (MExtractAccess.CountUsingTemplate(TemplateRow, null, WriteTransaction) == 0)
                    {
                        /*
                         * Add Partner to Extract.
                         */
                        NewRow             = TemplateTable.NewRowTyped(false);
                        NewRow.ExtractId   = AExtractId;
                        NewRow.PartnerKey  = APartnerKey;
                        NewRow.SiteKey     = ALocationPK.SiteKey;
                        NewRow.LocationKey = ALocationPK.LocationKey;
                        TemplateTable.Rows.Add(NewRow);

                        MExtractAccess.SubmitChanges(TemplateTable, WriteTransaction);

                        ReturnValue = true;
                    }
                    else
                    {
                        // Partner is already in that Extract -> Partner does not get added.
                        ReturnValue = false;
                    }

                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                        TLogging.LogAtLevel(8, "TExtractsHandling.AddPartnerToExtract: committed own transaction!");
                    }
                }
                catch (Exception Exc)
                {
                    TLogging.Log("An Exception occured while adding a Partner to an Extract:" + Environment.NewLine + Exc.ToString());

                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.RollbackTransaction();
                    }

                    throw;
                }
            }
            else
            {
                // Invalid PartnerKey -> return false;
                ReturnValue = false;
            }

            return(ReturnValue);
        }
コード例 #19
0
ファイル: ExtractMaster.cs プロジェクト: js1987/openpetragit
        public static Boolean SubtractExtracts(String ANewExtractName,
            String ANewExtractDescription,
            String ABaseExtractName,
            List <Int32>ASubtractExtractIdList,
            out Int32 ANewExtractId)
        {
            Boolean ResultValue = true;
            Boolean ExtractAlreadyExists = false;
            MExtractTable ExtractTable;
            MExtractMasterTable BaseExtractMasterTable;
            MExtractTable BaseExtractTable;
            MExtractTable SubtractedExtractTable = new MExtractTable();
            MExtractRow TemplateRow;
            Boolean NewTransaction;

            List <Int64>SubtractPartnerKeyList = new List <Int64>();

            ANewExtractId = -1;

            TDBTransaction WriteTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable,
                TEnforceIsolationLevel.eilMinimum, out NewTransaction);

            try
            {
                ResultValue = MPartner.Extracts.TExtractsHandling.CreateNewExtract(ANewExtractName,
                    ANewExtractDescription, out ANewExtractId, out ExtractAlreadyExists);

                if (ResultValue && !ExtractAlreadyExists)
                {
                    // first create a table that contains all partners to be subtracted
                    foreach (Int32 ExtractId in ASubtractExtractIdList)
                    {
                        ExtractTable = MExtractAccess.LoadViaMExtractMaster(ExtractId, WriteTransaction);

                        foreach (DataRow ExtractRow in ExtractTable.Rows)
                        {
                            if (!SubtractPartnerKeyList.Exists(item => item == ((MExtractRow)ExtractRow).PartnerKey))
                            {
                                SubtractPartnerKeyList.Add(((MExtractRow)ExtractRow).PartnerKey);
                            }
                        }
                    }

                    if (ASubtractExtractIdList.Count > 0)
                    {
                        BaseExtractMasterTable = MExtractMasterAccess.LoadByUniqueKey(ABaseExtractName, WriteTransaction);
                        BaseExtractTable = MExtractAccess.LoadViaMExtractMaster(((MExtractMasterRow)BaseExtractMasterTable.Rows[0]).ExtractId,
                            WriteTransaction);

                        // iterate through all partners in base extract and check if this record also exists in extracts to be subtracted
                        foreach (DataRow ExtractRow in BaseExtractTable.Rows)
                        {
                            if (!SubtractPartnerKeyList.Exists(item => item == ((MExtractRow)ExtractRow).PartnerKey))
                            {
                                // if partner key does not exist in list to subtract then add it to result extract
                                TemplateRow = (MExtractRow)SubtractedExtractTable.NewRowTyped(true);
                                TemplateRow.ExtractId = ANewExtractId;
                                TemplateRow.PartnerKey = ((MExtractRow)ExtractRow).PartnerKey;
                                TemplateRow.SiteKey = ((MExtractRow)ExtractRow).SiteKey;
                                TemplateRow.LocationKey = ((MExtractRow)ExtractRow).LocationKey;

                                SubtractedExtractTable.Rows.Add(TemplateRow);
                            }
                        }
                    }

                    // update key count in master table
                    MExtractMasterTable IntersectedExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(ANewExtractId, WriteTransaction);
                    IntersectedExtractMaster[0].KeyCount = SubtractedExtractTable.Rows.Count;

                    // submit changes in master and then in extract content table which refers to it
                    MExtractAccess.SubmitChanges(SubtractedExtractTable, WriteTransaction);

                    MExtractMasterAccess.SubmitChanges(IntersectedExtractMaster, WriteTransaction);

                    ResultValue = true;
                }

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the subtraction of Extracts:" + Environment.NewLine + Exc.ToString());

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }

                throw;
            }

            return ResultValue;
        }
コード例 #20
0
        /// <summary>
        /// save the changes on the screen (code is copied from auto-generated code)
        /// </summary>
        /// <returns></returns>
        public bool SaveChanges()
        {
            bool ReturnValue = false;

            FPetraUtilsObject.OnDataSavingStart(this, new System.EventArgs());

            if (FPetraUtilsObject.VerificationResultCollection.Count == 0)
            {
                foreach (DataRow InspectDR in FMainDS.MExtract.Rows)
                {
                    InspectDR.EndEdit();
                }

                if (!FPetraUtilsObject.HasChanges)
                {
                    return(true);
                }
                else
                {
                    FPetraUtilsObject.WriteToStatusBar("Saving data...");
                    this.Cursor = Cursors.WaitCursor;

                    TSubmitChangesResult SubmissionResult;

                    //Ict.Common.Data.TTypedDataTable SubmitDT = FMainDS.MExtract.GetChangesTyped();
                    MExtractTable           SubmitDT  = new MExtractTable();
                    ExtractTDSMExtractTable ChangesDT = FMainDS.MExtract.GetChangesTyped();

                    if (ChangesDT != null)
                    {
                        SubmitDT.Merge(ChangesDT);
                    }
                    else
                    {
                        SubmitDT = null;
                    }

                    if (SubmitDT == null)
                    {
                        // There is nothing to be saved.
                        // Update UI
                        FPetraUtilsObject.WriteToStatusBar(Catalog.GetString("There is nothing to be saved."));
                        this.Cursor = Cursors.Default;

                        // We don't have unsaved changes anymore
                        FPetraUtilsObject.DisableSaveButton();

                        return(true);
                    }

                    // Submit changes to the PETRAServer
                    try
                    {
                        SubmissionResult = TRemote.MPartner.Partner.WebConnectors.SaveExtract
                                               (FExtractId, ref SubmitDT);
                    }
                    catch (ESecurityDBTableAccessDeniedException Exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        TMessages.MsgSecurityException(Exp, this.GetType());

                        ReturnValue = false;
                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return(ReturnValue);
                    }
                    catch (EDBConcurrencyException Exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        TMessages.MsgDBConcurrencyException(Exp, this.GetType());

                        ReturnValue = false;
                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return(ReturnValue);
                    }
                    catch (Exception)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        throw;
                    }

                    switch (SubmissionResult)
                    {
                    case TSubmitChangesResult.scrOK:

                        // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server
                        FMainDS.MExtract.AcceptChanges();

                        // Merge back with data from the Server (eg. for getting Sequence values)
                        FMainDS.MExtract.Merge(SubmitDT, false);

                        // need to accept the new modification ID
                        FMainDS.MExtract.AcceptChanges();

                        // Update UI
                        FPetraUtilsObject.WriteToStatusBar("Data successfully saved.");
                        this.Cursor = Cursors.Default;

                        // TODO EnableSave(false);

                        // We don't have unsaved changes anymore
                        FPetraUtilsObject.DisableSaveButton();

                        SetPrimaryKeyReadOnly(true);

                        // refresh extract master screen if it is open
                        TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated);
                        BroadcastMessage.SetMessageDataName(ExtractName);
                        TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
                        this.Focus();     // keeps the focus on the current form

                        // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return(true);

                    case TSubmitChangesResult.scrError:

                        // TODO scrError
                        this.Cursor = Cursors.Default;
                        break;

                    case TSubmitChangesResult.scrNothingToBeSaved:

                        // TODO scrNothingToBeSaved
                        this.Cursor = Cursors.Default;
                        return(true);

                    case TSubmitChangesResult.scrInfoNeeded:

                        // TODO scrInfoNeeded
                        this.Cursor = Cursors.Default;
                        break;
                    }
                }
            }

            return(false);
        }
コード例 #21
0
ファイル: ExtractMaster.cs プロジェクト: js1987/openpetragit
        public static TSubmitChangesResult SaveExtract(int AExtractId, ref MExtractTable AExtractTable)
        {
            TDBTransaction SubmitChangesTransaction;
            int CountExtractRows;
            MExtractMasterTable ExtractMasterDT;

            if (AExtractTable != null)
            {
                SubmitChangesTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

                try
                {
                    MExtractAccess.SubmitChanges(AExtractTable, SubmitChangesTransaction);

                    // update extract master record with the correct number of extract records
                    if (AExtractTable.Rows.Count > 0)
                    {
                        CountExtractRows = MExtractAccess.CountViaMExtractMaster(AExtractId, SubmitChangesTransaction);
                        ExtractMasterDT = MExtractMasterAccess.LoadByPrimaryKey(AExtractId, SubmitChangesTransaction);

                        if (ExtractMasterDT.Rows.Count != 0)
                        {
                            ((MExtractMasterRow)ExtractMasterDT.Rows[0]).KeyCount = CountExtractRows;

                            MExtractMasterAccess.SubmitChanges(ExtractMasterDT, SubmitChangesTransaction);
                        }
                    }

                    DBAccess.GDBAccessObj.CommitTransaction();
                }
                catch (Exception Exc)
                {
                    TLogging.Log("An Exception occured during the saving of an Extract:" + Environment.NewLine + Exc.ToString());

                    DBAccess.GDBAccessObj.RollbackTransaction();

                    throw;
                }
            }

            return TSubmitChangesResult.scrOK;
        }
コード例 #22
0
        public static bool GetData(string ATablename, TSearchCriteria[] ASearchCriteria, out TTypedDataTable AResultTable)
        {
            // TODO: check access permissions for the current user

            TDBTransaction ReadTransaction = null;

            TTypedDataTable tempTable = null;

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

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

                    tempTable = PFormAccess.LoadAll(fieldList, ReadTransaction);
                }
                else if (ATablename == PInternationalPostalTypeTable.GetTableDBName())
                {
                    tempTable = PInternationalPostalTypeAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == PtApplicationTypeTable.GetTableDBName())
                {
                    tempTable = PtApplicationTypeAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == PFormalityTable.GetTableDBName())
                {
                    tempTable = PFormalityAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == PMailingTable.GetTableDBName())
                {
                    tempTable = PMailingAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName())
                {
                    tempTable = PPartnerGiftDestinationAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction);
                }
                else if (ATablename == PmDocumentTypeTable.GetTableDBName())
                {
                    tempTable = PmDocumentTypeAccess.LoadAll(ReadTransaction);
                }
                else if (ATablename == SGroupTable.GetTableDBName())
                {
                    tempTable = SGroupAccess.LoadAll(ReadTransaction);
                }
                else
                {
                    throw new Exception("TCommonDataReader.GetData: unknown table " + ATablename);
                }
            });

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

            // return the table
            AResultTable = tempTable;

            return(true);
        }
コード例 #23
0
ファイル: Extracts.cs プロジェクト: js1987/openpetragit
        /// <summary>
        /// Adds a Partner to an Extract, if they are not already present
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of Partner</param>
        /// <param name="ALocationPK">Location PK of a Partner's PartnerLocation
        /// (usually the LocationPK of the 'Best Address' of the Partner).</param>
        /// <param name="AExtractId">ExtractId of the Extract that the Partner should
        /// get added to.</param>
        /// <returns>True if the Partner was added to the Extract, otherwise false.</returns>
        public static bool AddPartnerToExtract(Int64 APartnerKey,
            TLocationPK ALocationPK, int AExtractId)
        {
            bool ReturnValue;
            TDBTransaction WriteTransaction;
            MExtractTable TemplateTable;
            MExtractRow TemplateRow;
            MExtractRow NewRow;
            Boolean NewTransaction;

            if (APartnerKey > 0)
            {
                WriteTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(
                    IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum, out NewTransaction);

                try
                {
                    /*
                     * First check whether the Partner isn't already in that Extract
                     */
                    TemplateTable = new MExtractTable();
                    TemplateRow = TemplateTable.NewRowTyped(false);
                    TemplateRow.ExtractId = AExtractId;
                    TemplateRow.PartnerKey = APartnerKey;

                    if (MExtractAccess.CountUsingTemplate(TemplateRow, null, WriteTransaction) == 0)
                    {
                        /*
                         * Add Partner to Extract.
                         */
                        NewRow = TemplateTable.NewRowTyped(false);
                        NewRow.ExtractId = AExtractId;
                        NewRow.PartnerKey = APartnerKey;
                        NewRow.SiteKey = ALocationPK.SiteKey;
                        NewRow.LocationKey = ALocationPK.LocationKey;
                        TemplateTable.Rows.Add(NewRow);

                        MExtractAccess.SubmitChanges(TemplateTable, WriteTransaction);

                        ReturnValue = true;
                    }
                    else
                    {
                        // Partner is already in that Extract -> Partner does not get added.
                        ReturnValue = false;
                    }

                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                        TLogging.LogAtLevel(8, "TExtractsHandling.AddPartnerToExtract: committed own transaction!");
                    }
                }
                catch (Exception Exc)
                {
                    TLogging.Log("An Exception occured while adding a Partner to an Extract:" + Environment.NewLine + Exc.ToString());

                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.RollbackTransaction();
                    }

                    throw;
                }
            }
            else
            {
                // Invalid PartnerKey -> return false;
                ReturnValue = false;
            }

            return ReturnValue;
        }
コード例 #24
0
ファイル: Extracts.cs プロジェクト: merbst/openpetra
        /// <summary>
        /// extend an extract from a list of best addresses
        /// </summary>
        /// <param name="AExtractId">Extract Id of the Extract to extend</param>
        /// <param name="APartnerKeysTable"></param>
        /// <param name="APartnerKeyColumn">number of the column that contains the partner keys</param>
        /// <param name="ASiteKeyColumn">number of the column that contains the site keys</param>
        /// <param name="ALocationKeyColumn">number of the column that contains the location keys</param>
        /// <param name="AKeyCount">The number of keys that were actually added to the extract (any duplicates are excluded)</param>
        /// <param name="AIgnoredKeyList">A reference to a List of long.  If not null the server will fill it with the partner keys that were ignored.  Does not include duplicates.</param>
        /// <param name="AIgnoreDuplicates">true if duplicates should be looked out for. Can be set to false if called only once and not several times per extract.</param>
        /// <param name="AIgnoreInactive">true if inactive partners should be ignored</param>
        /// <param name="AIgnoreNonMailingLocations">true to ignore if the partner's best address is a non-mailing location</param>
        /// <param name="AIgnoreNoSolicitations">true to ignore partners where the No Solicitations flag is set</param>
        public static void ExtendExtractFromListOfPartnerKeys(
            Int32 AExtractId,
            DataTable APartnerKeysTable,
            Int32 APartnerKeyColumn,
            Int32 ASiteKeyColumn,
            Int32 ALocationKeyColumn,
            out Int32 AKeyCount,
            out List <long> AIgnoredKeyList,
            bool AIgnoreDuplicates,
            bool AIgnoreInactive,
            bool AIgnoreNonMailingLocations,
            bool AIgnoreNoSolicitations)
        {
            int RecordCounter = 0;
            PPartnerLocationTable PartnerLocationKeysTable;
            Int64 PartnerKey;

            List <long> ignoredKeyList = new List <long>();

            TDBTransaction Transaction  = null;
            bool           SubmissionOK = true;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK,
                                                                  delegate
            {
                // Pre-process the table to remove partner rows that do not match the filter requirements
                for (int i = APartnerKeysTable.Rows.Count - 1; i >= 0; i--)
                {
                    DataRow dr       = APartnerKeysTable.Rows[i];
                    Int64 partnerKey = Convert.ToInt64(dr[APartnerKeyColumn]);

                    // Get a partner record containing our fields of interest
                    StringCollection fields = new StringCollection();
                    fields.Add(PPartnerTable.GetStatusCodeDBName());
                    fields.Add(PPartnerTable.GetNoSolicitationsDBName());
                    DataTable dt = PPartnerAccess.LoadByPrimaryKey(partnerKey, fields, Transaction);

                    if (dt.Rows.Count > 0)
                    {
                        if (AIgnoreInactive || AIgnoreNoSolicitations)
                        {
                            bool isActive         = false;
                            bool isNoSolicitation = false;
                            object o = dt.Rows[0][PPartnerTable.GetStatusCodeDBName()];

                            if (o != null)
                            {
                                TStdPartnerStatusCode statusCode = SharedTypes.StdPartnerStatusCodeStringToEnum(o.ToString());
                                isActive = (statusCode == TStdPartnerStatusCode.spscACTIVE);
                            }

                            o = dt.Rows[0][PPartnerTable.GetNoSolicitationsDBName()];

                            if (o != null)
                            {
                                isNoSolicitation = Convert.ToBoolean(o);
                            }

                            if ((AIgnoreInactive && !isActive) || (AIgnoreNoSolicitations && isNoSolicitation))
                            {
                                ignoredKeyList.Add(partnerKey);
                                APartnerKeysTable.Rows.Remove(dr);
                            }
                        }
                    }
                    else
                    {
                        ignoredKeyList.Add(partnerKey);
                    }
                }

                MExtractTable ExtractTable = new MExtractTable();
                ExtractTable = MExtractAccess.LoadViaMExtractMaster(AExtractId, Transaction);

                // Location Keys need to be determined as extracts do not only need partner keys but
                // also Location Keys.
                DetermineBestLocationKeys(APartnerKeysTable, APartnerKeyColumn, ASiteKeyColumn,
                                          ALocationKeyColumn, out PartnerLocationKeysTable,
                                          Transaction);

                // use the returned table which contains partner and location keys to build the extract
                foreach (PPartnerLocationRow PartnerLocationRow in PartnerLocationKeysTable.Rows)
                {
                    PartnerKey = PartnerLocationRow.PartnerKey;

                    if (PartnerKey > 0)
                    {
                        if (AIgnoreNonMailingLocations)
                        {
                            // The PartnerLocationRow only contains the PK fields so now we need to get the SendMail column
                            StringCollection fields = new StringCollection();
                            fields.Add(PPartnerLocationTable.GetSendMailDBName());

                            PPartnerLocationTable t =
                                PPartnerLocationAccess.LoadByPrimaryKey(PartnerKey, PartnerLocationRow.SiteKey,
                                                                        PartnerLocationRow.LocationKey, fields, Transaction);

                            if ((t != null) && (t.Rows.Count > 0) && (((PPartnerLocationRow)t.Rows[0]).SendMail == false))
                            {
                                ignoredKeyList.Add(PartnerKey);
                                continue;
                            }
                        }

                        RecordCounter += 1;
                        TLogging.LogAtLevel(1, "Preparing Partner " + PartnerKey + " (Record Number " + RecordCounter + ")");

                        // add row for partner to extract and fill with contents
                        MExtractRow NewRow = ExtractTable.NewRowTyped();
                        NewRow.ExtractId   = AExtractId;
                        NewRow.PartnerKey  = PartnerKey;
                        NewRow.SiteKey     = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetSiteKeyDBName()]);
                        NewRow.LocationKey = Convert.ToInt32(PartnerLocationRow[PPartnerLocationTable.GetLocationKeyDBName()]);

                        // only add row if it does not already exist for this partner
                        if (AIgnoreDuplicates || !ExtractTable.Rows.Contains(new object[] { NewRow.ExtractId, NewRow.PartnerKey, NewRow.SiteKey }))
                        {
                            ExtractTable.Rows.Add(NewRow);
                        }
                    }
                }

                if (ExtractTable.Rows.Count > 0)
                {
                    // update field in extract master for quick access to number of partners in extract
                    MExtractMasterTable ExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(AExtractId, Transaction);
                    ExtractMaster[0].KeyCount         = ExtractTable.Rows.Count;

                    ExtractTable.ThrowAwayAfterSubmitChanges = true;     // no need to keep data as this increases speed significantly

                    MExtractAccess.SubmitChanges(ExtractTable, Transaction);

                    MExtractMasterAccess.SubmitChanges(ExtractMaster, Transaction);
                }
            });

            AKeyCount       = RecordCounter;
            AIgnoredKeyList = ignoredKeyList;
        }
コード例 #25
0
ファイル: Extracts.cs プロジェクト: js1987/openpetragit
        /// <summary>
        /// extend an extract from a list of best addresses
        /// </summary>
        /// <param name="AExtractId">Extract Id of the Extract to extend</param>
        /// <param name="APartnerKeysTable"></param>
        /// <param name="APartnerKeyColumn">number of the column that contains the partner keys</param>
        /// <param name="ASiteKeyColumn">number of the column that contains the site keys</param>
        /// <param name="ALocationKeyColumn">number of the column that contains the location keys</param>
        /// <param name="AIgnoreDuplicates">true if duplicates should be looked out for. Can be set to false if called only once and not several times per extract.</param>
        /// <param name="ACommitTransaction">true if transaction should be committed at end of method</param>
        public static void ExtendExtractFromListOfPartnerKeys(
            Int32 AExtractId,
            DataTable APartnerKeysTable,
            Int32 APartnerKeyColumn,
            Int32 ASiteKeyColumn,
            Int32 ALocationKeyColumn,
            bool AIgnoreDuplicates,
            bool ACommitTransaction)
        {
            Boolean NewTransaction;
            int RecordCounter = 0;
            PPartnerLocationTable PartnerLocationKeysTable;
            Int64 PartnerKey;

            TDBTransaction WriteTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable,
                TEnforceIsolationLevel.eilMinimum, out NewTransaction);

            try
            {
                MExtractTable ExtractTable = new MExtractTable();
                ExtractTable = MExtractAccess.LoadViaMExtractMaster(AExtractId, WriteTransaction);

                // Location Keys need to be determined as extracts do not only need partner keys but
                // also Location Keys.
                DetermineBestLocationKeys(APartnerKeysTable, APartnerKeyColumn, ASiteKeyColumn,
                    ALocationKeyColumn, out PartnerLocationKeysTable,
                    WriteTransaction);

                // use the returned table which contains partner and location keys to build the extract
                foreach (PPartnerLocationRow PartnerLocationRow in PartnerLocationKeysTable.Rows)
                {
                    PartnerKey = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetPartnerKeyDBName()]);

                    if (PartnerKey > 0)
                    {
                        RecordCounter += 1;
                        TLogging.Log("Preparing Partner " + PartnerKey.ToString() + " (Record Number " + RecordCounter.ToString() + ")");

                        // add row for partner to extract and fill with contents
                        MExtractRow NewRow = ExtractTable.NewRowTyped();
                        NewRow.ExtractId = AExtractId;
                        NewRow.PartnerKey = PartnerKey;
                        NewRow.SiteKey = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetSiteKeyDBName()]);
                        NewRow.LocationKey = Convert.ToInt32(PartnerLocationRow[PPartnerLocationTable.GetLocationKeyDBName()]);

                        // only add row if it does not already exist for this partner
                        if (AIgnoreDuplicates || !ExtractTable.Rows.Contains(new object[] { NewRow.ExtractId, NewRow.PartnerKey, NewRow.SiteKey }))
                        {
                            ExtractTable.Rows.Add(NewRow);
                        }
                    }
                }

                if (ExtractTable.Rows.Count > 0)
                {
                    // update field in extract master for quick access to number of partners in extract
                    MExtractMasterTable ExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(AExtractId, WriteTransaction);
                    ExtractMaster[0].KeyCount = ExtractTable.Rows.Count;

                    ExtractTable.ThrowAwayAfterSubmitChanges = true; // no need to keep data as this increases speed significantly

                    MExtractAccess.SubmitChanges(ExtractTable, WriteTransaction);

                    MExtractMasterAccess.SubmitChanges(ExtractMaster, WriteTransaction);
                }

                if (ACommitTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured while extending an Extract from a list of Partner Keys:" + Environment.NewLine + Exc.ToString());

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }

                throw;
            }
        }
コード例 #26
0
        /// <summary>
        /// save the changes on the screen (code is copied from auto-generated code)
        /// </summary>
        /// <returns></returns>
        public bool SaveChanges()
        {
            FPetraUtilsObject.OnDataSavingStart(this, new System.EventArgs());

            if (FPetraUtilsObject.VerificationResultCollection.Count == 0)
            {
                foreach (DataRow InspectDR in FMainDS.MExtract.Rows)
                {
                    InspectDR.EndEdit();
                }

                if (!FPetraUtilsObject.HasChanges)
                {
                    return(true);
                }
                else
                {
                    FPetraUtilsObject.WriteToStatusBar("Saving data...");
                    this.Cursor = Cursors.WaitCursor;

                    TSubmitChangesResult SubmissionResult;

                    //Ict.Common.Data.TTypedDataTable SubmitDT = FMainDS.MExtract.GetChangesTyped();
                    MExtractTable SubmitDT = new MExtractTable();
                    SubmitDT.Merge(FMainDS.MExtract.GetChangesTyped());

                    if (SubmitDT == null)
                    {
                        // There is nothing to be saved.
                        // Update UI
                        FPetraUtilsObject.WriteToStatusBar(Catalog.GetString("There is nothing to be saved."));
                        this.Cursor = Cursors.Default;

                        // We don't have unsaved changes anymore
                        FPetraUtilsObject.DisableSaveButton();

                        return(true);
                    }

                    // Submit changes to the PETRAServer
                    try
                    {
                        SubmissionResult = TRemote.MPartner.Partner.WebConnectors.SaveExtract
                                               (FExtractId, ref SubmitDT);
                    }
                    catch (System.Net.Sockets.SocketException)
                    {
                        FPetraUtilsObject.WriteToStatusBar("Data could not be saved!");
                        this.Cursor = Cursors.Default;
                        MessageBox.Show("The PETRA Server cannot be reached! Data cannot be saved!",
                                        "No Server response",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        bool ReturnValue = false;

                        // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return(ReturnValue);
                    }

                    /* TODO ESecurityDBTableAccessDeniedException
                     *                  catch (ESecurityDBTableAccessDeniedException Exp)
                     *                  {
                     *                      FPetraUtilsObject.WriteToStatusBar("Data could not be saved!");
                     *                      this.Cursor = Cursors.Default;
                     *                      // TODO TMessages.MsgSecurityException(Exp, this.GetType());
                     *                      bool ReturnValue = false;
                     *                      // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                     *                      return ReturnValue;
                     *                  }
                     */
                    catch (EDBConcurrencyException)
                    {
                        FPetraUtilsObject.WriteToStatusBar("Data could not be saved!");
                        this.Cursor = Cursors.Default;

                        // TODO TMessages.MsgDBConcurrencyException(Exp, this.GetType());
                        bool ReturnValue = false;

                        // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return(ReturnValue);
                    }
                    catch (Exception exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar("Data could not be saved!");
                        this.Cursor = Cursors.Default;
                        TLogging.Log(
                            Catalog.GetString(
                                "An error occurred while trying to connect to the OpenPetra Server!") + Environment.NewLine + exp.ToString(),
                            TLoggingType.ToLogfile);
                        MessageBox.Show(
                            Catalog.GetString("An error occurred while trying to connect to the OpenPetra Server!") + Environment.NewLine +
                            "For details see the log file: " + TLogging.GetLogFileName(),
                            "Server connection error",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);

                        // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return(false);
                    }

                    switch (SubmissionResult)
                    {
                    case TSubmitChangesResult.scrOK:

                        // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server
                        FMainDS.MExtract.AcceptChanges();

                        // Merge back with data from the Server (eg. for getting Sequence values)
                        FMainDS.MExtract.Merge(SubmitDT, false);

                        // need to accept the new modification ID
                        FMainDS.MExtract.AcceptChanges();

                        // Update UI
                        FPetraUtilsObject.WriteToStatusBar("Data successfully saved.");
                        this.Cursor = Cursors.Default;

                        // TODO EnableSave(false);

                        // We don't have unsaved changes anymore
                        FPetraUtilsObject.DisableSaveButton();

                        SetPrimaryKeyReadOnly(true);

                        // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return(true);

                    case TSubmitChangesResult.scrError:

                        // TODO scrError
                        this.Cursor = Cursors.Default;
                        break;

                    case TSubmitChangesResult.scrNothingToBeSaved:

                        // TODO scrNothingToBeSaved
                        this.Cursor = Cursors.Default;
                        return(true);

                    case TSubmitChangesResult.scrInfoNeeded:

                        // TODO scrInfoNeeded
                        this.Cursor = Cursors.Default;
                        break;
                    }
                }
            }

            return(false);
        }
コード例 #27
0
ファイル: ExtractMaster.cs プロジェクト: Davincier/openpetra
        public static Boolean CombineExtracts(String ANewExtractName,
            String ANewExtractDescription,
            List <Int32>ACombineExtractIdList,
            out Int32 ANewExtractId)
        {
            Boolean ResultValue = true;
            Boolean ExtractAlreadyExists = false;
            MExtractTable ExtractTable;
            MExtractTable CombinedExtractTable = new MExtractTable();
            MExtractRow TemplateRow;
            Int32 NewExtractId;

            NewExtractId = -1;

            TDBTransaction Transaction = null;
            bool SubmissionOK = false;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable,
                ref Transaction,
                ref SubmissionOK,
                delegate
                {
                    ResultValue = MPartner.Extracts.TExtractsHandling.CreateNewExtract(ANewExtractName,
                        ANewExtractDescription, out NewExtractId, out ExtractAlreadyExists);

                    if (ResultValue && !ExtractAlreadyExists)
                    {
                        // loop through each extract and combine them
                        foreach (Int32 ExtractId in ACombineExtractIdList)
                        {
                            ExtractTable = MExtractAccess.LoadViaMExtractMaster(ExtractId, Transaction);

                            foreach (DataRow ExtractRow in ExtractTable.Rows)
                            {
                                if (CombinedExtractTable.Rows.Find(new object[] { NewExtractId,
                                                                                  ((MExtractRow)ExtractRow).PartnerKey,
                                                                                  ((MExtractRow)ExtractRow).SiteKey }) == null)
                                {
                                    // create and add row to combined extract as it does not exist yet
                                    TemplateRow = (MExtractRow)CombinedExtractTable.NewRowTyped(true);
                                    TemplateRow.ExtractId = NewExtractId;
                                    TemplateRow.PartnerKey = ((MExtractRow)ExtractRow).PartnerKey;
                                    TemplateRow.SiteKey = ((MExtractRow)ExtractRow).SiteKey;
                                    TemplateRow.LocationKey = ((MExtractRow)ExtractRow).LocationKey;

                                    CombinedExtractTable.Rows.Add(TemplateRow);
                                }
                            }
                        }

                        // update key count in master table
                        MExtractMasterTable CombinedExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(NewExtractId, Transaction);
                        CombinedExtractMaster[0].KeyCount = CombinedExtractTable.Rows.Count;

                        // submit changes in master and then in extract content table which refers to it
                        MExtractAccess.SubmitChanges(CombinedExtractTable, Transaction);

                        MExtractMasterAccess.SubmitChanges(CombinedExtractMaster, Transaction);
                    }

                    SubmissionOK = true;
                });

            ResultValue = SubmissionOK;
            ANewExtractId = NewExtractId;

            return ResultValue;
        }
コード例 #28
0
        public static void GetData(string ATablename, TSearchCriteria[] ASearchCriteria, out TTypedDataTable AResultTable,
                                   TDBTransaction AReadTransaction)
        {
            AResultTable = null;
            string context = string.Format("GetData {0}", SharedConstants.MODULE_ACCESS_MANAGER);

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

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

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

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

            // Accept row changes here so that the Client gets 'unmodified' rows
            AResultTable.AcceptChanges();
        }
コード例 #29
0
ファイル: ExtractMaster.cs プロジェクト: Davincier/openpetra
        public static Boolean IntersectExtracts(String ANewExtractName,
            String ANewExtractDescription,
            List <Int32>AIntersectExtractIdList,
            out Int32 ANewExtractId)
        {
            Boolean ResultValue = true;
            Boolean ExtractAlreadyExists = false;
            Int32 ExtractIndex;
            MExtractTable FirstExtractTable;
            MExtractTable IntersectedExtractTable = new MExtractTable();
            MExtractRow TemplateRow;
            Boolean PartnerExistsInAllExtracts;
            Int32 NewExtractId;

            NewExtractId = -1;

            TDBTransaction Transaction = null;
            bool SubmissionOK = false;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable,
                ref Transaction,
                ref SubmissionOK,
                delegate
                {
                    ResultValue = MPartner.Extracts.TExtractsHandling.CreateNewExtract(ANewExtractName,
                        ANewExtractDescription, out NewExtractId, out ExtractAlreadyExists);

                    if (ResultValue && !ExtractAlreadyExists)
                    {
                        if (AIntersectExtractIdList.Count > 0)
                        {
                            FirstExtractTable = MExtractAccess.LoadViaMExtractMaster(AIntersectExtractIdList[0], Transaction);

                            // iterate through all partners in first extract and check if this record also exists in all other extracts
                            foreach (DataRow ExtractRow in FirstExtractTable.Rows)
                            {
                                PartnerExistsInAllExtracts = true;

                                // now check if this partner record exists in all other extracts as well
                                for (ExtractIndex = 1;
                                     ExtractIndex < AIntersectExtractIdList.Count && PartnerExistsInAllExtracts;
                                     ExtractIndex++)
                                {
                                    if (!MExtractAccess.Exists(AIntersectExtractIdList[ExtractIndex], ((MExtractRow)ExtractRow).PartnerKey,
                                            ((MExtractRow)ExtractRow).SiteKey, Transaction))
                                    {
                                        // can stop here as there is at least one extract where partner does not exist
                                        PartnerExistsInAllExtracts = false;
                                    }
                                }

                                // create and add row to intersected extract as it exists in all extracts
                                if (PartnerExistsInAllExtracts)
                                {
                                    TemplateRow = (MExtractRow)IntersectedExtractTable.NewRowTyped(true);
                                    TemplateRow.ExtractId = NewExtractId;
                                    TemplateRow.PartnerKey = ((MExtractRow)ExtractRow).PartnerKey;
                                    TemplateRow.SiteKey = ((MExtractRow)ExtractRow).SiteKey;
                                    TemplateRow.LocationKey = ((MExtractRow)ExtractRow).LocationKey;

                                    IntersectedExtractTable.Rows.Add(TemplateRow);
                                }
                            }
                        }

                        // update key count in master table
                        MExtractMasterTable IntersectedExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(NewExtractId, Transaction);
                        IntersectedExtractMaster[0].KeyCount = IntersectedExtractTable.Rows.Count;

                        // submit changes in master and then in extract content table which refers to it
                        MExtractAccess.SubmitChanges(IntersectedExtractTable, Transaction);

                        MExtractMasterAccess.SubmitChanges(IntersectedExtractMaster, Transaction);
                    }

                    SubmissionOK = true;
                });

            ResultValue = SubmissionOK;
            ANewExtractId = NewExtractId;

            return ResultValue;
        }
コード例 #30
0
ファイル: Extracts.cs プロジェクト: Davincier/openpetra
        /// <summary>
        /// extend an extract from a list of best addresses
        /// </summary>
        /// <param name="AExtractId">Extract Id of the Extract to extend</param>
        /// <param name="APartnerKeysTable"></param>
        /// <param name="APartnerKeyColumn">number of the column that contains the partner keys</param>
        /// <param name="ASiteKeyColumn">number of the column that contains the site keys</param>
        /// <param name="ALocationKeyColumn">number of the column that contains the location keys</param>
        /// <param name="AIgnoreDuplicates">true if duplicates should be looked out for. Can be set to false if called only once and not several times per extract.</param>
        public static void ExtendExtractFromListOfPartnerKeys(
            Int32 AExtractId,
            DataTable APartnerKeysTable,
            Int32 APartnerKeyColumn,
            Int32 ASiteKeyColumn,
            Int32 ALocationKeyColumn,
            bool AIgnoreDuplicates)
        {
            int RecordCounter = 0;
            PPartnerLocationTable PartnerLocationKeysTable;
            Int64 PartnerKey;

            TDBTransaction Transaction = null;
            bool SubmissionOK = true;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK,
                delegate
                {
                    MExtractTable ExtractTable = new MExtractTable();
                    ExtractTable = MExtractAccess.LoadViaMExtractMaster(AExtractId, Transaction);

                    // Location Keys need to be determined as extracts do not only need partner keys but
                    // also Location Keys.
                    DetermineBestLocationKeys(APartnerKeysTable, APartnerKeyColumn, ASiteKeyColumn,
                        ALocationKeyColumn, out PartnerLocationKeysTable,
                        Transaction);

                    // use the returned table which contains partner and location keys to build the extract
                    foreach (PPartnerLocationRow PartnerLocationRow in PartnerLocationKeysTable.Rows)
                    {
                        PartnerKey = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetPartnerKeyDBName()]);

                        if (PartnerKey > 0)
                        {
                            RecordCounter += 1;
                            TLogging.LogAtLevel(1, "Preparing Partner " + PartnerKey + " (Record Number " + RecordCounter + ")");

                            // add row for partner to extract and fill with contents
                            MExtractRow NewRow = ExtractTable.NewRowTyped();
                            NewRow.ExtractId = AExtractId;
                            NewRow.PartnerKey = PartnerKey;
                            NewRow.SiteKey = Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetSiteKeyDBName()]);
                            NewRow.LocationKey = Convert.ToInt32(PartnerLocationRow[PPartnerLocationTable.GetLocationKeyDBName()]);

                            // only add row if it does not already exist for this partner
                            if (AIgnoreDuplicates || !ExtractTable.Rows.Contains(new object[] { NewRow.ExtractId, NewRow.PartnerKey, NewRow.SiteKey }))
                            {
                                ExtractTable.Rows.Add(NewRow);
                            }
                        }
                    }

                    if (ExtractTable.Rows.Count > 0)
                    {
                        // update field in extract master for quick access to number of partners in extract
                        MExtractMasterTable ExtractMaster = MExtractMasterAccess.LoadByPrimaryKey(AExtractId, Transaction);
                        ExtractMaster[0].KeyCount = ExtractTable.Rows.Count;

                        ExtractTable.ThrowAwayAfterSubmitChanges = true; // no need to keep data as this increases speed significantly

                        MExtractAccess.SubmitChanges(ExtractTable, Transaction);

                        MExtractMasterAccess.SubmitChanges(ExtractMaster, Transaction);
                    }
                });
        }
コード例 #31
0
        /// <summary>
        /// save the changes on the screen (code is copied from auto-generated code)
        /// </summary>
        /// <returns></returns>
        public bool SaveChanges()
        {
            bool ReturnValue = false;

            FPetraUtilsObject.OnDataSavingStart(this, new System.EventArgs());

            if (FPetraUtilsObject.VerificationResultCollection.Count == 0)
            {
                foreach (DataRow InspectDR in FMainDS.MExtract.Rows)
                {
                    InspectDR.EndEdit();
                }

                if (!FPetraUtilsObject.HasChanges)
                {
                    return true;
                }
                else
                {
                    FPetraUtilsObject.WriteToStatusBar("Saving data...");
                    this.Cursor = Cursors.WaitCursor;

                    TSubmitChangesResult SubmissionResult;

                    //Ict.Common.Data.TTypedDataTable SubmitDT = FMainDS.MExtract.GetChangesTyped();
                    MExtractTable SubmitDT = new MExtractTable();
                    SubmitDT.Merge(FMainDS.MExtract.GetChangesTyped());

                    if (SubmitDT == null)
                    {
                        // There is nothing to be saved.
                        // Update UI
                        FPetraUtilsObject.WriteToStatusBar(Catalog.GetString("There is nothing to be saved."));
                        this.Cursor = Cursors.Default;

                        // We don't have unsaved changes anymore
                        FPetraUtilsObject.DisableSaveButton();

                        return true;
                    }

                    // Submit changes to the PETRAServer
                    try
                    {
                        SubmissionResult = TRemote.MPartner.Partner.WebConnectors.SaveExtract
                                               (FExtractId, ref SubmitDT);
                    }
                    catch (ESecurityDBTableAccessDeniedException Exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        TMessages.MsgSecurityException(Exp, this.GetType());

                        ReturnValue = false;
                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return ReturnValue;
                    }
                    catch (EDBConcurrencyException Exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        TMessages.MsgDBConcurrencyException(Exp, this.GetType());

                        ReturnValue = false;
                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return ReturnValue;
                    }
                    catch (Exception)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        throw;
                    }

                    switch (SubmissionResult)
                    {
                        case TSubmitChangesResult.scrOK:

                            // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server
                            FMainDS.MExtract.AcceptChanges();

                            // Merge back with data from the Server (eg. for getting Sequence values)
                            FMainDS.MExtract.Merge(SubmitDT, false);

                            // need to accept the new modification ID
                            FMainDS.MExtract.AcceptChanges();

                            // Update UI
                            FPetraUtilsObject.WriteToStatusBar("Data successfully saved.");
                            this.Cursor = Cursors.Default;

                            // TODO EnableSave(false);

                            // We don't have unsaved changes anymore
                            FPetraUtilsObject.DisableSaveButton();

                            SetPrimaryKeyReadOnly(true);

                            // refresh extract master screen if it is open
                            TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated);
                            BroadcastMessage.SetMessageDataName(ExtractName);
                            TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
                            this.Focus(); // keeps the focus on the current form

                            // TODO OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                            return true;

                        case TSubmitChangesResult.scrError:

                            // TODO scrError
                            this.Cursor = Cursors.Default;
                            break;

                        case TSubmitChangesResult.scrNothingToBeSaved:

                            // TODO scrNothingToBeSaved
                            this.Cursor = Cursors.Default;
                            return true;

                        case TSubmitChangesResult.scrInfoNeeded:

                            // TODO scrInfoNeeded
                            this.Cursor = Cursors.Default;
                            break;
                    }
                }
            }

            return false;
        }