public int CUDclientinfo(ClientRegistrationEntity clientinfo, char Operation)
        {
            Hashtable hashtable = new Hashtable();

            if (Operation == 'i')
            {
                hashtable.Add("@ClientRegistartionID", 0);
                hashtable.Add("@VerifiedBy", DBNull.Value);
                hashtable.Add("@VerifiedOn", DBNull.Value);
                hashtable.Add("@VerifiedThough", DBNull.Value);
                hashtable.Add("@Status", 1);
            }
            else
            {
                hashtable.Add("@ClientRegistartionID", clientinfo.ClientRegistartionID);
                hashtable.Add("@VerifiedBy", DBNull.Value);
                hashtable.Add("@VerifiedOn", DBNull.Value);
                hashtable.Add("@VerifiedThough", DBNull.Value);
                hashtable.Add("@Status", clientinfo.Status);
            }
            hashtable.Add("@SAID", clientinfo.SAID);
            hashtable.Add("@Title", clientinfo.Title);
            hashtable.Add("@FirstName", clientinfo.FirstName);
            hashtable.Add("@LastName", clientinfo.LastName);
            hashtable.Add("@EmailID", clientinfo.EmailID);
            hashtable.Add("@MobileNumber", clientinfo.MobileNumber);
            hashtable.Add("@Province", clientinfo.Province);
            hashtable.Add("@City", clientinfo.City);

            hashtable.Add("@Operation", Operation);

            DataUtilities dataUtilities = new DataUtilities();
            int           result        = dataUtilities.ExecuteNonQuery("ClientCRUD", hashtable);

            return(result);
        }
Example #2
0
        public void OutputCanvasCnvRelevantField()
        {
            var vcfLine = "1	9314201	Canvas:GAIN:1:9314202:9404148	N	<CNV>	36	PASS	SVTYPE=CNV;END=9404148;ensembl_gene_id=ENSG00000049239,ENSG00000252841,ENSG00000171621	RC:BC:CN:MCC	.	151:108:6:4";

            var annotatedVariant = DataUtilities.GetVariant(Resources.CacheGRCh37("ENST00000377403_chr1_Ensembl84"), null, vcfLine);

            Assert.NotNull(annotatedVariant);

            JsonUtilities.AlleleEquals(annotatedVariant,
                                       "{\"altAllele\":\"CNV\",\"refAllele\":\"N\",\"begin\":9314202,\"chromosome\":\"1\",\"end\":9404148,\"variantType\":\"copy_number_variation\",\"vid\":\"1:9314202:9404148:6\",\"overlappingGenes\":[\"H6PD\"],\"transcripts\":{\"ensembl\":[{\"transcript\":\"ENST00000377403.2\",\"bioType\":\"protein_coding\",\"exons\":\"4-5/5\",\"introns\":\"3-4/4\",\"geneId\":\"ENSG00000049239\",\"hgnc\":\"H6PD\",\"consequence\":[\"copy_number_increase\"],\"isCanonical\":true,\"proteinId\":\"ENSP00000366620.1\"}]}}");

            var cols = vcfLine.Split('\t');

            var extractor = new SampleFieldExtractor(cols);
            var samples   = extractor.ExtractSamples();

            Assert.Equal(2, samples.Count);

            var sample = samples[1];

            var observedCn = sample?.CopyNumber;

            Assert.Equal("6", observedCn);
        }
        public void SpliceVariants()
        {
            var sa = new SupplementaryAnnotationPosition(889158)
            {
                IsRefMinorAllele           = true,
                GlobalMajorAllele          = "G",
                GlobalMajorAlleleFrequency = "0.8239"
            };

            var saReader = new MockSupplementaryAnnotationReader(sa);

            var annotatedVariant = DataUtilities.GetVariant(Resources.CacheGRCh37("ENST00000327044_chr1_Ensembl84"), saReader,
                                                            "chr1	889158	.	C	.	1243.00	PASS	SNVSB=-130.5;SNVHPOL=3;CSQ=C|ENSG00000188976|ENST00000327044|Transcript|splice_region_variant&intron_variant|||||||CCDS3.1|ENST00000327044.6:c.888+4C>G|||YES|||ENSP00000317992|||8/18|NOC2L||||| GT:GQ:GQX:DP:DPF:AD     1/1:313:26:105:9:0,105");

            Assert.NotNull(annotatedVariant);
            Assert.Contains("\"isReferenceMinorAllele\":true", annotatedVariant.ToString());

            var transcriptAllele = annotatedVariant.AnnotatedAlternateAlleles.FirstOrDefault()?.EnsemblTranscripts.FirstOrDefault();

            Assert.NotNull(transcriptAllele);

            // ReSharper disable once PossibleNullReferenceException
            Assert.Equal("splice_region_variant&intron_variant", string.Join("&", transcriptAllele.Consequence));
        }
Example #4
0
        public void AnnotationCarryover()
        {
            var annotatedVariant = DataUtilities.GetVariant(DataUtilities.EmptyCachePrefix, Resources.MiniSuppAnnot("chr2_90472571_90472592.nsa"),
                                                            "2	90472571	.	AAAAAAAAAAAAAAAAAAGTCC	AGTCT	177	PASS	CIGAR=1M21D4I;RU=.;REFREP=.;IDREP=.	GT:GQ:GQX:DPI:AD	0/1:220:177:46:40,7");

            Assert.NotNull(annotatedVariant);

            var altAllele = JsonUtilities.GetFirstAlleleJson(annotatedVariant);

            Assert.NotNull(altAllele);

            Assert.Equal("{\"altAllele\":\"GTCT\",\"refAllele\":\"AAAAAAAAAAAAAAAAAGTCC\",\"begin\":90472572,\"chromosome\":\"2\",\"end\":90472592,\"variantType\":\"indel\",\"vid\":\"2:90472572:90472592:GTCT\"}", altAllele);

            var annotatedVariant2 = DataUtilities.GetVariant(DataUtilities.EmptyCachePrefix, Resources.MiniSuppAnnot("chr2_90472571_90472592.nsa"),
                                                             "2	90472592	.	C	.	.	PASS	RefMinor	GT:GQX:DP:DPF:AD	0:96:33:15:33");

            Assert.NotNull(annotatedVariant2);

            var altAllele2 = JsonUtilities.GetFirstAlleleJson(annotatedVariant2);

            Assert.NotNull(altAllele2);

            Assert.Equal("{\"refAllele\":\"C\",\"begin\":90472592,\"chromosome\":\"2\",\"end\":90472592,\"globalMinorAllele\":\"C\",\"gmaf\":0.006989,\"isReferenceMinorAllele\":true,\"variantType\":\"SNV\",\"vid\":\"2:90472592:C\"}", altAllele2);
        }
Example #5
0
        public static List <string> GetAutoCompleteData(string prefixText, int count)
        {
            const int     minPrefixLength = 3;
            List <string> valuesList      = new List <string>();

            if (prefixText.Length >= minPrefixLength)
            {
                try
                {
                    List <Drug_Information> drugs = EF_Data.GetDrugsInfoQuery(prefixText);

                    foreach (Drug_Information drug in drugs)
                    {
                        valuesList.Add(drug.Drug_Name_for_Pull_Down_Menu);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

            return(DataUtilities.FilterDropdownList(valuesList));
        }
Example #6
0
    protected void Chart_Vars_MSD() //(string div_name, int width, int height, string x1, string x2)
    {
        DataTable dt_vars = getData_Vars_MSD();

        AddGV(dt_vars);

        //DataTable dt_m1 = GetData("variable", "groupname", "mean");
        //DataTable dt_m2 = GetData("variable", "groupname", "n");

        //AddGV(dt_m1);
        //AddGV(dt_m2);

        //lblInfo.Text += "<br/><b>1</b>";
        //foreach (DataColumn c in dt_m1.Columns)
        //{
        //    lblInfo.Text += "<br/>" + c.ColumnName + " - " + c.DataType.ToString();
        //}

        //lblInfo.Text += "<br/><b>2</b>";
        //foreach (DataColumn c in dt_m2.Columns)
        //{
        //    lblInfo.Text += "<br/>" + c.ColumnName + " - " + c.DataType.ToString();
        //}

        ////dt_m1.Merge(dt_m2);
        //AddGV(dt_m1);


        foreach (DataColumn c in dt_vars.Columns)
        {
            lblInfo.Text += c.ColumnName + "...";
        }

        AddGV(DataUtilities.PivotLINQ(dt_vars, dt_vars.Columns[1], dt_vars.Columns[2], dt_vars.Columns[3]));
        AddGV(DataUtilities.PivotLINQ(dt_vars, dt_vars.Columns[1], dt_vars.Columns[3], dt_vars.Columns[2]));
    }
Example #7
0
 public OptionsParser(string options)
 {
     if (options == null)
     {
         throw new ArgumentNullException(nameof(options));
     }
     if (options.Length > 0)
     {
         string[] optionsArray = SplitAt(options, ";");
         foreach (string opt in optionsArray)
         {
             int index = opt.IndexOf('=');
             if (index < 0)
             {
                 throw new ArgumentException("Invalid options string: " +
                                             options);
             }
             string key = DataUtilities.ToLowerCaseAscii(opt.Substring(0,
                                                                       index));
             string value = opt.Substring(index + 1);
             this.dict[key] = value;
         }
     }
 }
Example #8
0
        public static bool GiftRevertAdjust(Hashtable requestParams, out TVerificationResultCollection AMessages)
        {
            AMessages = new TVerificationResultCollection();

            Int32   ALedgerNumber   = (Int32)requestParams["ALedgerNumber"];
            Boolean batchSelected   = (Boolean)requestParams["NewBatchSelected"];
            Int32   ANewBatchNumber = 0;

            bool TaxDeductiblePercentageEnabled = Convert.ToBoolean(
                TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, "FALSE"));

            if (batchSelected)
            {
                ANewBatchNumber = (Int32)requestParams["NewBatchNumber"];
            }

            String Function          = (String)requestParams["Function"];
            Int32  AGiftDetailNumber = (Int32)requestParams["GiftDetailNumber"];
            Int32  AGiftNumber       = (Int32)requestParams["GiftNumber"];
            Int32  ABatchNumber      = (Int32)requestParams["BatchNumber"];

            //decimal batchHashTotal = 0;
            decimal batchGiftTotal = 0;

            GiftBatchTDS   MainDS      = new GiftBatchTDS();
            TDBTransaction Transaction = null;
            DateTime       ADateEffective;

            Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

                AGiftBatchRow giftBatch;

                if (!batchSelected)
                {
                    ADateEffective = (DateTime)requestParams["GlEffectiveDate"];

                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, Transaction);

                    AGiftBatchRow oldGiftBatch = MainDS.AGiftBatch[0];
                    TGiftBatchFunctions.CreateANewGiftBatchRow(ref MainDS, ref Transaction, ref LedgerTable, ALedgerNumber, ADateEffective);
                    giftBatch = MainDS.AGiftBatch[1];
                    giftBatch.BankAccountCode     = oldGiftBatch.BankAccountCode;
                    giftBatch.BankCostCentre      = oldGiftBatch.BankCostCentre;
                    giftBatch.CurrencyCode        = oldGiftBatch.CurrencyCode;
                    giftBatch.ExchangeRateToBase  = oldGiftBatch.ExchangeRateToBase;
                    giftBatch.MethodOfPaymentCode = oldGiftBatch.MethodOfPaymentCode;
                    giftBatch.HashTotal           = 0;

                    if (giftBatch.MethodOfPaymentCode.Length == 0)
                    {
                        giftBatch.SetMethodOfPaymentCodeNull();
                    }

                    giftBatch.BankCostCentre = oldGiftBatch.BankCostCentre;
                    giftBatch.GiftType       = oldGiftBatch.GiftType;

                    if (Function.Equals("AdjustGift"))
                    {
                        giftBatch.BatchDescription = Catalog.GetString("Gift Adjustment");
                    }
                    else
                    {
                        giftBatch.BatchDescription = Catalog.GetString("Reverse Gift");
                    }
                }
                else
                {
                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ANewBatchNumber, Transaction);

                    giftBatch      = MainDS.AGiftBatch[0];
                    ADateEffective = giftBatch.GlEffectiveDate;
                    //If into an existing batch, then retrive the existing batch total
                    batchGiftTotal = giftBatch.BatchTotal;
                }

                if (Function.Equals("ReverseGiftBatch"))
                {
                    AGiftAccess.LoadViaAGiftBatch(MainDS, ALedgerNumber, ABatchNumber, Transaction);

                    foreach (AGiftRow gift in MainDS.AGift.Rows)
                    {
                        AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, gift.GiftTransactionNumber, Transaction);
                    }
                }
                else
                {
                    AGiftAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, Transaction);

                    if (Function.Equals("ReverseGiftDetail"))
                    {
                        AGiftDetailAccess.LoadByPrimaryKey(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, AGiftDetailNumber, Transaction);
                    }
                    else
                    {
                        AGiftDetailAccess.LoadViaAGift(MainDS, ALedgerNumber, ABatchNumber, AGiftNumber, Transaction);
                    }
                }

                //assuming new elements are added after these static borders

                int cycle = 0;

                MainDS.AGift.DefaultView.Sort = string.Format("{0}, {1}",
                                                              AGiftTable.GetBatchNumberDBName(),
                                                              AGiftTable.GetGiftTransactionNumberDBName());

                MainDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                    AGiftDetailTable.GetBatchNumberDBName(),
                                                                    AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                    AGiftDetailTable.GetDetailNumberDBName());

                do
                {
                    foreach (DataRowView giftRow in MainDS.AGift.DefaultView)
                    {
                        AGiftRow oldGift = (AGiftRow)giftRow.Row;

                        if ((oldGift.BatchNumber == ABatchNumber) && (oldGift.LedgerNumber == ALedgerNumber) &&
                            (Function.Equals("ReverseGiftBatch") || (oldGift.GiftTransactionNumber == AGiftNumber)))
                        {
                            AGiftRow gift = MainDS.AGift.NewRowTyped(true);
                            DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift);
                            gift.LedgerNumber          = giftBatch.LedgerNumber;
                            gift.BatchNumber           = giftBatch.BatchNumber;
                            gift.DateEntered           = ADateEffective;
                            gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                            giftBatch.LastGiftNumber++;
                            gift.LastDetailNumber = 0;

                            MainDS.AGift.Rows.Add(gift);

                            foreach (DataRowView giftDetailRow in MainDS.AGiftDetail.DefaultView)
                            {
                                AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row;

                                if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) &&
                                    (oldGiftDetail.BatchNumber == ABatchNumber) &&
                                    (oldGiftDetail.LedgerNumber == ALedgerNumber) &&
                                    (!Function.Equals("ReverseGiftDetail") || (oldGiftDetail.DetailNumber == AGiftDetailNumber)))
                                {
                                    if ((cycle == 0) && oldGiftDetail.ModifiedDetail)
                                    {
                                        AMessages.Add(new TVerificationResult(
                                                          String.Format(Catalog.GetString("Cannot reverse or adjust Gift {0} with Detail {1} in Batch {2}"),
                                                                        oldGiftDetail.GiftTransactionNumber, oldGiftDetail.DetailNumber, oldGiftDetail.BatchNumber),
                                                          String.Format(Catalog.GetString("It was already adjusted or reversed.")),
                                                          TResultSeverity.Resv_Critical));

                                        DBAccess.GDBAccessObj.RollbackTransaction();

                                        return(false);
                                    }

                                    AGiftDetailRow giftDetail = MainDS.AGiftDetail.NewRowTyped(true);
                                    DataUtilities.CopyAllColumnValuesWithoutPK(oldGiftDetail, giftDetail);

                                    giftDetail.DetailNumber = ++gift.LastDetailNumber;

                                    giftDetail.LedgerNumber          = gift.LedgerNumber;
                                    giftDetail.BatchNumber           = giftBatch.BatchNumber;
                                    giftDetail.GiftTransactionNumber = gift.GiftTransactionNumber;
                                    //Identify the reversal source
                                    giftDetail.ModifiedDetailKey = "|" + oldGiftDetail.BatchNumber.ToString() + "|" +
                                                                   oldGiftDetail.GiftTransactionNumber.ToString() + "|" +
                                                                   oldGiftDetail.DetailNumber.ToString();

                                    decimal signum = (cycle == 0) ? -1 : 1;
                                    giftDetail.GiftTransactionAmount = signum * oldGiftDetail.GiftTransactionAmount;
                                    batchGiftTotal           += giftDetail.GiftTransactionAmount;
                                    giftDetail.GiftAmount     = signum * oldGiftDetail.GiftAmount;
                                    giftDetail.GiftAmountIntl = signum * oldGiftDetail.GiftAmountIntl;

                                    if (TaxDeductiblePercentageEnabled)
                                    {
                                        giftDetail.TaxDeductibleAmount     = signum * oldGiftDetail.TaxDeductibleAmount;
                                        giftDetail.TaxDeductibleAmountBase = signum * oldGiftDetail.TaxDeductibleAmountBase;
                                        giftDetail.TaxDeductibleAmountIntl = signum * oldGiftDetail.TaxDeductibleAmountIntl;
                                        giftDetail.NonDeductibleAmount     = signum * oldGiftDetail.NonDeductibleAmount;
                                        giftDetail.NonDeductibleAmountBase = signum * oldGiftDetail.NonDeductibleAmountBase;
                                        giftDetail.NonDeductibleAmountIntl = signum * oldGiftDetail.NonDeductibleAmountIntl;
                                    }

                                    giftDetail.GiftCommentOne   = (String)requestParams["ReversalCommentOne"];
                                    giftDetail.GiftCommentTwo   = (String)requestParams["ReversalCommentTwo"];
                                    giftDetail.GiftCommentThree = (String)requestParams["ReversalCommentThree"];
                                    giftDetail.CommentOneType   = (String)requestParams["ReversalCommentOneType"];
                                    giftDetail.CommentTwoType   = (String)requestParams["ReversalCommentTwoType"];
                                    giftDetail.CommentThreeType = (String)requestParams["ReversalCommentThreeType"];

                                    // This is used to mark both as a Reverted giftDetails, except the adjusted (new) gift

                                    giftDetail.ModifiedDetail    = (cycle == 0);
                                    oldGiftDetail.ModifiedDetail = (cycle == 0);
                                    MainDS.AGiftDetail.Rows.Add(giftDetail);
                                }
                            }
                        }
                    }

                    cycle++;
                } while ((cycle < 2) && Function.Equals("AdjustGift"));

                //When reversing into a new or existing batch, set batch total
                if (!Function.Equals("AdjustGift"))
                {
                    giftBatch.BatchTotal = batchGiftTotal;
                }

                // save everything at the end
                AGiftBatchAccess.SubmitChanges(MainDS.AGiftBatch, Transaction);

                ALedgerAccess.SubmitChanges(LedgerTable, Transaction);

                AGiftAccess.SubmitChanges(MainDS.AGift, Transaction);

                AGiftDetailAccess.SubmitChanges(MainDS.AGiftDetail, Transaction);

                MainDS.AGiftBatch.AcceptChanges();

                DBAccess.GDBAccessObj.CommitTransaction();

                return(true);
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured while performing Gift Reverse/Adjust:" + Environment.NewLine + Exc.ToString());

                DBAccess.GDBAccessObj.RollbackTransaction();

                throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), Exc);
            }
        }
        // We have to have our own handler for the delete button because we need to check references
        //  while making an allowance for any reference to PDataLabelUse.
        // All the UsedBy checkboxes are backed by the PdataLLabel Use table so we know that these references exist.
        // The DeleteRecordManual method test for reference conflicts but allows for PDataLabelUse.
        // If all is ok it calls the standard code, which does NOT check for conflicts.
        private void DeleteRecordManual(Object sender, EventArgs e)
        {
            if ((FPreviouslySelectedDetailRow == null) || (FPrevRowChangedRow == -1))
            {
                return;
            }

            DataRowView[] HighlightedRows = grdDetails.SelectedDataRowsAsDataRowView;

            if ((HighlightedRows.Length == 1) && (!TVerificationHelper.IsNullOrOnlyNonCritical(FPetraUtilsObject.VerificationResultCollection)))
            {
                // If we only have 1 row highlighted and it has validation errors we can quit because the standard code will work fine
                return;
            }

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

            this.Cursor = Cursors.WaitCursor;

            foreach (DataRowView rv in HighlightedRows)
            {
                TVerificationResultCollection VerificationResults = null;

                // Get the number of references for the row, and the number of rows in PDataLabelUse
                int NumReferences = TRemote.MCommon.ReferenceCount.WebConnectors.GetCacheableRecordReferenceCount(
                    "DataLabelList",
                    DataUtilities.GetPKValuesFromDataRow(rv.Row),
                    FPetraUtilsObject.MaxReferenceCountOnDelete,
                    out VerificationResults);
                int NumDataLabelUses = rv.Row[UsedByColumnOrdinal].ToString().Split(new char[] { ',' }).Length;

                // If there are more references we need to build a message and add it to our list
                if ((NumReferences > NumDataLabelUses) && (VerificationResults != null) && (VerificationResults.Count > 0))
                {
                    string groupName = rv.Row[FMainDS.PDataLabel.ColumnGroup].ToString();
                    string labelName = rv.Row[FMainDS.PDataLabel.ColumnText].ToString();
                    string strRowID  = groupName;

                    if (strRowID != String.Empty)
                    {
                        strRowID += " - ";
                    }

                    strRowID += labelName;

                    string msg = Messages.BuildMessageFromVerificationResult(
                        String.Format(
                            Catalog.GetString("The record '{0}' cannot be deleted!{1}{2}"),
                            strRowID,
                            Environment.NewLine,
                            Catalog.GetPluralString("Reason:", "Reasons:", VerificationResults.Count)),
                        VerificationResults);
                    msg += Catalog.GetString(
                        "You can ignore the references to the 'Data Label Use' table.  They will be removed automatically.  But you must resolve the other references before this row can be deleted.");

                    listConflicts.Add(msg);
                }
            }

            this.Cursor = Cursors.Default;

            // Did we get any conflicts?
            for (int i = 0; i < listConflicts.Count; i++)
            {
                if (i < listConflicts.Count - 1)
                {
                    // There is another one to show after this so include a chance for the user to quit...
                    if (MessageBox.Show(listConflicts[i] + Environment.NewLine + Environment.NewLine + "Do you want to see the next conflict?",
                                        Catalog.GetString("Record Deletion"), MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                    {
                        break;
                    }
                }
                else
                {
                    MessageBox.Show(listConflicts[i], Catalog.GetString("Record Deletion"));
                }
            }

            if (listConflicts.Count == 0)
            {
                // All OK to delete the highlighted row(s) so call the standard method
                DeletePDataLabel();
            }
        }
        /// <summary>
        /// Standard method to delete the Data Row whose Details are currently displayed.
        /// There is full support for multi-row deletion.
        /// Optional manual code can be included to take action prior, during or after each deletion.
        /// When the row(s) have been deleted the highlighted row index stays the same unless the deleted row was the last one.
        /// The Details for the newly highlighted row are automatically displayed - or not, if the grid has now become empty.
        /// </summary>
        private void DeletePPostcodeRegionRange()
        {
            string CompletionMessage = String.Empty;

            if ((FPreviouslySelectedRangeRow == null) || (FPrevRangeRowChangedRow == -1))
            {
                return;
            }

            DataRowView[] HighlightedRows = grdRanges.SelectedDataRowsAsDataRowView;

            if (HighlightedRows.Length == 1)
            {
                TVerificationResultCollection VerificationResults = null;

                if (TVerificationHelper.IsNullOrOnlyNonCritical(FPetraUtilsObject.VerificationResultCollection))
                {
                    this.Cursor = Cursors.WaitCursor;
                    TRemote.MPartner.ReferenceCount.WebConnectors.GetNonCacheableRecordReferenceCount(
                        FMainDS.PPostcodeRegionRange,
                        DataUtilities.GetPKValuesFromDataRow(FPreviouslySelectedRangeRow),
                        FPetraUtilsObject.MaxReferenceCountOnDelete,
                        out VerificationResults);
                    this.Cursor = Cursors.Default;
                }

                if ((VerificationResults != null) &&
                    (VerificationResults.Count > 0))
                {
                    MessageBox.Show(Messages.BuildMessageFromVerificationResult(
                                        Catalog.GetString("Record cannot be deleted!") +
                                        Environment.NewLine +
                                        Catalog.GetPluralString("Reason:", "Reasons:", VerificationResults.Count),
                                        VerificationResults),
                                    Catalog.GetString("Record Deletion"));
                    return;
                }

                string DeletionQuestion = Catalog.GetString("Are you sure you want to delete the current row?");

                if ((FPrimaryKeyControl != null) && (FPrimaryKeyLabel != null))
                {
                    DeletionQuestion += String.Format("{0}{0}({1} {2})",
                                                      Environment.NewLine,
                                                      "Range Name:",
                                                      FPreviouslySelectedRangeRow.Range);
                }

                bool AllowDeletion     = true;
                bool DeletionPerformed = false;

                if (AllowDeletion)
                {
                    if ((MessageBox.Show(DeletionQuestion,
                                         Catalog.GetString("Confirm Delete"),
                                         MessageBoxButtons.YesNo,
                                         MessageBoxIcon.Question,
                                         MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes))
                    {
                        try
                        {
                            FPreviouslySelectedRangeRow.Delete();
                            DeletionPerformed = true;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(String.Format(Catalog.GetString("An error occurred while deleting this record.{0}{0}{1}"),
                                                          Environment.NewLine, ex.Message),
                                            Catalog.GetString("Error"),
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                        }

                        if (DeletionPerformed)
                        {
                            FPetraUtilsObject.SetChangedFlag();
                        }

                        // Select and display the details of the nearest row to the one previously selected
                        grdRanges.SelectRowInGrid(FPrevRangeRowChangedRow, true);

                        // Clear any errors left over from  the deleted row
                        FPetraUtilsObject.VerificationResultCollection.Clear();
                    }
                }

                if (DeletionPerformed && (CompletionMessage.Length > 0))
                {
                    MessageBox.Show(CompletionMessage,
                                    Catalog.GetString("Deletion Completed"));
                }
            }
            else
            {
                string DeletionQuestion = String.Format(Catalog.GetString(
                                                            "Do you want to delete the {0} highlighted rows?{1}{1}"), HighlightedRows.Length, Environment.NewLine);
                DeletionQuestion += Catalog.GetString("Each record will be checked to confirm that it can be deleted.");

                if (MessageBox.Show(DeletionQuestion,
                                    Catalog.GetString("Confirm Delete"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    int recordsDeleted                       = 0;
                    int recordsUndeletable                   = 0;
                    int recordsDeleteDisallowed              = 0;
                    List <TMultiDeleteResult> listConflicts  = new List <TMultiDeleteResult>();
                    List <TMultiDeleteResult> listExceptions = new List <TMultiDeleteResult>();

                    this.Cursor = Cursors.WaitCursor;

                    foreach (DataRowView drv in HighlightedRows)
                    {
                        PPostcodeRegionRangeRow rowToDelete = (PPostcodeRegionRangeRow)(drv.Row);
                        string rowDetails = MakePKValuesStringManual(rowToDelete);

                        TVerificationResultCollection VerificationResults = null;
                        TRemote.MPartner.ReferenceCount.WebConnectors.GetNonCacheableRecordReferenceCount(
                            FMainDS.PPostcodeRegionRange,
                            DataUtilities.GetPKValuesFromDataRow(rowToDelete),
                            FPetraUtilsObject.MaxReferenceCountOnDelete,
                            out VerificationResults);

                        if ((VerificationResults != null) && (VerificationResults.Count > 0))
                        {
                            TMultiDeleteResult result = new TMultiDeleteResult(rowDetails,
                                                                               Messages.BuildMessageFromVerificationResult(String.Empty, VerificationResults));
                            listConflicts.Add(result);
                            continue;
                        }

                        bool AllowDeletion     = true;
                        bool DeletionPerformed = false;

                        if (AllowDeletion)
                        {
                            try
                            {
                                rowToDelete.Delete();
                                DeletionPerformed = true;
                            }
                            catch (Exception ex)
                            {
                                TMultiDeleteResult result = new TMultiDeleteResult(rowDetails, ex.Message);
                                listExceptions.Add(result);
                            }
                        }
                        else
                        {
                            recordsDeleteDisallowed++;
                        }

                        if (DeletionPerformed)
                        {
                            FPetraUtilsObject.SetChangedFlag();
                            recordsDeleted++;
                        }
                    }

                    this.Cursor = Cursors.Default;

                    // Select and display the details of the nearest row to the one previously selected
                    grdRanges.SelectRowInGrid(FPrevRangeRowChangedRow, true);

                    if ((recordsDeleted > 0) && (CompletionMessage.Length > 0))
                    {
                        MessageBox.Show(CompletionMessage,
                                        Catalog.GetString("Deletion Completed"));
                    }

                    //  Show the results of the multi-deletion
                    string results = null;

                    if (recordsDeleted > 0)
                    {
                        string s1 = Catalog.GetPluralString("record", "records", recordsDeleted);
                        string s2 = Catalog.GetPluralString("was", "were", recordsDeleted);
                        results = String.Format(Catalog.GetString("{0} {1} {2} successfully deleted."), recordsDeleted, s1, s2);
                    }
                    else
                    {
                        results = "No records were deleted.";
                    }

                    if (recordsUndeletable > 0)
                    {
                        string s1 = Catalog.GetPluralString("record", "records", recordsUndeletable);
                        string s2 = Catalog.GetPluralString("it is marked", "they are marked", recordsUndeletable);
                        results += String.Format(Catalog.GetString("{0}{1} {2} could not be deleted because {3} as non-deletable."),
                                                 Environment.NewLine,
                                                 recordsUndeletable,
                                                 s1, s2);
                    }

                    if (recordsDeleteDisallowed > 0)
                    {
                        string s1 = Catalog.GetPluralString("record was not be deleted", "records were not be deleted", recordsUndeletable);
                        results += String.Format(Catalog.GetString("{0}{1} {2} because deletion was not allowed."),
                                                 Environment.NewLine,
                                                 recordsDeleteDisallowed,
                                                 s1);
                    }

                    bool showCancel = false;

                    if (listConflicts.Count > 0)
                    {
                        showCancel = true;
                        string s1 = Catalog.GetPluralString("record", "records", listConflicts.Count);
                        string s2 = Catalog.GetPluralString("it is referenced", "they are referenced", listConflicts.Count);
                        results += String.Format(Catalog.GetString("{0}{1} {2} could not be deleted because {3} by at least one other table."),
                                                 Environment.NewLine,
                                                 listConflicts.Count,
                                                 s1, s2);
                    }

                    if (listExceptions.Count > 0)
                    {
                        showCancel = true;
                        string s1 = Catalog.GetPluralString("record", "records", listExceptions.Count);
                        results += String.Format(Catalog.GetString("{0}{1} {2} could not be deleted because the delete action failed unexpectedly."),
                                                 Environment.NewLine,
                                                 listExceptions.Count,
                                                 s1);
                    }

                    if (showCancel)
                    {
                        results +=
                            String.Format(Catalog.GetString("{0}{0}Click OK to review the details, or Cancel to return direct to the data screen"),
                                          Environment.NewLine);

                        if (MessageBox.Show(results,
                                            Catalog.GetString("Delete Action Summary"),
                                            MessageBoxButtons.OKCancel,
                                            MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
                        {
                            ReviewMultiDeleteResults(listConflicts, Catalog.GetString("Rows in this table that are referenced by other tables"));
                            ReviewMultiDeleteResults(listExceptions, Catalog.GetString("Unexpected Exceptions"));
                        }
                    }
                    else
                    {
                        MessageBox.Show(results,
                                        Catalog.GetString("Delete Action Summary"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }
            }
        }
Example #11
0
        public static bool SavePartner(PartnerEditTDS AMainDS,
                                       List <string> ASubscriptions,
                                       List <string> APartnerTypes,
                                       bool ASendMail,
                                       string ADefaultEmailAddress,
                                       string ADefaultPhoneMobile,
                                       string ADefaultPhoneLandline,
                                       out TVerificationResultCollection AVerificationResult)
        {
            List <string>  Dummy1, Dummy2;
            string         Dummy3, Dummy4, Dummy5;
            PartnerEditTDS SaveDS;

            AVerificationResult = new TVerificationResultCollection();

            if (AMainDS.PPartner[0].ModificationId == DateTime.MinValue)
            {
                // this is a new partner
                SaveDS = AMainDS;

                if (SaveDS.PPartner[0].PartnerKey == -1)
                {
                    SaveDS.PPartner[0].PartnerKey = NewPartnerKey();
                }

                if (SaveDS.PFamily.Count > 0)
                {
                    SaveDS.PFamily[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.PPerson.Count > 0)
                {
                    SaveDS.PPerson[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.PChurch.Count > 0)
                {
                    SaveDS.PChurch[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.POrganisation.Count > 0)
                {
                    SaveDS.POrganisation[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }

                PPartnerLocationRow partnerlocation = SaveDS.PPartnerLocation.NewRowTyped();
                partnerlocation.PartnerKey  = SaveDS.PPartner[0].PartnerKey;
                partnerlocation.LocationKey = SaveDS.PLocation[0].LocationKey;
                partnerlocation.SiteKey     = SaveDS.PLocation[0].SiteKey;
                partnerlocation.SendMail    = ASendMail;
                SaveDS.PPartnerLocation.Rows.Add(partnerlocation);
            }
            else
            {
                SaveDS = GetPartnerDetails(AMainDS.PPartner[0].PartnerKey, out Dummy1, out Dummy2, out Dummy3, out Dummy4, out Dummy5);
                DataUtilities.CopyDataSet(AMainDS, SaveDS);
            }

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

            foreach (PPartnerTypeRow partnertype in SaveDS.PPartnerType.Rows)
            {
                if (!APartnerTypes.Contains(partnertype.TypeCode))
                {
                    partnertype.Delete();
                }
                else
                {
                    ExistingPartnerTypes.Add(partnertype.TypeCode);
                }
            }

            // add new partner types
            foreach (string partnertype in APartnerTypes)
            {
                if (!ExistingPartnerTypes.Contains(partnertype))
                {
                    PPartnerTypeRow partnertypeRow = SaveDS.PPartnerType.NewRowTyped();
                    partnertypeRow.PartnerKey = AMainDS.PPartner[0].PartnerKey;
                    partnertypeRow.TypeCode   = partnertype;
                    SaveDS.PPartnerType.Rows.Add(partnertypeRow);
                }
            }

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

            foreach (PSubscriptionRow subscription in SaveDS.PSubscription.Rows)
            {
                if (!ASubscriptions.Contains(subscription.PublicationCode))
                {
                    subscription.Delete();
                }
                else
                {
                    ExistingSubscriptions.Add(subscription.PublicationCode);
                }
            }

            // add new subscriptions
            foreach (string subscription in ASubscriptions)
            {
                if (!ExistingSubscriptions.Contains(subscription))
                {
                    PSubscriptionRow subscriptionRow = SaveDS.PSubscription.NewRowTyped();
                    subscriptionRow.PartnerKey          = AMainDS.PPartner[0].PartnerKey;
                    subscriptionRow.PublicationCode     = subscription;
                    subscriptionRow.ReasonSubsGivenCode = "FREE";
                    SaveDS.PSubscription.Rows.Add(subscriptionRow);
                }
            }

            bool foundDefaultEmailAddress   = false;
            bool foundDefaultPhoneLandLine  = false;
            bool foundDefaultMobileLandLine = false;

            foreach (PPartnerAttributeRow partnerattr in SaveDS.PPartnerAttribute.Rows)
            {
                if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_EMAIL)
                {
                    partnerattr.Value        = ADefaultEmailAddress;
                    foundDefaultEmailAddress = true;
                }
                else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_PHONE)
                {
                    partnerattr.Value         = ADefaultPhoneLandline;
                    foundDefaultPhoneLandLine = true;
                }
                else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_MOBILE_PHONE)
                {
                    partnerattr.Value          = ADefaultPhoneMobile;
                    foundDefaultMobileLandLine = true;
                }
            }

            if (!foundDefaultEmailAddress)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_EMAIL;
                partnerattr.Value         = ADefaultEmailAddress;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            if (!foundDefaultPhoneLandLine)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_PHONE;
                partnerattr.Value         = ADefaultPhoneLandline;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            if (!foundDefaultMobileLandLine)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_MOBILE_PHONE;
                partnerattr.Value         = ADefaultPhoneMobile;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            // TODO: either reuse Partner Edit UIConnector
            // or check for changed partner key, or changed Partner Class, etc.

            // set Partner Short Name
            if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_PERSON)
            {
                SaveDS.PPartner[0].PartnerShortName =
                    Calculations.DeterminePartnerShortName(
                        SaveDS.PPerson[0].FamilyName,
                        SaveDS.PPerson[0].Title,
                        SaveDS.PPerson[0].FirstName,
                        SaveDS.PPerson[0].MiddleName1);
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY)
            {
                SaveDS.PPartner[0].PartnerShortName =
                    Calculations.DeterminePartnerShortName(
                        SaveDS.PFamily[0].FamilyName,
                        SaveDS.PFamily[0].Title,
                        SaveDS.PFamily[0].FirstName);
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_UNIT)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.PUnit[0].UnitName;
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.POrganisation[0].OrganisationName;
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_BANK)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.PBank[0].BranchName;
            }

            // TODO: check if location 0 (no address) was changed. we don't want to overwrite that
            // alternative: check if somebody else uses that location, and split the locations. or ask if others should be updated???
            if (SaveDS.PLocation[0].RowState == DataRowState.Modified && SaveDS.PLocation[0].LocationKey == 0)
            {
                TLogging.Log("we cannot update addresses of people with location 0");
                AVerificationResult.Add(new TVerificationResult("error", "we cannot update addresses of people with location 0", TResultSeverity.Resv_Critical));
                return(false);
            }

            DataSet ResponseDS = new PartnerEditTDS();
            TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(SaveDS.PPartner[0].PartnerKey);

            try
            {
                TSubmitChangesResult result = uiconnector.SubmitChanges(
                    ref SaveDS,
                    ref ResponseDS,
                    out AVerificationResult);
                return(result == TSubmitChangesResult.scrOK);
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                return(false);
            }
        }
Example #12
0
        public static bool SavePartner(PartnerEditTDS AMainDS,
                                       List <string> ASubscriptions,
                                       List <string> APartnerTypes,
                                       bool ASendMail,
                                       string ADefaultEmailAddress,
                                       string ADefaultPhoneMobile,
                                       string ADefaultPhoneLandline,
                                       out TVerificationResultCollection AVerificationResult)
        {
            List <string>  Dummy1, Dummy2;
            string         Dummy3, Dummy4, Dummy5;
            PartnerEditTDS SaveDS;

            AVerificationResult = new TVerificationResultCollection();

            if (AMainDS.PPartner[0].ModificationId == DateTime.MinValue)
            {
                // this is a new partner
                SaveDS = AMainDS;

                if (SaveDS.PPartner[0].PartnerKey == -1)
                {
                    SaveDS.PPartner[0].PartnerKey = NewPartnerKey();
                }

                if (SaveDS.PFamily.Count > 0)
                {
                    SaveDS.PFamily[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.PPerson.Count > 0)
                {
                    SaveDS.PPerson[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.PChurch.Count > 0)
                {
                    SaveDS.PChurch[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.POrganisation.Count > 0)
                {
                    SaveDS.POrganisation[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }

                PPartnerLocationRow partnerlocation = SaveDS.PPartnerLocation.NewRowTyped();
                partnerlocation.PartnerKey  = SaveDS.PPartner[0].PartnerKey;
                partnerlocation.LocationKey = SaveDS.PLocation[0].LocationKey;
                partnerlocation.SiteKey     = SaveDS.PLocation[0].SiteKey;
                partnerlocation.SendMail    = ASendMail;
                SaveDS.PPartnerLocation.Rows.Add(partnerlocation);
            }
            else
            {
                SaveDS = GetPartnerDetails(AMainDS.PPartner[0].PartnerKey, out Dummy1, out Dummy2, out Dummy3, out Dummy4, out Dummy5);
                DataUtilities.CopyDataSet(AMainDS, SaveDS);
            }

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

            foreach (PPartnerTypeRow partnertype in SaveDS.PPartnerType.Rows)
            {
                if (!APartnerTypes.Contains(partnertype.TypeCode))
                {
                    partnertype.Delete();
                }
                else
                {
                    ExistingPartnerTypes.Add(partnertype.TypeCode);
                }
            }

            // add new partner types
            foreach (string partnertype in APartnerTypes)
            {
                if (!ExistingPartnerTypes.Contains(partnertype))
                {
                    PPartnerTypeRow partnertypeRow = SaveDS.PPartnerType.NewRowTyped();
                    partnertypeRow.PartnerKey = AMainDS.PPartner[0].PartnerKey;
                    partnertypeRow.TypeCode   = partnertype;
                    SaveDS.PPartnerType.Rows.Add(partnertypeRow);
                }
            }

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

            foreach (PSubscriptionRow subscription in SaveDS.PSubscription.Rows)
            {
                if (!ASubscriptions.Contains(subscription.PublicationCode))
                {
                    subscription.Delete();
                }
                else
                {
                    ExistingSubscriptions.Add(subscription.PublicationCode);
                }
            }

            // add new subscriptions
            foreach (string subscription in ASubscriptions)
            {
                if (!ExistingSubscriptions.Contains(subscription))
                {
                    PSubscriptionRow subscriptionRow = SaveDS.PSubscription.NewRowTyped();
                    subscriptionRow.PartnerKey          = AMainDS.PPartner[0].PartnerKey;
                    subscriptionRow.PublicationCode     = subscription;
                    subscriptionRow.ReasonSubsGivenCode = "FREE";
                    SaveDS.PSubscription.Rows.Add(subscriptionRow);
                }
            }

            bool foundDefaultEmailAddress   = false;
            bool foundDefaultPhoneLandLine  = false;
            bool foundDefaultMobileLandLine = false;

            foreach (PPartnerAttributeRow partnerattr in SaveDS.PPartnerAttribute.Rows)
            {
                if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_EMAIL)
                {
                    partnerattr.Value        = ADefaultEmailAddress;
                    foundDefaultEmailAddress = true;
                }
                else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_PHONE)
                {
                    partnerattr.Value         = ADefaultPhoneLandline;
                    foundDefaultPhoneLandLine = true;
                }
                else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_MOBILE_PHONE)
                {
                    partnerattr.Value          = ADefaultPhoneMobile;
                    foundDefaultMobileLandLine = true;
                }
            }

            if (!foundDefaultEmailAddress)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_EMAIL;
                partnerattr.Value         = ADefaultEmailAddress;
                partnerattr.Index         = 0;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            if (!foundDefaultPhoneLandLine)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_PHONE;
                partnerattr.Value         = ADefaultPhoneLandline;
                partnerattr.Index         = 0;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            if (!foundDefaultMobileLandLine)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_MOBILE_PHONE;
                partnerattr.Value         = ADefaultPhoneMobile;
                partnerattr.Index         = 0;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            // TODO: either reuse Partner Edit UIConnector
            // or check for changed partner key, or changed Partner Class, etc.

            // set Partner Short Name
            if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_PERSON)
            {
                SaveDS.PPartner[0].PartnerShortName =
                    Calculations.DeterminePartnerShortName(
                        SaveDS.PPerson[0].FamilyName,
                        SaveDS.PPerson[0].Title,
                        SaveDS.PPerson[0].FirstName,
                        SaveDS.PPerson[0].MiddleName1);
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY)
            {
                // check if we have a valid family name
                if (SaveDS.PFamily[0].FamilyName.Trim().Length == 0)
                {
                    AVerificationResult.Add(new TVerificationResult("error", "Please specify the family name", "",
                                                                    "MaintainPartners.ErrMissingFamilyName", TResultSeverity.Resv_Critical));
                    return(false);
                }

                // check if we have a valid title
                if (SaveDS.PFamily[0].Title.Trim().Length == 0)
                {
                    AVerificationResult.Add(new TVerificationResult("error", "Please specify the title", "",
                                                                    "MaintainPartners.ErrMissingTitle", TResultSeverity.Resv_Critical));
                    return(false);
                }

                SaveDS.PPartner[0].PartnerShortName =
                    Calculations.DeterminePartnerShortName(
                        SaveDS.PFamily[0].FamilyName,
                        SaveDS.PFamily[0].Title,
                        SaveDS.PFamily[0].FirstName);
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_UNIT)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.PUnit[0].UnitName;
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION)
            {
                // check if we have a valid organisation name
                if (SaveDS.POrganisation[0].OrganisationName.Trim().Length == 0)
                {
                    AVerificationResult.Add(new TVerificationResult("error", "Please specify the organisation name", "",
                                                                    "MaintainPartners.ErrMissingOrganisationName", TResultSeverity.Resv_Critical));
                    return(false);
                }

                SaveDS.PPartner[0].PartnerShortName = SaveDS.POrganisation[0].OrganisationName;
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_BANK)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.PBank[0].BranchName;
            }

            // change legacy addresses. create a new separate location for each partner
            if (SaveDS.PLocation[0].LocationKey == 0)
            {
                PLocationRow location = SaveDS.PLocation.NewRowTyped();
                DataUtilities.CopyAllColumnValues(SaveDS.PLocation[0], location);
                location.SiteKey     = DomainManager.GSiteKey;
                location.LocationKey = -1;
                SaveDS.PLocation.Rows.Clear();
                SaveDS.PLocation.Rows.Add(location);

                PPartnerLocationRow plocation = SaveDS.PPartnerLocation.NewRowTyped();
                DataUtilities.CopyAllColumnValues(SaveDS.PPartnerLocation[0], plocation);
                plocation.LocationKey = -1;
                plocation.SiteKey     = DomainManager.GSiteKey;
                SaveDS.PPartnerLocation[0].Delete();
                SaveDS.PPartnerLocation.Rows.Add(plocation);
            }

            // check if we have a valid country code
            if (SaveDS.PLocation[0].CountryCode.Trim().Length == 0)
            {
                AVerificationResult.Add(new TVerificationResult("error", "The country code is missing", TResultSeverity.Resv_Critical));
                return(false);
            }

            TDBTransaction Transaction      = new TDBTransaction();
            bool           WrongCountryCode = false;

            DBAccess.ReadTransaction(ref Transaction,
                                     delegate
            {
                WrongCountryCode = !PCountryAccess.Exists(SaveDS.PLocation[0].CountryCode, Transaction);
            });

            if (WrongCountryCode)
            {
                AVerificationResult.Add(new TVerificationResult("error", "The country code does not match a country", TResultSeverity.Resv_Critical));
                return(false);
            }

            DataSet ResponseDS = new PartnerEditTDS();
            TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(SaveDS.PPartner[0].PartnerKey);

            try
            {
                TSubmitChangesResult result = uiconnector.SubmitChanges(
                    ref SaveDS,
                    ref ResponseDS,
                    out AVerificationResult);
                return(result == TSubmitChangesResult.scrOK);
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                return(false);
            }
        }
Example #13
0
        public static bool GiftRevertAdjust(
            Int32 ALedgerNumber,
            Int32 ABatchNumber,
            Int32 AGiftDetailNumber,
            bool ABatchSelected,
            Int32 ANewBatchNumber,
            DateTime?ANewGLDateEffective,
            GiftAdjustmentFunctionEnum AFunction,
            bool ANoReceipt,
            Decimal ANewPct,
            out int AAdjustmentBatchNumber)
        {
            AAdjustmentBatchNumber = 0;
            int AdjustmentBatchNo = AAdjustmentBatchNumber;

            GiftBatchTDS GiftDS = new GiftBatchTDS();

            decimal batchGiftTotal = 0;

            ANewBatchNumber = ABatchSelected ? ANewBatchNumber : 0;

            TDBTransaction Transaction  = new TDBTransaction();
            TDataBase      db           = DBAccess.Connect("GiftRevertAdjust");
            bool           SubmissionOK = false;

            try
            {
                db.WriteTransaction(
                    ref Transaction,
                    ref SubmissionOK,
                    delegate
                {
                    // load the original gifts and gift details
                    AGiftAccess.LoadViaAGiftBatch(GiftDS, ALedgerNumber, ABatchNumber, Transaction);
                    AGiftDetailAccess.LoadViaAGiftBatch(GiftDS, ALedgerNumber, ABatchNumber, Transaction);

                    ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

                    AGiftBatchRow giftBatch;

                    DateTime DateEffective;

                    if (ANewGLDateEffective.HasValue)
                    {
                        DateEffective = ANewGLDateEffective.Value;
                    }
                    else
                    {
                        AGiftBatchTable OriginalGiftBatch = AGiftBatchAccess.LoadByPrimaryKey(ALedgerNumber, ABatchNumber, Transaction);
                        DateEffective = OriginalGiftBatch[0].GlEffectiveDate;
                    }

                    // if we need to create a new gift batch
                    if (!ABatchSelected)
                    {
                        giftBatch = CreateNewGiftBatch(
                            ALedgerNumber,
                            ABatchNumber,
                            DateEffective,
                            AFunction,
                            ref GiftDS, ref ledgerTable, Transaction);
                    }
                    else     // using an existing gift batch
                    {
                        AGiftBatchAccess.LoadByPrimaryKey(GiftDS, ALedgerNumber, ANewBatchNumber, Transaction);

                        giftBatch     = GiftDS.AGiftBatch[0];
                        DateEffective = giftBatch.GlEffectiveDate;
                        //If into an existing batch, then retrieve the existing batch total
                        batchGiftTotal = giftBatch.BatchTotal;
                    }

                    AdjustmentBatchNo = giftBatch.BatchNumber;

                    //assuming new elements are added after these static borders

                    GiftDS.AGift.DefaultView.Sort = string.Format("{0}, {1}",
                                                                  AGiftTable.GetBatchNumberDBName(),
                                                                  AGiftTable.GetGiftTransactionNumberDBName());

                    GiftDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}",
                                                                        AGiftDetailTable.GetBatchNumberDBName(),
                                                                        AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                                        AGiftDetailTable.GetDetailNumberDBName());

                    foreach (DataRowView giftRow in GiftDS.AGift.DefaultView)
                    {
                        int cycle = 0;

                        // first cycle creates gift reversal; second cycle creates new adjusted gift (if needed)
                        do
                        {
                            AGiftRow oldGift = (AGiftRow)giftRow.Row;

                            if (oldGift.RowState != DataRowState.Added)
                            {
                                AGiftRow gift = GiftDS.AGift.NewRowTyped(true);
                                DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift);
                                gift.LedgerNumber = giftBatch.LedgerNumber;
                                gift.BatchNumber  = giftBatch.BatchNumber;
                                // keep the same DateEntered as in the original gift if it is in the same period as the batch
                                if ((gift.DateEntered.Year != DateEffective.Year) || (gift.DateEntered.Month != DateEffective.Month))
                                {
                                    gift.DateEntered = DateEffective;
                                }
                                gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1;
                                giftBatch.LastGiftNumber++;
                                gift.LinkToPreviousGift = (cycle != 0);
                                gift.LastDetailNumber   = 0;
                                gift.FirstTimeGift      = false;

                                // do not print a receipt for reversed gifts
                                if (cycle == 0)
                                {
                                    gift.ReceiptPrinted = true;
                                    gift.PrintReceipt   = false;
                                }
                                else
                                {
                                    gift.ReceiptPrinted = false;
                                    gift.PrintReceipt   = !ANoReceipt;
                                }

                                GiftDS.AGift.Rows.Add(gift);

                                foreach (DataRowView giftDetailRow in GiftDS.AGiftDetail.DefaultView)
                                {
                                    AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row;

                                    // if gift detail belongs to gift
                                    if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) &&
                                        (oldGiftDetail.BatchNumber == oldGift.BatchNumber) &&
                                        (AFunction != GiftAdjustmentFunctionEnum.ReverseGiftDetail) ||
                                        (oldGiftDetail.DetailNumber == AGiftDetailNumber))
                                    {
                                        AddDuplicateGiftDetailToGift(ref GiftDS, ref gift, oldGiftDetail, cycle == 0, Transaction,
                                                                     AFunction,
                                                                     ANewPct);

                                        batchGiftTotal += ((cycle == 0) ? 0 : oldGiftDetail.GiftTransactionAmount);

                                        // original gift also gets marked as a reversal
                                        oldGiftDetail.ModifiedDetail = true;
                                    }
                                }
                            }

                            cycle++;
                        } while ((cycle < 2) &&
                                 (AFunction.Equals(GiftAdjustmentFunctionEnum.AdjustGift) ||
                                  AFunction.Equals(GiftAdjustmentFunctionEnum.FieldAdjust) ||
                                  AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust)));
                    }

                    //When reversing into a new or existing batch, set batch total
                    giftBatch.BatchTotal = batchGiftTotal;

                    // save everything at the end
                    AGiftBatchAccess.SubmitChanges(GiftDS.AGiftBatch, Transaction);
                    ALedgerAccess.SubmitChanges(ledgerTable, Transaction);
                    AGiftAccess.SubmitChanges(GiftDS.AGift, Transaction);
                    AGiftDetailAccess.SubmitChanges(GiftDS.AGiftDetail, Transaction);

                    GiftDS.AGiftBatch.AcceptChanges();

                    SubmissionOK = true;
                });
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), ex);
            }

            AAdjustmentBatchNumber = AdjustmentBatchNo;

            db.CloseDBConnection();

            return(SubmissionOK);
        }
        /// <summary>
        /// Called from a delegate set up by my constructor.
        /// Or if you're not using a reporting UI, you can call this directly, once the data and params have been set up.
        /// </summary>
        /// <param name="ACalc"></param>
        public void DesignReport(TRptCalculator ACalc)
        {
            ACalc.GetParameters().Add("param_design_template", true);

            if (FSelectedTemplate != null)
            {
                if (FDataGetter != null)
                {
                    if (!FDataGetter(ACalc))
                    {
                        return;
                    }
                }

                FFastReportType.GetMethod("LoadFromString", new Type[] { FSelectedTemplate.XmlText.GetType() }).Invoke(FfastReportInstance,
                                                                                                                       new object[] { FSelectedTemplate.XmlText });

                LoadReportParams(ACalc);
                FFastReportType.GetMethod("Design", new Type[0]).Invoke(FfastReportInstance, null);

                //
                // The user can change the report template - if it's changed I'll update the server
                // (unless the template is read-only, in which case I'll need to make a copy.)
                object ret       = FFastReportType.GetMethod("SaveToString", new Type[0]).Invoke(FfastReportInstance, null);
                String XmlString = (String)ret;
                //
                // I only want to check part of the report to assess whether it's changed, otherwise it always detects a change
                // (the modified date is changed, and the parameters may also be different.)

                Boolean TemplateChanged = false;
                Int32   Page1Pos        = XmlString.IndexOf("<ReportPage");
                Int32   PrevPage1Pos    = FSelectedTemplate.XmlText.IndexOf("<ReportPage");

                if ((Page1Pos < 1) || (PrevPage1Pos < 1))
                {
                    TemplateChanged = true;
                }
                else
                {
                    if (XmlString.Substring(Page1Pos) != FSelectedTemplate.XmlText.Substring(PrevPage1Pos))
                    {
                        TemplateChanged = true;
                    }
                }

                if (TemplateChanged)
                {
                    Boolean MakeACopy = false;

                    if (FSelectedTemplate.Readonly)
                    {
                        if (MessageBox.Show(
                                String.Format(Catalog.GetString("{0} cannot be ovewritten.\r\nMake a copy instead?"), FSelectedTemplate.ReportVariant),
                                Catalog.GetString("Design Template"),
                                MessageBoxButtons.YesNo) == DialogResult.No)
                        {
                            return;
                        }

                        MakeACopy = true;
                    }
                    else
                    {
                        if (MessageBox.Show(
                                String.Format(Catalog.GetString("Save changes to {0}?"), FSelectedTemplate.ReportVariant),
                                Catalog.GetString("Design Template"),
                                MessageBoxButtons.YesNo) == DialogResult.No)
                        {
                            return;
                        }
                    }

                    SReportTemplateTable TemplateTable = new SReportTemplateTable();
                    SReportTemplateRow   NewRow        = TemplateTable.NewRowTyped();
                    DataUtilities.CopyAllColumnValues(FSelectedTemplate, NewRow);
                    TemplateTable.Rows.Add(NewRow);

                    if (MakeACopy)
                    {
                        NewRow.TemplateId     = -1; // The value will come from the sequence
                        NewRow.ReportVariant  = "Copy of " + TemplateTable[0].ReportVariant;
                        NewRow.Readonly       = false;
                        NewRow.Default        = false;
                        NewRow.PrivateDefault = false;
                    }
                    else
                    {
                        TemplateTable.AcceptChanges(); // Don't allow this one-row table to be seen as "new"
                    }

                    NewRow.XmlText = XmlString;
                    SReportTemplateTable Tbl = TRemote.MReporting.WebConnectors.SaveTemplates(TemplateTable);
                    Tbl.AcceptChanges();
                    SetTemplate(Tbl[0]);
                }
            }

            if (FPetraUtilsObject != null)
            {
                FPetraUtilsObject.UpdateParentFormEndOfReport();
            }
        }
Example #15
0
        public void Should_Add_Coin()
        {
            _coinService.AddCoin(DataUtilities.GetCoin());

            _unitOfWorkMock.Verify(r => r.Coins.Add(It.IsAny <Coin>()));
        }
Example #16
0
        private int GetChangedRecordCountManual(out string AMessage)
        {
            //For Gift Batch we will get a mix of some batches, gifts and gift details.
            // Only check relevant tables.
            List <string> TablesToCheck = new List <string>();

            TablesToCheck.Add(FMainDS.AGiftBatch.TableName);
            TablesToCheck.Add(FMainDS.AGift.TableName);
            TablesToCheck.Add(FMainDS.AGiftDetail.TableName);

            List <Tuple <string, int> > TableAndCountList = new List <Tuple <string, int> >();
            int AllChangesCount = 0;

            if (FMainDS.HasChanges())
            {
                foreach (DataTable dt in FMainDS.GetChanges().Tables)
                {
                    string currentTableName = dt.TableName;

                    if ((dt != null) &&
                        TablesToCheck.Contains(currentTableName) &&
                        (dt.Rows.Count > 0))
                    {
                        int tableChangesCount = 0;

                        DataTable dtChanges = dt.GetChanges();

                        foreach (DataRow dr in dtChanges.Rows)
                        {
                            if (DataUtilities.DataRowColumnsHaveChanged(dr))
                            {
                                tableChangesCount++;
                                AllChangesCount++;
                            }
                        }

                        if (tableChangesCount > 0)
                        {
                            TableAndCountList.Add(new Tuple <string, int>(currentTableName, tableChangesCount));
                        }
                    }
                }
            }

            // Now build up a sensible message
            AMessage = String.Empty;

            if (TableAndCountList.Count > 0)
            {
                if (TableAndCountList.Count == 1)
                {
                    Tuple <string, int> TableAndCount = TableAndCountList[0];

                    string tableName = TableAndCount.Item1;

                    if (TableAndCount.Item1.Equals(AGiftBatchTable.GetTableName()))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to the details of {0} {1}.{2}"),
                                                 TableAndCount.Item2,
                                                 Catalog.GetPluralString("batch", "batches", TableAndCount.Item2),
                                                 Environment.NewLine);
                    }
                    else if (TableAndCount.Item1.Equals(AGiftTable.GetTableName()))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to the details of {0} {1}.{2}"),
                                                 TableAndCount.Item2,
                                                 Catalog.GetPluralString("gift", "gifts", TableAndCount.Item2),
                                                 Environment.NewLine);
                    }
                    else //if (TableAndCount.Item1.Equals(AGiftDetailTable.GetTableName()))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}.{2}"),
                                                 TableAndCount.Item2,
                                                 Catalog.GetPluralString("gift detail", "gift details", TableAndCount.Item2),
                                                 Environment.NewLine);
                    }
                }
                else
                {
                    int nBatches     = 0;
                    int nGifts       = 0;
                    int nGiftDetails = 0;

                    foreach (Tuple <string, int> TableAndCount in TableAndCountList)
                    {
                        if (TableAndCount.Item1.Equals(AGiftBatchTable.GetTableName()))
                        {
                            nBatches = TableAndCount.Item2;
                        }
                        else if (TableAndCount.Item1.Equals(AGiftTable.GetTableName()))
                        {
                            nGifts = TableAndCount.Item2;
                        }
                        else //if (TableAndCount.Item1.Equals(AGiftDetailTable.GetTableName()))
                        {
                            nGiftDetails = TableAndCount.Item2;
                        }
                    }

                    if ((nBatches > 0) && (nGifts > 0) && (nGiftDetails > 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}, {2} {3} and {4} {5}.{6}"),
                                                 nBatches,
                                                 Catalog.GetPluralString("batch", "batches", nBatches),
                                                 nGifts,
                                                 Catalog.GetPluralString("gift", "gifts", nGifts),
                                                 nGiftDetails,
                                                 Catalog.GetPluralString("gift detail", "gift details", nGiftDetails),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches > 0) && (nGifts > 0) && (nGiftDetails == 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1} and {2} {3}.{4}"),
                                                 nBatches,
                                                 Catalog.GetPluralString("batch", "batches", nBatches),
                                                 nGifts,
                                                 Catalog.GetPluralString("gift", "gifts", nGifts),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches > 0) && (nGifts == 0) && (nGiftDetails > 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1} and {2} {3}.{4}"),
                                                 nBatches,
                                                 Catalog.GetPluralString("batch", "batches", nBatches),
                                                 nGiftDetails,
                                                 Catalog.GetPluralString("gift detail", "gift details", nGiftDetails),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches > 0) && (nGifts == 0) && (nGiftDetails == 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}.{2}"),
                                                 nBatches,
                                                 Catalog.GetPluralString("batch", "batches", nBatches),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches == 0) && (nGifts > 0) && (nGiftDetails > 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1} and {2} {3}.{4}"),
                                                 nGifts,
                                                 Catalog.GetPluralString("gift", "gifts", nGifts),
                                                 nGiftDetails,
                                                 Catalog.GetPluralString("gift detail", "gift details", nGiftDetails),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches == 0) && (nGifts > 0) && (nGiftDetails == 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}.{2}"),
                                                 nGifts,
                                                 Catalog.GetPluralString("gift", "gifts", nGiftDetails),
                                                 Environment.NewLine);
                    }
                    else if ((nBatches == 0) && (nGifts == 0) && (nGiftDetails > 0))
                    {
                        AMessage = String.Format(Catalog.GetString("    You have made changes to {0} {1}.{2}"),
                                                 nGiftDetails,
                                                 Catalog.GetPluralString("gift detail", "gift details", nGiftDetails),
                                                 Environment.NewLine);
                    }
                }

                AMessage += Catalog.GetString("(some of the changes may include related background items)");
                AMessage += Environment.NewLine;
                AMessage += String.Format(TFrmPetraEditUtils.StrConsequenceIfNotSaved, Environment.NewLine);
            }

            return(AllChangesCount);
        }
Example #17
0
        /// <summary>
        /// Determine best location for partner out of a list of possible locations. Or simply find best one
        /// if no suggestion is made.
        /// </summary>
        /// <param name="APartnerKey"></param>
        /// <param name="ALocationKeyList"></param>
        /// <param name="APartnerLocationKeysTable"></param>
        /// <param name="ATransaction"></param>
        /// <returns>True if the address was found and added, otherwise false.</returns>
        private static Boolean DetermineAndAddBestLocationKey(
            Int64 APartnerKey,
            List <TLocationPK> ALocationKeyList,
            ref PPartnerLocationTable APartnerLocationKeysTable,
            TDBTransaction ATransaction)
        {
            PPartnerLocationTable AllPartnerLocationTable;
            PPartnerLocationTable FilteredPartnerLocationTable = new PPartnerLocationTable();
            TLocationPK           LocationPK = new TLocationPK();
            PPartnerLocationRow   PartnerLocationKeyRow;
            PPartnerLocationRow   PartnerLocationRowCopy;
            TLocationPK           BestLocationPK;

            if (ALocationKeyList.Count == 0)
            {
                // no list suggested: find best address in db for this partner
                BestLocationPK = TMailing.GetPartnersBestLocation(APartnerKey);
            }
            else if (ALocationKeyList.Count == 1)
            {
                // only one location suggested: take this one
                BestLocationPK = ALocationKeyList[0];
            }
            else
            {
                // Process location key list related to partner.
                // In order to use Calculations.DetermineBestAddress we need to first retrieve full data
                // for all suggested records from the db. Therefore load all locations for this partner
                // and then create a table of the ones that are suggested.
                AllPartnerLocationTable = PPartnerLocationAccess.LoadViaPPartner(APartnerKey, ATransaction);

                foreach (PPartnerLocationRow PartnerLocationRow in AllPartnerLocationTable.Rows)
                {
                    LocationPK.SiteKey     = PartnerLocationRow.SiteKey;
                    LocationPK.LocationKey = PartnerLocationRow.LocationKey;

                    if (ALocationKeyList.Contains(LocationPK))
                    {
                        PartnerLocationRowCopy = (PPartnerLocationRow)FilteredPartnerLocationTable.NewRow();
                        DataUtilities.CopyAllColumnValues(PartnerLocationRow, PartnerLocationRowCopy);
                        FilteredPartnerLocationTable.Rows.Add(PartnerLocationRowCopy);
                    }
                }

                BestLocationPK = Calculations.DetermineBestAddress(FilteredPartnerLocationTable);
            }

            // create new row, initialize it and add it to the table
            if (BestLocationPK.LocationKey != -1)
            {
                PartnerLocationKeyRow = (PPartnerLocationRow)APartnerLocationKeysTable.NewRow();
                PartnerLocationKeyRow[PPartnerLocationTable.GetPartnerKeyDBName()]  = APartnerKey;
                PartnerLocationKeyRow[PPartnerLocationTable.GetSiteKeyDBName()]     = BestLocationPK.SiteKey;
                PartnerLocationKeyRow[PPartnerLocationTable.GetLocationKeyDBName()] = BestLocationPK.LocationKey;

                // only add row if it does not already exist
                if (!APartnerLocationKeysTable.Rows.Contains(
                        new object[] { PartnerLocationKeyRow.PartnerKey, PartnerLocationKeyRow.SiteKey, PartnerLocationKeyRow.LocationKey }))
                {
                    APartnerLocationKeysTable.Rows.Add(PartnerLocationKeyRow);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #18
0
        static void CheckMail(object source, System.Timers.ElapsedEventArgs e)
        {
            NotesUtils pNotesUtils = null;

            Console.WriteLine("Notes Check:");
            System.Timers.Timer pp = (System.Timers.Timer)source;
            pp.Enabled = false;

            try
            {
                //pNotesUtils = new NotesUtils(pNotesSession, "mail9you/runstar", "mail\\费亚平.nsf");
                pNotesUtils = new NotesUtils(pNotesSession, "mail9you/runstar", "mail\\netadmin.nsf");

                if (pNotesUtils.OpenDataBase("netadmin", "12341234"))
                {
                    if (pNotesUtils.GetMailInfo())
                    {
                        MSSQLOperate pSaveMail = new MSSQLOperate(strAnalyse);

                        CustomDataCollection pMailStruct = (CustomDataCollection)pNotesUtils.Records;
                        CustomData[,] pMailInfo = pMailStruct[-1];

                        for (int i = 0; i < pMailStruct.RowCount; i++)
                        {
                            pSaveMail.Connect(false);
                            string        strProcParams = "SP_PUT_NOTESCONTENT";
                            DbParameter[] paramCache    = DataUtilities.GetParameters(strProcParams);

                            #region
                            if (paramCache == null)
                            {
                                paramCache = new SqlParameter[] {
                                    new SqlParameter("@iFailure", SqlDbType.Int, 4),
                                    new SqlParameter("@iCategory", SqlDbType.Int, 4),
                                    new SqlParameter("@strUID", SqlDbType.VarChar, 100),
                                    new SqlParameter("@strPUID", SqlDbType.VarChar, 100),
                                    new SqlParameter("@strSubject", SqlDbType.VarChar, 100),
                                    new SqlParameter("@dtPost", SqlDbType.DateTime),
                                    new SqlParameter("@strSender", SqlDbType.VarChar, 50),
                                    new SqlParameter("@strRecive", SqlDbType.Text),
                                    new SqlParameter("@strContent", SqlDbType.Text),
                                    new SqlParameter("@strCount", SqlDbType.VarChar, 100),
                                    new SqlParameter("@iView", SqlDbType.Int, 4),
                                    new SqlParameter("@iGroup", SqlDbType.Int, 4)
                                };
                                DataUtilities.SetParameters(strProcParams, paramCache);
                            }

                            paramCache[0].Value  = 0;
                            paramCache[1].Value  = 0;
                            paramCache[2].Value  = pMailInfo[i, 0].Content;
                            paramCache[3].Value  = pMailInfo[i, 1].Content;
                            paramCache[4].Value  = pMailInfo[i, 2].Content;
                            paramCache[5].Value  = pMailInfo[i, 4].Content;
                            paramCache[6].Value  = pMailInfo[i, 3].Content;
                            paramCache[7].Value  = pMailInfo[i, 5].Content;
                            paramCache[8].Value  = pMailInfo[i, 6].Content;
                            paramCache[9].Value  = pMailInfo[i, 7].Content;
                            paramCache[10].Value = 0;
                            paramCache[11].Value = 2;
                            #endregion

                            pSaveMail.ExecuteQuery(false, strProcParams, paramCache);
                            pSaveMail.GetResult(RecordStyle.NONE);
                        }

                        #region
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("Notes Recive Count : " + pMailStruct.RowCount);
                        Console.ForegroundColor = ConsoleColor.Gray;
                        Console.WriteLine("");
                        #endregion
                    }
                    else
                    {
                        #region
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("Notes Recive Exception : " + pNotesUtils.Message);
                        Console.ForegroundColor = ConsoleColor.Gray;
                        Console.WriteLine("");
                        #endregion
                    }
                }
                else
                {
                    #region
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Notes Connect Exception : " + pNotesUtils.Message);
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("");
                    #endregion
                }
            }
            catch (Exception ex)
            {
                #region
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Notes Save Exception : " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("");
                #endregion
            }
            finally
            {
                if (pNotesUtils != null)
                {
                    pNotesUtils.Dispose();
                }
            }

            pp.Enabled = true;
        }
Example #19
0
        /// <summary>
        /// Adds a duplicate Gift Detail (or reversed duplicate GiftDetail) to Gift.
        /// </summary>
        /// <param name="AMainDS"></param>
        /// <param name="AGift"></param>
        /// <param name="AOldGiftDetail"></param>
        /// <param name="AReversal">True for reverse or false for straight duplicate</param>
        /// <param name="ATransaction"></param>
        /// <param name="AFunction"></param>
        /// <param name="ANewPct"></param>
        /// <param name="AAutoCompleteComments"></param>
        /// <param name="AReversalCommentOne"></param>
        /// <param name="AReversalCommentTwo"></param>
        /// <param name="AReversalCommentThree"></param>
        /// <param name="AReversalCommentOneType"></param>
        /// <param name="AReversalCommentTwoType"></param>
        /// <param name="AReversalCommentThreeType"></param>
        /// <param name="AUpdateTaxDeductiblePctRecipients"></param>
        /// <param name="AGeneralFixedGiftDestination"></param>
        /// <param name="AFixedGiftDestination"></param>
        private static void AddDuplicateGiftDetailToGift(ref GiftBatchTDS AMainDS,
                                                         ref AGiftRow AGift,
                                                         AGiftDetailRow AOldGiftDetail,
                                                         bool AReversal,
                                                         TDBTransaction ATransaction,
                                                         GiftAdjustmentFunctionEnum AFunction,
                                                         Decimal ANewPct,
                                                         bool AAutoCompleteComments       = false,
                                                         string AReversalCommentOne       = "",
                                                         string AReversalCommentTwo       = "",
                                                         string AReversalCommentThree     = "",
                                                         string AReversalCommentOneType   = "",
                                                         string AReversalCommentTwoType   = "",
                                                         string AReversalCommentThreeType = "",
                                                         List <string[]> AUpdateTaxDeductiblePctRecipients = null,
                                                         bool AGeneralFixedGiftDestination   = false,
                                                         List <string> AFixedGiftDestination = null
                                                         )
        {
            bool TaxDeductiblePercentageEnabled =
                new TSystemDefaults(ATransaction.DataBaseObj).GetBooleanDefault(SharedConstants.SYSDEFAULT_TAXDEDUCTIBLEPERCENTAGE, false);

            AGiftDetailRow giftDetail = AMainDS.AGiftDetail.NewRowTyped(true);

            DataUtilities.CopyAllColumnValuesWithoutPK(AOldGiftDetail, giftDetail);

            giftDetail.DetailNumber = AGift.LastDetailNumber + 1;
            AGift.LastDetailNumber++;

            giftDetail.LedgerNumber          = AGift.LedgerNumber;
            giftDetail.BatchNumber           = AGift.BatchNumber;
            giftDetail.GiftTransactionNumber = AGift.GiftTransactionNumber;
            giftDetail.IchNumber             = 0;

            decimal signum = (AReversal) ? -1 : 1;

            giftDetail.GiftTransactionAmount = signum * AOldGiftDetail.GiftTransactionAmount;
            giftDetail.GiftAmount            = signum * AOldGiftDetail.GiftAmount;
            giftDetail.GiftAmountIntl        = signum * AOldGiftDetail.GiftAmountIntl;

            if (TaxDeductiblePercentageEnabled)
            {
                if (!AReversal && AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust))
                {
                    giftDetail.TaxDeductiblePct = ANewPct;
                    TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail);
                }
                else if (!AReversal)
                {
                    if (AUpdateTaxDeductiblePctRecipients != null)
                    {
                        string[] Result = AUpdateTaxDeductiblePctRecipients.Find(x => x[0] == giftDetail.RecipientKey.ToString());

                        // true if a new percentage is available and the user wants to use it
                        if (Result != null)
                        {
                            giftDetail.TaxDeductiblePct = Convert.ToDecimal(Result[1]);
                            TaxDeductibility.UpdateTaxDeductibiltyAmounts(ref giftDetail);
                        }
                    }
                }
                else
                {
                    giftDetail.TaxDeductibleAmount     = signum * AOldGiftDetail.TaxDeductibleAmount;
                    giftDetail.TaxDeductibleAmountBase = signum * AOldGiftDetail.TaxDeductibleAmountBase;
                    giftDetail.TaxDeductibleAmountIntl = signum * AOldGiftDetail.TaxDeductibleAmountIntl;
                    giftDetail.NonDeductibleAmount     = signum * AOldGiftDetail.NonDeductibleAmount;
                    giftDetail.NonDeductibleAmountBase = signum * AOldGiftDetail.NonDeductibleAmountBase;
                    giftDetail.NonDeductibleAmountIntl = signum * AOldGiftDetail.NonDeductibleAmountIntl;
                }
            }

            if (AAutoCompleteComments) // only used for tax deductible pct gift adjustments
            {
                AGiftRow OldGiftRow = (AGiftRow)AMainDS.AGift.Rows.Find(
                    new object[] { AOldGiftDetail.LedgerNumber, AOldGiftDetail.BatchNumber, AOldGiftDetail.GiftTransactionNumber });

                giftDetail.GiftCommentThree = Catalog.GetString("Original gift date: " + OldGiftRow.DateEntered.ToString("dd-MMM-yyyy"));
                giftDetail.CommentThreeType = "Both";
            }
            else // user defined
            {
                giftDetail.GiftCommentOne   = AReversalCommentOne;
                giftDetail.GiftCommentTwo   = AReversalCommentTwo;
                giftDetail.GiftCommentThree = AReversalCommentThree;
                giftDetail.CommentOneType   = AReversalCommentOneType;
                giftDetail.CommentTwoType   = AReversalCommentTwoType;
                giftDetail.CommentThreeType = AReversalCommentThreeType;
            }

            // If reversal: mark the new gift as a reversal
            if (AReversal)
            {
                giftDetail.ModifiedDetail = true;

                //Identify the reversal source
                giftDetail.ModifiedDetailKey = "|" + AOldGiftDetail.BatchNumber.ToString() + "|" +
                                               AOldGiftDetail.GiftTransactionNumber.ToString() + "|" +
                                               AOldGiftDetail.DetailNumber.ToString();
            }
            else
            {
                giftDetail.ModifiedDetail = false;

                // Make sure the motivation detail is still active. If not then we need a new one.
                AMotivationDetailTable MotivationDetailTable = AMotivationDetailAccess.LoadViaAMotivationGroup(
                    giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, ATransaction);
                DataRow CurrentMotivationDetail = MotivationDetailTable.Rows.Find(
                    new object[] { giftDetail.LedgerNumber, giftDetail.MotivationGroupCode, giftDetail.MotivationDetailCode });

                // Motivation detail has been made inactive (or doesn't exist) then use default
                if (!((MotivationDetailTable != null) && (MotivationDetailTable.Rows.Count > 0) && (CurrentMotivationDetail != null)) ||
                    !Convert.ToBoolean(CurrentMotivationDetail[AMotivationDetailTable.GetMotivationStatusDBName()]))
                {
                    bool ActiveRowFound = false;

                    // search for first alternative active detail that is part of the same group
                    foreach (AMotivationDetailRow Row in MotivationDetailTable.Rows)
                    {
                        if ((Row.MotivationDetailCode != giftDetail.MotivationDetailCode) && Row.MotivationStatus)
                        {
                            ActiveRowFound = true;
                            giftDetail.MotivationGroupCode  = Row.MotivationGroupCode;
                            giftDetail.MotivationDetailCode = Row.MotivationDetailCode;
                            break;
                        }
                    }

                    // if none found then use default group and detail
                    if (!ActiveRowFound)
                    {
                        giftDetail.MotivationGroupCode  = MFinanceConstants.MOTIVATION_GROUP_GIFT;
                        giftDetail.MotivationDetailCode = MFinanceConstants.GROUP_DETAIL_SUPPORT;
                    }
                }

                // if the gift destination should be fixed
                if ((AFunction.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust) && AGeneralFixedGiftDestination) ||
                    ((AFixedGiftDestination != null) && (AFixedGiftDestination.Exists(x => x == giftDetail.RecipientKey.ToString()))))
                {
                    giftDetail.FixedGiftDestination = true;
                }
                else
                {
                    giftDetail.FixedGiftDestination = false;
                }
            }

            AMainDS.AGiftDetail.Rows.Add(giftDetail);
        }
Example #20
0
        static void ServerEvent(object pObject)
        {
            if (pObject.GetType() == typeof(SocketEventArgs))
            {
                SocketEventArgs pSocketEvent = (SocketEventArgs)pObject;
                #region
                if (pSocketEvent.Link)
                {
                    Console.Write("※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※");
                    Console.WriteLine("Client [{0}] Connected!", pSocketEvent.Connection.SocketEndPoint.Address.ToString());
                }
                else
                {
                    string        strProcParams = "SP_VERIFY_LOGOUT";
                    DbParameter[] paramCache    = DataUtilities.GetParameters(strProcParams);

                    if (paramCache == null)
                    {
                        paramCache = new SqlParameter[] {
                            new SqlParameter("@strSession", SqlDbType.VarChar, 50)
                        };
                        DataUtilities.SetParameters(strProcParams, paramCache);
                    }

                    paramCache[0].Value = pSocketEvent.Connection.Session;

                    MSSQLOperate pLogout = new MSSQLOperate(strAnalyse);
                    pLogout.Connect(false);
                    pLogout.ExecuteQuery(false, strProcParams, paramCache);
                    pLogout.GetResult(RecordStyle.NONE);

                    Console.WriteLine("Client [{0}, {1}] Disconnected!", pSocketEvent.Connection.SocketEndPoint.Address.ToString(), pSocketEvent.Connection.Session);

                    if (null != pSocketEvent.SocketException)
                    {
                        Console.WriteLine("Socket Exception : {0}", pSocketEvent.SocketException.Message);
                    }

                    Console.Write("※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※");
                }
                #endregion
                ((SocketEventArgs)pObject).Connection.OnRecive();
            }
            else if (pObject.GetType() == typeof(MessageEventArgs))
            {
                DateTime tStartTime = DateTime.Now;

                TaskParser pTaskParser = new TaskParser(pNotesSession, (MessageEventArgs)pObject, strAnalyse, strOnline, strAccess);

                if (!pTaskParser.Parser())
                {
                    Console.WriteLine(pTaskParser.Error);
                }

                pTaskParser.Dispose();

                #region 发送/保存消息

                /*TaskService pMessageID = pTaskParser.SocketMessage;
                 *
                 * MSSQLOperate pMessageADO = new MSSQLOperate(strMessage);
                 *
                 * if (pMessageADO.Connect(false))
                 * {
                 *  string strProcParams = "SP_SEND_INSTANTMESSAGE";
                 *  DbParameter[] paramCache = DataUtilities.GetParameters(strProcParams);
                 *
                 *  if (paramCache == null)
                 *  {
                 *      paramCache = new SqlParameter[]{
                 *                                 new SqlParameter("@strCommand",SqlDbType.VarChar, 50),
                 *                                 new SqlParameter("@strSession",SqlDbType.VarChar, 50)
                 *                             };
                 *      DataUtilities.SetParameters(strProcParams, paramCache);
                 *  }
                 *
                 *  paramCache[0].Value = pMessageID.ToString();
                 *  paramCache[1].Value = ((MessageEventArgs)pObject).Connection.Session;
                 *
                 *  pMessageADO.ExecuteQuery(false, strProcParams, paramCache);
                 *  pMessageADO.GetResult(RecordStyle.DATASET);
                 *  DataSet pMessageData = (DataSet)pMessageADO.RecordData;
                 *
                 *  if (pMessageADO.AffectRow > 0)
                 *  {
                 *      for (int i = 0; i < pMessageData.Tables[0].Rows.Count; i++)
                 *      {
                 *          if (pMessageData.Tables[0].Rows[i][1].ToString() != "")
                 *          {
                 *              //离线消息
                 *              if (pMessageData.Tables[0].Rows[i][3].ToString() == "N/A")
                 *              {
                 *                  string strInput = @"INSERT INTO Message_Content(Content_Message, Content_Sender, Content_Recive, Content_Desc)
                 *                      VALUES(" + pMessageData.Tables[0].Rows[i][0].ToString() + "," + pMessageData.Tables[0].Rows[i][1].ToString()
                 + "," + pMessageData.Tables[0].Rows[i][2].ToString();
                 +
                 +                  pMessageADO.ExecuteQuery(strInput);
                 +                  pMessageADO.GetResult(RecordStyle.NONE);
                 +              }
                 +              //及时消息
                 +              else
                 +              {
                 +                  CustomDataCollection mSendContent = new CustomDataCollection(StructType.CUSTOMDATA);
                 +
                 +                  mSendContent.Add("用户:" + pMessageData.Tables[0].Rows[i][4].ToString() + "触发了命令:" + pMessageData.Tables[0].Rows[i][5].ToString() + "内容为:");
                 +
                 +                  SocketPacket pSourcePacket = new SocketPacket(pMessageID, mSendContent);
                 +                  byte[] pSendBuffer = pSourcePacket.CoalitionInfo();
                 +
                 +                  //byte[] pSendBuffer = mSocketDate.setSocketData(CEnum.ServiceKey.INSTANT_CONTENT_RECIVE, CEnum.Msg_Category.INSTANT, mSendContent).bMsgBuffer;
                 +
                 +                  //((MessageEventArgs)pObject).SocketConnection.OnSend(pMessageData.Tables[0].Rows[i][3].ToString(), pSendBuffer);
                 +              }
                 +          }
                 +      }
                 +  }
                 +  pMessageADO.DisConnected();
                 + }
                 + else
                 + {
                 +  Console.ForegroundColor = ConsoleColor.Red;
                 +  Console.WriteLine(String.Format("      DB Connect Error!"));
                 +  Console.ForegroundColor = ConsoleColor.Gray;
                 +  Console.WriteLine();
                 + }*/
                #endregion

                ((MessageEventArgs)pObject).Connection.OnRecive();

                //Print Message
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(String.Format("      Total Times : {0}", DateTime.Now.Subtract(tStartTime)));
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine();
            }
        }
Example #21
0
 public int Del(int id)
 {
     return(DataUtilities.ExcuteNonQuery("Account_Delete", CommandType.StoredProcedure, "@ID", id));
 }
        /// <summary>
        /// Print a receipt for each gift (one page for each donor) in the batch
        /// </summary>
        /// <param name="AGiftTDS"></param>
        public void PrintGiftBatchReceipts(GiftBatchTDS AGiftTDS)
        {
            AGiftBatchRow GiftBatchRow = AGiftTDS.AGiftBatch[0];

            DataView GiftView = new DataView(AGiftTDS.AGift);

            //AGiftTDS.AGift.DefaultView.RowFilter
            GiftView.RowFilter = String.Format("{0}={1} and {2}={3}",
                                               AGiftTable.GetLedgerNumberDBName(), GiftBatchRow.LedgerNumber,
                                               AGiftTable.GetBatchNumberDBName(), GiftBatchRow.BatchNumber);
            String       ReceiptedDonorsList             = "";
            List <Int32> ReceiptedGiftTransactions       = new List <Int32>();
            SortedList <Int64, AGiftTable> GiftsPerDonor = new SortedList <Int64, AGiftTable>();

            foreach (DataRowView rv in GiftView)
            {
                AGiftRow GiftRow = (AGiftRow)rv.Row;
                bool     ReceiptEachGift;
                String   ReceiptLetterFrequency;
                bool     EmailGiftStatement;
                bool     AnonymousDonor;

                TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerReceiptingInfo(
                    GiftRow.DonorKey,
                    out ReceiptEachGift,
                    out ReceiptLetterFrequency,
                    out EmailGiftStatement,
                    out AnonymousDonor);

                if (ReceiptEachGift)
                {
                    // I want to print a receipt for this gift,
                    // but if there's already one queued for this donor,
                    // I'll add this gift onto the existing receipt.

                    if (!GiftsPerDonor.ContainsKey(GiftRow.DonorKey))
                    {
                        GiftsPerDonor.Add(GiftRow.DonorKey, new AGiftTable());
                    }

                    AGiftRow NewRow = GiftsPerDonor[GiftRow.DonorKey].NewRowTyped();
                    DataUtilities.CopyAllColumnValues(GiftRow, NewRow);
                    GiftsPerDonor[GiftRow.DonorKey].Rows.Add(NewRow);
                } // if receipt required
            }     // foreach gift

            String HtmlDoc = "";

            OpenFileDialog DialogOpen = new OpenFileDialog();

            if (Directory.Exists(TAppSettingsManager.GetValue("Formletters.Path")))
            {
                DialogOpen.InitialDirectory = TAppSettingsManager.GetValue("Formletters.Path");
            }

            DialogOpen.Filter           = Catalog.GetString("HTML file (*.html)|*.html;*.htm");
            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title            = Catalog.GetString("Select the template for the gift receipt");

            if (DialogOpen.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string HTMLTemplateFilename = DialogOpen.FileName;

            foreach (Int64 DonorKey in GiftsPerDonor.Keys)
            {
                String        DonorShortName;
                TPartnerClass DonorClass;
                TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerShortName(DonorKey, out DonorShortName, out DonorClass);
                DonorShortName = Calculations.FormatShortName(DonorShortName, eShortNameFormat.eReverseShortname);

                string HtmlPage = TRemote.MFinance.Gift.WebConnectors.PrintGiftReceipt(
                    GiftBatchRow.CurrencyCode,
                    DonorShortName,
                    DonorKey,
                    DonorClass,
                    GiftsPerDonor[DonorKey],
                    HTMLTemplateFilename
                    );

                TFormLettersTools.AttachNextPage(ref HtmlDoc, HtmlPage);
                ReceiptedDonorsList += (DonorShortName + "\r\n");

                foreach (AGiftRow GiftRow in GiftsPerDonor[DonorKey].Rows)
                {
                    ReceiptedGiftTransactions.Add(GiftRow.GiftTransactionNumber);
                }
            }

            TFormLettersTools.CloseDocument(ref HtmlDoc);

            if (ReceiptedGiftTransactions.Count > 0)
            {
                TFrmReceiptControl.PreviewOrPrint(HtmlDoc);

                if (MessageBox.Show(
                        Catalog.GetString(
                            "Press OK if receipts to these recipients were printed correctly.\r\nThe gifts will be marked as receipted.\r\n") +
                        ReceiptedDonorsList,

                        Catalog.GetString("Receipt Printing"),
                        MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    foreach (Int32 Trans in ReceiptedGiftTransactions)
                    {
                        TRemote.MFinance.Gift.WebConnectors.MarkReceiptsPrinted(
                            GiftBatchRow.LedgerNumber,
                            GiftBatchRow.BatchNumber,
                            Trans);
                    }
                }
            }
        }
Example #23
0
        public CBORObject ReadForFirstByte(
            int firstbyte,
            CBORTypeFilter filter)
        {
            if (this.depth > 500)
            {
                throw new CBORException("Too deeply nested");
            }
            if (firstbyte < 0)
            {
                throw new CBORException("Premature end of data");
            }
            if (firstbyte == 0xff)
            {
                throw new CBORException("Unexpected break code encountered");
            }
            int type           = (firstbyte >> 5) & 0x07;
            int additional     = firstbyte & 0x1f;
            int expectedLength = CBORObject.GetExpectedLength(firstbyte);

            // Data checks
            if (expectedLength == -1)
            {
                // if the head byte is invalid
                throw new CBORException("Unexpected data encountered");
            }
            if (filter != null)
            {
                // Check for valid major types if asked
                if (!filter.MajorTypeMatches(type))
                {
                    throw new CBORException("Unexpected data type encountered");
                }
                if (firstbyte >= 0xe0 && firstbyte <= 0xff && firstbyte != 0xf9 &&
                    firstbyte != 0xfa && firstbyte != 0xfb)
                {
                    if (!filter.NonFPSimpleValueAllowed())
                    {
                        throw new CBORException("Unexpected data type encountered");
                    }
                }
            }
            // Check if this represents a fixed object
            CBORObject fixedObject = CBORObject.GetFixedObject(firstbyte);

            if (fixedObject != null)
            {
                return(fixedObject);
            }
            // Read fixed-length data
            byte[] data = null;
            if (expectedLength != 0)
            {
                data = new byte[expectedLength];
                // include the first byte because GetFixedLengthObject
                // will assume it exists for some head bytes
                data[0] = unchecked ((byte)firstbyte);
                if (expectedLength > 1 &&
                    this.stream.Read(data, 1, expectedLength - 1) != expectedLength
                    - 1)
                {
                    throw new CBORException("Premature end of data");
                }
                CBORObject cbor = CBORObject.GetFixedLengthObject(firstbyte, data);
                if (this.stringRefs != null && (type == 2 || type == 3))
                {
                    this.stringRefs.AddStringIfNeeded(cbor, expectedLength - 1);
                }
                return(cbor);
            }
            var      uadditional      = (long)additional;
            EInteger bigintAdditional = EInteger.Zero;
            var      hasBigAdditional = false;

            data = new byte[8];
            var lowAdditional = 0;

            switch (firstbyte & 0x1f)
            {
            case 24: {
                int tmp = this.stream.ReadByte();
                if (tmp < 0)
                {
                    throw new CBORException("Premature end of data");
                }
                lowAdditional = tmp;
                uadditional   = lowAdditional;
                break;
            }

            case 25: {
                if (this.stream.Read(data, 0, 2) != 2)
                {
                    throw new CBORException("Premature end of data");
                }
                lowAdditional  = ((int)(data[0] & (int)0xff)) << 8;
                lowAdditional |= (int)(data[1] & (int)0xff);
                uadditional    = lowAdditional;
                break;
            }

            case 26: {
                if (this.stream.Read(data, 0, 4) != 4)
                {
                    throw new CBORException("Premature end of data");
                }
                uadditional  = ((long)(data[0] & (long)0xff)) << 24;
                uadditional |= ((long)(data[1] & (long)0xff)) << 16;
                uadditional |= ((long)(data[2] & (long)0xff)) << 8;
                uadditional |= (long)(data[3] & (long)0xff);
                break;
            }

            case 27: {
                if (this.stream.Read(data, 0, 8) != 8)
                {
                    throw new CBORException("Premature end of data");
                }
                if ((((int)data[0]) & 0x80) != 0)
                {
                    // Won't fit in a signed 64-bit number
                    var uabytes = new byte[9];
                    uabytes[0]       = data[7];
                    uabytes[1]       = data[6];
                    uabytes[2]       = data[5];
                    uabytes[3]       = data[4];
                    uabytes[4]       = data[3];
                    uabytes[5]       = data[2];
                    uabytes[6]       = data[1];
                    uabytes[7]       = data[0];
                    uabytes[8]       = 0;
                    hasBigAdditional = true;
                    bigintAdditional = EInteger.FromBytes(uabytes, true);
                }
                else
                {
                    uadditional  = ((long)(data[0] & (long)0xff)) << 56;
                    uadditional |= ((long)(data[1] & (long)0xff)) << 48;
                    uadditional |= ((long)(data[2] & (long)0xff)) << 40;
                    uadditional |= ((long)(data[3] & (long)0xff)) << 32;
                    uadditional |= ((long)(data[4] & (long)0xff)) << 24;
                    uadditional |= ((long)(data[5] & (long)0xff)) << 16;
                    uadditional |= ((long)(data[6] & (long)0xff)) << 8;
                    uadditional |= (long)(data[7] & (long)0xff);
                }
                break;
            }
            }
            // The following doesn't check for major types 0 and 1,
            // since all of them are fixed-length types and are
            // handled in the call to GetFixedLengthObject.
            if (type == 2) // Byte string
            {
                if (additional == 31)
                {
                    // Streaming byte string
                    using (var ms = new MemoryStream()) {
                        // Requires same type as this one
                        while (true)
                        {
                            int nextByte = this.stream.ReadByte();
                            if (nextByte == 0xff)
                            {
                                // break if the "break" code was read
                                break;
                            }
                            long len = ReadDataLength(this.stream, nextByte, 2);
                            if ((len >> 63) != 0 || len > Int32.MaxValue)
                            {
                                throw new CBORException("Length" + ToUnsignedBigInteger(len) +
                                                        " is bigger than supported ");
                            }
                            if (nextByte != 0x40)
                            {
                                // NOTE: 0x40 means the empty byte string
                                ReadByteData(this.stream, len, ms);
                            }
                        }
                        if (ms.Position > Int32.MaxValue)
                        {
                            throw new
                                  CBORException("Length of bytes to be streamed is bigger than supported ");
                        }
                        data = ms.ToArray();
                        return(new CBORObject(
                                   CBORObject.CBORObjectTypeByteString,
                                   data));
                    }
                }
                else
                {
                    if (hasBigAdditional)
                    {
                        throw new CBORException("Length of " +
                                                CBORUtilities.BigIntToString(bigintAdditional) + " is bigger than supported");
                    }
                    if (uadditional > Int32.MaxValue)
                    {
                        throw new CBORException("Length of " +
                                                CBORUtilities.LongToString(uadditional) +
                                                " is bigger than supported");
                    }
                    data = ReadByteData(this.stream, uadditional, null);
                    var cbor = new CBORObject(CBORObject.CBORObjectTypeByteString, data);
                    if (this.stringRefs != null)
                    {
                        int hint = (uadditional > Int32.MaxValue || hasBigAdditional) ?
                                   Int32.MaxValue : (int)uadditional;
                        this.stringRefs.AddStringIfNeeded(cbor, hint);
                    }
                    return(cbor);
                }
            }
            if (type == 3) // Text string
            {
                if (additional == 31)
                {
                    // Streaming text string
                    var builder = new StringBuilder();
                    while (true)
                    {
                        int nextByte = this.stream.ReadByte();
                        if (nextByte == 0xff)
                        {
                            // break if the "break" code was read
                            break;
                        }
                        long len = ReadDataLength(this.stream, nextByte, 3);
                        if ((len >> 63) != 0 || len > Int32.MaxValue)
                        {
                            throw new CBORException("Length" + ToUnsignedBigInteger(len) +
                                                    " is bigger than supported");
                        }
                        if (nextByte != 0x60)
                        {
                            // NOTE: 0x60 means the empty string
                            if (PropertyMap.ExceedsKnownLength(this.stream, len))
                            {
                                throw new CBORException("Premature end of data");
                            }
                            switch (
                                DataUtilities.ReadUtf8(
                                    this.stream,
                                    (int)len,
                                    builder,
                                    false))
                            {
                            case -1:
                                throw new CBORException("Invalid UTF-8");

                            case -2:
                                throw new CBORException("Premature end of data");
                            }
                        }
                    }
                    return(new CBORObject(
                               CBORObject.CBORObjectTypeTextString,
                               builder.ToString()));
                }
                else
                {
                    if (hasBigAdditional)
                    {
                        throw new CBORException("Length of " +
                                                CBORUtilities.BigIntToString(bigintAdditional) + " is bigger than supported");
                    }
                    if (uadditional > Int32.MaxValue)
                    {
                        throw new CBORException("Length of " +
                                                CBORUtilities.LongToString(uadditional) +
                                                " is bigger than supported");
                    }
                    if (PropertyMap.ExceedsKnownLength(this.stream, uadditional))
                    {
                        throw new CBORException("Premature end of data");
                    }
                    var builder = new StringBuilder();
                    switch (
                        DataUtilities.ReadUtf8(
                            this.stream,
                            (int)uadditional,
                            builder,
                            false))
                    {
                    case -1:
                        throw new CBORException("Invalid UTF-8");

                    case -2:
                        throw new CBORException("Premature end of data");
                    }
                    var cbor = new CBORObject(
                        CBORObject.CBORObjectTypeTextString,
                        builder.ToString());
                    if (this.stringRefs != null)
                    {
                        int hint = (uadditional > Int32.MaxValue || hasBigAdditional) ?
                                   Int32.MaxValue : (int)uadditional;
                        this.stringRefs.AddStringIfNeeded(cbor, hint);
                    }
                    return(cbor);
                }
            }
            if (type == 4) // Array
            {
                CBORObject cbor = CBORObject.NewArray();
                if (additional == 31)
                {
                    var vtindex = 0;
                    // Indefinite-length array
                    while (true)
                    {
                        int headByte = this.stream.ReadByte();
                        if (headByte < 0)
                        {
                            throw new CBORException("Premature end of data");
                        }
                        if (headByte == 0xff)
                        {
                            // Break code was read
                            break;
                        }
                        if (filter != null && !filter.ArrayIndexAllowed(vtindex))
                        {
                            throw new CBORException("Array is too long");
                        }
                        ++this.depth;
                        CBORObject o = this.ReadForFirstByte(
                            headByte,
                            filter == null ? null : filter.GetSubFilter(vtindex));
                        --this.depth;
                        cbor.Add(o);
                        ++vtindex;
                    }
                    return(cbor);
                }
                if (hasBigAdditional)
                {
                    throw new CBORException("Length of " +
                                            CBORUtilities.BigIntToString(bigintAdditional) + " is bigger than supported");
                }
                if (uadditional > Int32.MaxValue)
                {
                    throw new CBORException("Length of " +
                                            CBORUtilities.LongToString(uadditional) +
                                            " is bigger than supported");
                }
                if (filter != null && !filter.ArrayLengthMatches(uadditional))
                {
                    throw new CBORException("Array is too long");
                }
                if (PropertyMap.ExceedsKnownLength(this.stream, uadditional))
                {
                    throw new CBORException("Remaining data too small for array length");
                }
                ++this.depth;
                for (long i = 0; i < uadditional; ++i)
                {
                    cbor.Add(
                        this.Read(filter == null ? null : filter.GetSubFilter(i)));
                }
                --this.depth;
                return(cbor);
            }
            if (type == 5) // Map, type 5
            {
                CBORObject cbor = CBORObject.NewMap();
                if (additional == 31)
                {
                    // Indefinite-length map
                    while (true)
                    {
                        int headByte = this.stream.ReadByte();
                        if (headByte < 0)
                        {
                            throw new CBORException("Premature end of data");
                        }
                        if (headByte == 0xff)
                        {
                            // Break code was read
                            break;
                        }
                        ++this.depth;
                        CBORObject key   = this.ReadForFirstByte(headByte, null);
                        CBORObject value = this.Read(null);
                        --this.depth;
                        if (this.policy == CBORDuplicatePolicy.Disallow)
                        {
                            if (cbor.ContainsKey(key))
                            {
                                throw new CBORException("Duplicate key already exists: " + key);
                            }
                        }
                        cbor[key] = value;
                    }
                    return(cbor);
                }
                if (hasBigAdditional)
                {
                    throw new CBORException("Length of " +
                                            CBORUtilities.BigIntToString(bigintAdditional) + " is bigger than supported");
                }
                if (uadditional > Int32.MaxValue)
                {
                    throw new CBORException("Length of " +
                                            CBORUtilities.LongToString(uadditional) +
                                            " is bigger than supported");
                }
                if (PropertyMap.ExceedsKnownLength(this.stream, uadditional))
                {
                    throw new CBORException("Remaining data too small for map length");
                }
                for (long i = 0; i < uadditional; ++i)
                {
                    ++this.depth;
                    CBORObject key   = this.Read(null);
                    CBORObject value = this.Read(null);
                    --this.depth;
                    if (this.policy == CBORDuplicatePolicy.Disallow)
                    {
                        if (cbor.ContainsKey(key))
                        {
                            throw new CBORException("Duplicate key already exists: " + key);
                        }
                    }
                    cbor[key] = value;
                }
                return(cbor);
            }
            if (type == 6) // Tagged item
            {
                ICBORTag taginfo       = null;
                var      haveFirstByte = false;
                var      newFirstByte  = -1;
                if (!hasBigAdditional)
                {
                    if (filter != null && !filter.TagAllowed(uadditional))
                    {
                        throw new CBORException("Unexpected tag encountered: " +
                                                uadditional);
                    }
                    int uad = uadditional >= 257 ? 257 : (uadditional < 0 ? 0 :
                                                          (int)uadditional);
                    switch (uad)
                    {
                    case 256:
                        // Tag 256: String namespace
                        this.stringRefs = this.stringRefs ?? (new StringRefs());
                        this.stringRefs.Push();
                        break;

                    case 25:
                        // String reference
                        if (this.stringRefs == null)
                        {
                            throw new CBORException("No stringref namespace");
                        }
                        break;

                    case 28:
                    case 29:
                        this.hasSharableObjects = true;
                        break;
                    }

                    taginfo = CBORObject.FindTagConverterLong(uadditional);
                }
                else
                {
                    if (filter != null && !filter.TagAllowed(bigintAdditional))
                    {
                        throw new CBORException("Unexpected tag encountered: " +
                                                uadditional);
                    }
                    taginfo = CBORObject.FindTagConverter(bigintAdditional);
                }
                ++this.depth;
                CBORObject o = haveFirstByte ? this.ReadForFirstByte(
                    newFirstByte,
                    taginfo == null ? null : taginfo.GetTypeFilter()) :
                               this.Read(taginfo == null ? null : taginfo.GetTypeFilter());
                --this.depth;
                if (hasBigAdditional)
                {
                    return(CBORObject.FromObjectAndTag(o, bigintAdditional));
                }
                if (uadditional < 65536)
                {
                    int uaddl = uadditional >= 257 ? 257 : (uadditional < 0 ? 0 :
                                                            (int)uadditional);
                    switch (uaddl)
                    {
                    case 256:
                        // string tag
                        this.stringRefs.Pop();
                        break;

                    case 25:
                        // stringref tag
                        return(this.stringRefs.GetString(o.AsEInteger()));
                    }

                    return(CBORObject.FromObjectAndTag(
                               o,
                               (int)uadditional));
                }
                return(CBORObject.FromObjectAndTag(
                           o,
                           (EInteger)uadditional));
            }
            throw new CBORException("Unexpected data encountered");
        }
Example #24
0
 private object TranslateEnum(Type clrEnumType, object member)
 {
     return(DataUtilities.ConvertToEnum(clrEnumType, member));
 }
Example #25
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        ///     14-Oct-13 - New method to log the page request information in the database ...
        /// </summary>
        public static void LogPageRequestInDatabase(ConfigurationInfo ci, string applicationName, string aspSessionID, string uniqueSessionID,
                                                    string pageURL, DateTime pageRequestTime, double serverProcessingMS, int currentUserID, string ipAddress)
        {
            bool success = false;

            DatabaseWrapper dbInfo = null;

            try {
                //_____ Check for a null configurationInfo or dbConInfo object
                if (ci == null || ci.DbConInfo.NAME == null)
                {
                    Logger.LogError(200, "Error inserting the PageRequest log into the database - null configurationInfo found, probably because of an application reset or session timeout.");
                }
                else
                {
                    // 3-Mar-2016 - ignore specific IP addresses (e.g. robots like the UptimeRobot), as these are artificially bloating the logs with limited utility!
                    if (ipAddress == null || AddressesToIgnore.Contains(ipAddress) == false)
                    {
                        //_____ Check for s***e data and make it blank if so, so it doesn't kill the database ...
                        applicationName = (applicationName == null) ? "" : applicationName;
                        aspSessionID    = (aspSessionID == null) ? "" : aspSessionID;
                        uniqueSessionID = (uniqueSessionID == null) ? "" : uniqueSessionID;
                        pageURL         = (pageURL == null) ? "" : pageURL;

                        //_____ Connect to the database ...
                        dbInfo = new DatabaseWrapper(ci);
                        dbInfo.Connect();

                        //_____ Create the table if it does not already exist
                        string createTableSQL = @"
                    CREATE TABLE " + logTN + @" (
                        ID int NOT NULL Auto_Increment, PRIMARY KEY(ID),
                        Application_Name VARCHAR(255), INDEX Application_Name(Application_Name),
                        Session_ID_ASP VARCHAR(50), INDEX Session_ID_ASP(Session_ID_ASP),
                        Session_ID_Unique VARCHAR(50), INDEX Session_ID_Unique(Session_ID_Unique),
                        Page_Name VARCHAR(255), INDEX Page_Name(Page_Name),
                        Page_URL LONGTEXT,
                        Page_Request_Date DATETIME, INDEX Page_Request_Date(Page_Request_Date),
                        Server_Render_Speed DOUBLE, INDEX Server_Render_Speed(Server_Render_Speed),
                        Current_User_ID INT, INDEX Current_User_ID(Current_User_ID),
                        IP_Address	VARCHAR(20),    INDEX IP_Address(IP_Address)
                    ) ENGINE=MyISAM;
                ";

                        if (dbInfo.TableExists(logTN) == false)
                        {
                            dbInfo.ExecuteSQL(createTableSQL, ref success);
                        }

                        //_____ Parse the page name
                        string pageName = "";
                        {
                            // remove the ?...... page params
                            string[] bits1 = pageURL.Split(new string[] { "?", "&" }, StringSplitOptions.None);
                            string[] bits2 = bits1[0].Split(new string[] { "/", "\\" }, StringSplitOptions.None);
                            pageName = bits2[bits2.Length - 1];
                        }

                        //_____ Build the SQL and run the insert ...
                        StringBuilder sql = new StringBuilder();
                        sql.Append("INSERT INTO " + logTN
                                   + " (Application_Name, Session_ID_ASP, Session_ID_Unique, Page_Name, Page_URL, Page_Request_Date, Server_Render_Speed, Current_User_ID, IP_Address ) VALUES (");
                        sql.Append(DataUtilities.Quote(applicationName) + ", ");
                        sql.Append(DataUtilities.Quote(aspSessionID) + ", ");
                        sql.Append(DataUtilities.Quote(uniqueSessionID) + ", ");
                        sql.Append(DataUtilities.Quote(pageName) + ", ");
                        sql.Append(DataUtilities.Quote(pageURL) + ", ");
                        sql.Append(DataUtilities.Quote(DateTimeInformation.FormatDatabaseDate(pageRequestTime, true, true)) + ", ");
                        sql.Append(serverProcessingMS + ", ");
                        sql.Append(currentUserID + ", ");
                        sql.Append(DataUtilities.DatabaseifyString(ipAddress, false));

                        sql.Append(");");

                        int numInserts = dbInfo.ExecuteSQL(sql.ToString(), ref success);

                        if (success == false)
                        {
                            Logger.LogError(201, "Error inserting the PageRequest log into the database - check the detailed log for details.");
                        }
                    }
                }
            } catch (Exception ex) {
                Logger.LogError(202, "Error inserting the PageRequest log into the database: " + ex.ToString());
            } finally {
                if (dbInfo != null)
                {
                    dbInfo.Disconnect();
                }
            }
        }
Example #26
0
        public long InsertToMainServer()
        {
            GetData Data = new GetData();
            Dictionary <string, string>                 summary     = Data.SummaryData;
            Dictionary <string, string>                 interchange = Data.InterchangeData;
            Dictionary <string, List <string> >         coal        = Data.CoalData;
            Dictionary <string, List <string> >         wind        = Data.WindData;
            Dictionary <string, List <string> >         biomass     = Data.BiomassData;
            Dictionary <string, List <string> >         hydro       = Data.HydroData;
            List <Dictionary <string, List <string> > > gas         = Data.GasData;

            long currentTime = DateTime.Now.Ticks;

            InsertToServer db = new InsertToServer();

            SelectFromServer selectDb = new SelectFromServer();

            DataUtilities util = new DataUtilities();

            util.DbMigrate();

            long pK = db.InsertMain("main_table", currentTime);

            if (pK > 0)
            {
                Console.WriteLine(pK);
            }
            else
            {
                Console.WriteLine("FAIL FAIL FAIL");
            }
            foreach (KeyValuePair <string, List <string> > entry in coal)
            {
                db.InsertFuelRecord("coal_table", pK, entry.Key, entry.Value[0], entry.Value[1], entry.Value[2]);
            }
            foreach (KeyValuePair <string, List <string> > entry in wind)
            {
                db.InsertFuelRecord("wind_table", pK, entry.Key, entry.Value[0], entry.Value[1], entry.Value[2]);
            }
            foreach (KeyValuePair <string, List <string> > entry in hydro)
            {
                db.InsertFuelRecord("hydro_table", pK, entry.Key, entry.Value[0], entry.Value[1], entry.Value[2]);
            }
            foreach (KeyValuePair <string, List <string> > entry in biomass)
            {
                db.InsertFuelRecord("biomass_table", pK, entry.Key, entry.Value[0], entry.Value[1], entry.Value[2]);
            }
            foreach (KeyValuePair <string, string> entry in summary)
            {
                db.InsertSummary("summary_table", pK, entry.Key, entry.Value);
            }
            foreach (KeyValuePair <string, string> entry in interchange)
            {
                db.InsertSummary("interchange_table", pK, entry.Key, entry.Value);
            }
            for (int i = 0; i < gas.Count; i++)
            {
                switch (i)
                {
                case 0:
                    foreach (KeyValuePair <string, List <string> > entry in gas[i])
                    {
                        db.InsertFuelRecord("simple_cycle_table", pK, entry.Key, entry.Value[0], entry.Value[1], entry.Value[2]);
                    }
                    break;

                case 1:
                    foreach (KeyValuePair <string, List <string> > entry in gas[i])
                    {
                        db.InsertFuelRecord("cogeneration_table", pK, entry.Key, entry.Value[0], entry.Value[1], entry.Value[2]);
                    }
                    break;

                case 2:
                    foreach (KeyValuePair <string, List <string> > entry in gas[i])
                    {
                        db.InsertFuelRecord("combined_cycle_table", pK, entry.Key, entry.Value[0], entry.Value[1], entry.Value[2]);
                    }
                    break;
                }
            }
            return(pK);
        }
Example #27
0
        private int GetChangedRecordCountManual(out string AMessage)
        {
            // For GL Batch we will get some mix of batches, journals and transactions
            // Only check relevant tables.
            List <string> TablesToCheck = new List <string>();

            TablesToCheck.Add(FMainDS.ABatch.TableName);
            TablesToCheck.Add(FMainDS.AJournal.TableName);
            TablesToCheck.Add(FMainDS.ATransaction.TableName);
            TablesToCheck.Add(FMainDS.ATransAnalAttrib.TableName);

            List <Tuple <string, int> > TableAndCountList = new List <Tuple <string, int> >();
            int AllChangesCount = 0;

            if (FMainDS.HasChanges())
            {
                // Work out how many changes in each table
                foreach (DataTable dt in FMainDS.GetChanges().Tables)
                {
                    string currentTableName = dt.TableName;

                    if ((dt != null) &&
                        TablesToCheck.Contains(currentTableName) &&
                        (dt.Rows.Count > 0))
                    {
                        int tableChangesCount = 0;

                        DataTable dtChanges = dt.GetChanges();

                        foreach (DataRow dr in dtChanges.Rows)
                        {
                            if (DataUtilities.DataRowColumnsHaveChanged(dr))
                            {
                                tableChangesCount++;
                                AllChangesCount++;
                            }
                        }

                        if (tableChangesCount > 0)
                        {
                            TableAndCountList.Add(new Tuple <string, int>(currentTableName, tableChangesCount));
                        }
                    }
                }
            }

            // Now build up a sensible message
            AMessage = String.Empty;

            if (TableAndCountList.Count > 0)
            {
                int nBatches      = 0;
                int nJournals     = 0;
                int nTransactions = 0;

                foreach (Tuple <string, int> TableAndCount in TableAndCountList)
                {
                    if (TableAndCount.Item1.Equals(ABatchTable.GetTableName()))
                    {
                        nBatches = TableAndCount.Item2;
                    }
                    else if (TableAndCount.Item1.Equals(AJournalTable.GetTableName()))
                    {
                        nJournals = TableAndCount.Item2;
                    }
                    else if (TableAndCount.Item2 > nTransactions)
                    {
                        nTransactions = TableAndCount.Item2;
                    }
                }

                AMessage = Catalog.GetString("    You have made changes to ");
                string strBatches      = String.Empty;
                string strJournals     = String.Empty;
                string strTransactions = String.Empty;

                if (nBatches > 0)
                {
                    strBatches = String.Format("{0} {1}",
                                               nBatches,
                                               Catalog.GetPluralString("batch", "batches", nBatches));
                }

                if (nJournals > 0)
                {
                    strJournals = String.Format("{0} {1}",
                                                nJournals,
                                                Catalog.GetPluralString("journal", "journals", nJournals));
                }

                if (nTransactions > 0)
                {
                    strTransactions = String.Format("{0} {1}",
                                                    nTransactions,
                                                    Catalog.GetPluralString("transaction", "transactions", nTransactions));
                }

                bool bGotAll = (nBatches > 0) && (nJournals > 0) && (nTransactions > 0);

                if (nBatches > 0)
                {
                    AMessage += strBatches;
                }

                if (nJournals > 0)
                {
                    if (bGotAll)
                    {
                        AMessage += ", ";
                    }
                    else if (nBatches > 0)
                    {
                        AMessage += " and ";
                    }

                    AMessage += strJournals;
                }

                if (nTransactions > 0)
                {
                    if ((nBatches > 0) || (nJournals > 0))
                    {
                        AMessage += " and ";
                    }

                    AMessage += strTransactions;
                }

                AMessage += Environment.NewLine + Catalog.GetString("(some of the changes may include related background items)");
                AMessage += Environment.NewLine;
                AMessage += String.Format(TFrmPetraEditUtils.StrConsequenceIfNotSaved, Environment.NewLine);
            }

            return(AllChangesCount);
        }
Example #28
0
        /// <summary>
        /// Saves the provided entity into the provided data store.
        /// </summary>
        /// <param name="entity">The entity to save to the data store.</param>
        /// <param name="handleReferences">A value indicating whether to delete old references and save new references.</param>
        public override void Save(IEntity entity, bool handleReferences)
        {
            using (LogGroup logGroup = LogGroup.StartDebug("Saving entity of type '" + entity.ShortTypeName + "'."))
            {
                if (entity == null)
                {
                    throw new ArgumentNullException("entity");
                }

                if (entity.ID == Guid.Empty)
                {
                    throw new ArgumentException("entity.ID must be set.");
                }

                // Clone the entity so that it doesn't get bound to the store
                IEntity clonedEntity = entity.Clone();

                Db4oDataStore store = (Db4oDataStore)GetDataStore(clonedEntity);

                if (store.ObjectContainer == null)
                {
                    throw new InvalidOperationException("The ObjectContainer has not been initialized on the '" + store.Name + "' data store.");
                }

                using (Batch batch = BatchState.StartBatch())
                {
                    if (EntitiesUtilities.IsReference(clonedEntity.GetType()) && DataAccess.Data.IsStored(clonedEntity))
                    {
                        LogWriter.Debug("Existing reference found. Skipping save.");
                        // Just skip the saving altogether, if the reference already exists
                    }
                    else
                    {
                        if (clonedEntity == null)
                        {
                            throw new ArgumentNullException("entity");
                        }

                        LogWriter.Debug("Entity type: " + clonedEntity.GetType().ToString());
                        LogWriter.Debug("Entity ID: " + clonedEntity.ID.ToString());

                        PreSave(clonedEntity, handleReferences);

                        if (clonedEntity != null)
                        {
                            DataUtilities.StripReferences(clonedEntity);

                            // Save the entity
                            store.ObjectContainer.Store(clonedEntity);

                            // Post save the original entity NOT the cloned entity
                            PostSave(entity);

                            store.Commit();

                            LogWriter.Debug("Entity stored in '" + store.Name + "' store.");
                        }
                        else
                        {
                            LogWriter.Debug("Cloned entity == null. Not stored.");
                        }
                    }
                }
            }
        }
Example #29
0
        public static Int32 FieldChangeAdjustment(Int32 ALedgerNumber,
                                                  Int64 ARecipientKey,
                                                  DateTime AStartDate,
                                                  DateTime AEndDate,
                                                  Int64 AOldField,
                                                  DateTime ADateCorrection,
                                                  bool AWithReceipt)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            GiftBatchTDS   oldGiftDS   = new GiftBatchTDS();

            try
            {
                // find all gifts that need reversing.
                // criteria:
                // posted gift batches only
                // no adjusted/reversed gifts
                // date of gift batch in specified date range
                // recipient field is the old field
                string SqlStmt = TDataBase.ReadSqlFile("Gift.GetGiftsToReverse.sql");

                List <OdbcParameter> parameters = new List <OdbcParameter>();
                OdbcParameter        param      = new OdbcParameter("LedgerNumber", OdbcType.Int);
                param.Value = ALedgerNumber;
                parameters.Add(param);
                param       = new OdbcParameter("StartDate", OdbcType.Date);
                param.Value = AStartDate;
                parameters.Add(param);
                param       = new OdbcParameter("EndDate", OdbcType.Date);
                param.Value = AEndDate;
                parameters.Add(param);
                param       = new OdbcParameter("RecipientKey", OdbcType.BigInt);
                param.Value = ARecipientKey;
                parameters.Add(param);
                param       = new OdbcParameter("OldField", OdbcType.BigInt);
                param.Value = AOldField;
                parameters.Add(param);

                DBAccess.GDBAccessObj.Select(oldGiftDS, SqlStmt, oldGiftDS.AGiftDetail.TableName, Transaction, parameters.ToArray());

                // load the gift and the gift batch records if they have not been loaded yet
                foreach (AGiftDetailRow giftdetail in oldGiftDS.AGiftDetail.Rows)
                {
                    oldGiftDS.AGift.DefaultView.RowFilter = String.Format("{0} = {1} and {2} = {3}",
                                                                          AGiftTable.GetBatchNumberDBName(),
                                                                          giftdetail.BatchNumber,
                                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                                          giftdetail.GiftTransactionNumber);

                    if (oldGiftDS.AGift.DefaultView.Count == 0)
                    {
                        AGiftTable tempGiftTable =
                            AGiftAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                         giftdetail.BatchNumber,
                                                         giftdetail.GiftTransactionNumber,
                                                         Transaction);
                        oldGiftDS.AGift.Merge(tempGiftTable);
                    }

                    oldGiftDS.AGiftBatch.DefaultView.RowFilter = String.Format("{0} = {1}",
                                                                               AGiftTable.GetBatchNumberDBName(),
                                                                               giftdetail.BatchNumber);

                    if (oldGiftDS.AGiftBatch.DefaultView.Count == 0)
                    {
                        AGiftBatchTable tempGiftBatchTable =
                            AGiftBatchAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                              giftdetail.BatchNumber,
                                                              Transaction);
                        oldGiftDS.AGiftBatch.Merge(tempGiftBatchTable);
                    }
                }

                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            catch (Exception)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
                throw;
            }

            // we need to create a gift batch for each set of gifts with the same Currency, BankAccountCode, BankCostCentre, and Gift Type
            SortedList <string, GiftBatchTDS> NewGiftBatches = new SortedList <string, GiftBatchTDS>();

            foreach (GiftBatchTDSAGiftDetailRow oldGiftDetail in oldGiftDS.AGiftDetail.Rows)
            {
                // get the gift batch row for this detail
                oldGiftDS.AGiftBatch.DefaultView.RowFilter =
                    String.Format("{0} = {1}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber);

                AGiftBatchRow oldGiftBatch = (AGiftBatchRow)oldGiftDS.AGiftBatch.DefaultView[0].Row;

                GiftBatchTDS GiftDS = CreateNewGiftBatch(NewGiftBatches, oldGiftBatch, ADateCorrection);

                AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

                // get the gift row for this detail
                DataView v = oldGiftDS.AGift.DefaultView;
                v.RowFilter =
                    String.Format("{0} = {1} and {2} = {3}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber,
                                  AGiftTable.GetGiftTransactionNumberDBName(), oldGiftDetail.GiftTransactionNumber);

                AGiftRow oldGift = (AGiftRow)v[0].Row;

                AGiftRow gift = GiftDS.AGift.NewRowTyped();
                gift.LedgerNumber          = giftbatchRow.LedgerNumber;
                gift.BatchNumber           = giftbatchRow.BatchNumber;
                gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1;
                gift.DonorKey    = oldGift.DonorKey;
                gift.DateEntered = ADateCorrection;
                giftbatchRow.LastGiftNumber++;
                GiftDS.AGift.Rows.Add(gift);

                if (!AWithReceipt)
                {
                    gift.ReceiptLetterCode = "NO*RECET";
                }

                // reverse the original gift
                GiftBatchTDSAGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftAmount            = detail.GiftAmount * -1;
                detail.GiftAmountIntl        = detail.GiftAmountIntl * -1;
                detail.GiftTransactionAmount = detail.GiftTransactionAmount * -1;
                gift.LastDetailNumber++;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // create the detail for the corrected gift to the new field
                detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftCommentOne        = String.Format(Catalog.GetString("posted on {0}"), oldGiftBatch.GlEffectiveDate.ToShortDateString());
                gift.LastDetailNumber++;

                // TODO: calculate costcentre code from current commitment; this currently is done only at time of posting
                // detail.RecipientLedgerNumber = oldGiftDetail.RecipientLedgerNumber;
                // detail.CostCentreCode = oldGiftDetail.CostCentreCode;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // TODO: how to make sure that the gl transaction is marked as System generated? avoid display on HOSA?

                // mark original gift detail as modified
                oldGiftDetail.ModifiedDetail = true;
            }

            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = TSubmitChangesResult.scrOK;

            for (Int32 batchCounter = 0; batchCounter < NewGiftBatches.Count; batchCounter++)
            {
                if (result == TSubmitChangesResult.scrOK)
                {
                    GiftBatchTDS GiftDS = NewGiftBatches.Values[batchCounter];
                    result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS, out VerificationResult);
                }
            }

            if (result == TSubmitChangesResult.scrOK)
            {
                result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref oldGiftDS, out VerificationResult);

                if ((result == TSubmitChangesResult.scrOK) && (NewGiftBatches.Count > 0))
                {
                    return(NewGiftBatches.Values[0].AGiftBatch[0].BatchNumber);
                }
            }

            return(-1);
        }
Example #30
0
        /// <summary>
        /// Refresh the data in the grid and the details after the database content was changed on the server
        /// </summary>
        public void RefreshAllData(bool AShowStatusDialogOnLoad = true, bool AIsMessageRefresh = false)
        {
            TFrmRecurringGiftBatch myParentForm = (TFrmRecurringGiftBatch)ParentForm;

            // Remember our current row position
            int nCurrentRowIndex    = GetSelectedRowIndex();
            int nCurrentBatchNumber = -1;

            if ((myParentForm != null) && (myParentForm.InitialBatchNumber > 0))
            {
                nCurrentBatchNumber             = myParentForm.InitialBatchNumber;
                myParentForm.InitialBatchNumber = -1;
            }
            else if (AIsMessageRefresh)
            {
                if (FPetraUtilsObject.HasChanges && !myParentForm.SaveChanges())
                {
                    string msg = String.Format(Catalog.GetString("A validation error has occured on the Recurring Gift Batches" +
                                                                 " form while trying to refresh.{0}{0}" +
                                                                 "You will need to close and reopen the Recurring Gift Batches form to see the new batch" +
                                                                 " after you have fixed the validation error."),
                                               Environment.NewLine);

                    MessageBox.Show(msg, "Refresh Recurring Gift Batches");
                    return;
                }

                nCurrentBatchNumber = 1;
            }
            else if (FPreviouslySelectedDetailRow != null)
            {
                nCurrentBatchNumber = FPreviouslySelectedDetailRow.BatchNumber;
            }

            TFrmRecurringGiftBatch parentForm = (TFrmRecurringGiftBatch)ParentForm;
            Cursor prevCursor = null;

            if (parentForm != null)
            {
                prevCursor = parentForm.Cursor;
            }
            else
            {
                prevCursor = this.Cursor;
            }

            parentForm.Cursor = Cursors.WaitCursor;

            if ((FMainDS != null) && (FMainDS.ARecurringGiftBatch != null))
            {
                // Remove all data from our DataSet object - the grid will go empty!
                FMainDS.ARecurringGiftBatch.Rows.Clear();
            }

            try
            {
                FPetraUtilsObject.DisableDataChangedEvent();

                FMainDS.Merge(TRemote.MFinance.Gift.WebConnectors.LoadARecurringGiftBatch(FLedgerNumber));

                // Now we can select the gift batch we had before (if it still exists on the grid)
                for (int i = 0; (i < FMainDS.ARecurringGiftBatch.Rows.Count); i++)
                {
                    if (FMainDS.ARecurringGiftBatch[i].BatchNumber == nCurrentBatchNumber)
                    {
                        DataView dv            = ((DevAge.ComponentModel.BoundDataView)grdDetails.DataSource).DataView;
                        Int32    RowNumberGrid = DataUtilities.GetDataViewIndexByDataTableIndex(dv, FMainDS.ARecurringGiftBatch, i) + 1;

                        nCurrentRowIndex = RowNumberGrid;
                        break;
                    }
                }

                ShowDetails(nCurrentRowIndex);

                UpdateRecordNumberDisplay();

                TUC_RecurringGiftTransactions TransactionForm = parentForm.GetTransactionsControl();

                if (TransactionForm != null)
                {
                    parentForm.EnableTransactions(grdDetails.Rows.Count > 1);

                    // if the batch number = -1 then this is not a valid instance of TUC_GiftTransactions and we do not need to refresh
                    if (TransactionForm.FBatchNumber != -1)
                    {
                        TransactionForm.ShowStatusDialogOnLoad = AShowStatusDialogOnLoad;

                        // This will update the transactions to match the current batch
                        TransactionForm.RefreshData();

                        TransactionForm.ShowStatusDialogOnLoad = true;
                    }
                }
            }
            finally
            {
                FPetraUtilsObject.EnableDataChangedEvent();
                parentForm.Cursor = prevCursor;
            }
        }