public void AddRentMaterialsToRentLedgerAndRentalItemActivitySet(ModelTMSContainer ControlObjectContext, RentLedger rl)
        {
            LoadOrderLines();

            // add each rental item line
            foreach (RentalItemActivityListItem ria in OrderLines)
            {
                RentalItemActivity riaactivity = new RentalItemActivity();

                // hookup items
                riaactivity.RentalItem = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemSet", "Id", ria.RentalItemId)) as RentalItem;

                // create rentalitemactivity line
                riaactivity.RentStartDateTime         = StartRentDate;
                riaactivity.RentEndStartDateTime      = EndRentDate;
                riaactivity.Description               = riaactivity.RentalItem.Description;
                riaactivity.InvoiceStatus             = "Open";
                riaactivity.CalculatedRentPrice       = ria.RentPrice;
                riaactivity.BaseRentPrice             = ria.RentPrice;
                riaactivity.DiscountPercentage        = ria.DiscountPercentage;
                riaactivity.VATRentPrice              = ria.Vat;
                riaactivity.TotalRentPrice            = ria.TotalRentPrice;
                riaactivity.IsTreatedAsAdvancePayment = ria.TreatAsAdvancePayment;
                riaactivity.GenerateDescription();

                riaactivity.UpdateAdvancePaymentStatus(ControlObjectContext, true, ria.TreatAsAdvancePayment);

                rl.RentalItemActivity.Add(riaactivity);
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            bool SetVis = false;

            // if there is a dataitem with a valid invoice then switch screen elements on/off
            if ((DataItem != null) && ((DataItem as RentalItemActivity).InvoiceLine != null))
            {
                // poup button
                URLPopUpControl_RentInvoice.URLToPopup = "WebFormPopup.aspx?uc=InvoiceBase&Id=" + (DataItem as RentalItemActivity).InvoiceLine.Invoice.Id.ToString();
                URLPopUpControl_RentInvoice.Visible    = true;

                // if Invoice is corrected or processed then disable price adjustments
                RentalItemActivity ria = (DataItem as RentalItemActivity);
                SetVis = ((!ria.InvoiceLine.Invoice.IsCorrected) && (ria.InvoiceLine.Invoice.InvoiceStatus == "Open"));
            }
            else
            {
                URLPopUpControl_RentInvoice.Visible = false;
            }

            ButtonRecalc.Visible = SetVis;
            CheckBoxChangeInvoiceLine.Visible   = SetVis;
            CheckBoxBasedOnOfficialRent.Visible = SetVis;

            TextBox_CalculatedRentPrice.Enabled = SetVis;
            TextBox_DiscountPercentage.Enabled  = SetVis;
            CalendarControl_RentStartDateTime_SelectedDateTime.Enabled    = SetVis;
            CalendarControl_RentEndStartDateTime_SelectedDateTime.Enabled = SetVis;
        }
        public void DisableItemsAndSendMail(ModelTMSContainer _ControlObjectContext)
        {
            // disable item
            Guid Temp;

            LabelDisabledItems.Text = "";
            foreach (GridViewRow gvr in GridViewRentedOutMaterials.Rows)
            {
                // need this item be disabled?
                if ((gvr.Cells[0].Controls[3] as RadioButtonList).SelectedIndex >= 1)
                {
                    // disable item
                    Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);

                    // get the corresponding RentalItemActivitySet
//                    RentalItemActivity ria = _ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
                    RentalItemActivity ria = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;

                    // and disable
                    ria.RentalItem.SendDisabledEMail(true);

                    LabelDisabledItems.Text = ria.RentalItem.Id.ToString() + ";" + LabelDisabledItems.Text;
                }
            }
        }
        public void ResetRentalItemStatus(ModelTMSContainer ControlObjectContext)
        {
            foreach (GridViewRow gvr in GridViewRentedOutMaterials.Rows)
            {
                Guid Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);

                // get the corresponding RentalItemActivitySet
//                RentalItemActivity ria = ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
                RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;

                ria.CheckInvoiceStatus();
            }
        }
        private Location GetFirstLocation(ModelTMSContainer ControlObjectContext)
        {
            Guid Temp;

            foreach (GridViewRow gvr in GridViewRentedOutMaterials.Rows)
            {
                if ((gvr.Cells[0].Controls[1] as CheckBox).Checked)
                {
                    Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);
                    RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;
                    return(ria.RentLedger.Location);
                }
            }
            return(null);
        }
        public void UpdateRentalItemStatus(ModelTMSContainer ControlObjectContext)
        {
            foreach (GridViewRow gvr in GridViewRentedOutMaterials.Rows)
            {
                Guid Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);

                // get the corresponding RentalItemActivitySet
//                RentalItemActivity ria = ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
                RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;

                if ((ria.InvoiceLine != null) && ((gvr.Cells[0].Controls[1] as CheckBox).Checked))
                {
                    ria.InvoiceStatus = (gvr.Cells[0].Controls[3] as RadioButtonList).SelectedValue;
                }
            }
        }
        protected void ButtonRecalc_Click(object sender, EventArgs e)
        {
            RentalItemActivity ria = (DataItem as RentalItemActivity);

            SaveDataIntoDataItemFromControls();

            ria.RecalcRentPrice(CheckBoxBasedOnOfficialRent.Checked);
            if (CheckBoxChangeInvoiceLine.Checked)
            {
                ria.UpdateLinkedInvoiceLine();
            }
            ria.UpdateAdvancePaymentStatus(ControlObjectContext, CheckBoxChangeInvoiceLine.Checked, CheckBox_IsTreatedAsAdvancePayment_Checked.Checked);

            RebindControls();

            StandardButtonSaveClickHandler(sender, e);
        }
        protected void GridViewRentedOutMaterials_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DateTime EndDateRent;

            if (e.Row.DataItem != null)
            { // register the row id in the hint
                (e.Row.Cells[0].Controls[1] as CheckBox).ToolTip = (e.Row.DataItem as DbDataRecord).GetValue(0).ToString();
                (e.Row.Cells[0].Controls[1] as CheckBox).Checked = RentalNr > 0;

                // get the combobox
                ComboBox cbx = (e.Row.Cells[8].Controls[3] as ComboBox);

                // grab the possible new enddate from the grid
                EndDateRent = new DateTime(2100, 1, 1);
                try
                {
                    EndDateRent = Convert.ToDateTime((e.Row.DataItem as DbDataRecord).GetValue(4));
                    EndDateRent = Convert.ToDateTime((e.Row.Cells[4].Controls[0]).ToString()); // original value
                }
                catch { }

                ObjectQuery Results = ControlObjectContext.CreateQuery <RentalItem>(MaterialAvailableQuery,
                                                                                    new ObjectParameter("RentalType", (e.Row.DataItem as DbDataRecord).GetValue(2)),
                                                                                    new ObjectParameter("LocationId", (e.Row.DataItem as DbDataRecord).GetValue(1)),
                                                                                    new ObjectParameter("StartDate", (e.Row.DataItem as DbDataRecord).GetValue(3)),
                                                                                    new ObjectParameter("EndDate", EndDateRent),
                                                                                    new ObjectParameter("BorderEndDate", new DateTime(2100, 1, 1)));

                LoadComboBox(cbx, Results);

                URLPopUpControl upc = (e.Row.Cells[8].Controls[5] as URLPopUpControl);
                // get the corresponding RentalItemActivitySet
                Guid Temp = new Guid((e.Row.DataItem as DbDataRecord).GetValue(0).ToString());
//                RentalItemActivity ria = ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
                RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;
                upc.Visible = false;
                if ((ria != null) && (ria.InvoiceLine != null))
                {
                    upc.Visible    = true;
                    upc.URLToPopup = "WebFormPopup.aspx?UC=InvoiceBase&Id=" + ria.InvoiceLine.Invoice.Id.ToString();
                }
            }
        }
        public int NrOfInvoicedItems()
        {
            int Result = 0;

            foreach (GridViewRow gvr in GridViewRentedOutMaterials.Rows)
            {
                Guid Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);

                // get the corresponding RentalItemActivitySet
//                RentalItemActivity ria = ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
                RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;

                if ((ria.InvoiceLine != null) && ((gvr.Cells[0].Controls[1] as CheckBox).Checked))
                {
                    Result++;
                }
            }

            return(Result);
        }
        public void SwapItems(ModelTMSContainer _ControlObjectContext)
        {
            // disable item
            LabelNewRIAId.Text = "";
            Guid Temp;
            Guid RentalItemGuid;

            foreach (GridViewRow gvr in GridViewRentedOutMaterials.Rows)
            {
                // need this item be swapped?
                // get the combobox
                ComboBox cbx = (gvr.Cells[8].Controls[3] as ComboBox);
                if (cbx.SelectedIndex >= 1)
                {
                    // get the corresponding RentalItemActivitySet
                    Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);
//                    RentalItemActivity ria = _ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
                    RentalItemActivity ria = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;

                    // and swap
                    RentalItemActivity NewRia = ria.CloneToNew(_ControlObjectContext);
                    RentalItemGuid = new Guid(cbx.SelectedValue);
//                    NewRia.RentalItem = _ControlObjectContext.RentalItemSet.Where(m => m.Id == RentalItemGuid).First<RentalItem>();
                    NewRia.RentalItem = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemSet", "Id", RentalItemGuid)) as RentalItem;
                    // make sure that the new item's rent starts when the old item''s period ends
                    NewRia.RentEndStartDateTime = ria.RentEndStartDateTime;
                    ria.RentEndStartDateTime    = Common.CurrentClientDateTime(Session);
                    NewRia.RentStartDateTime    = ria.RentEndStartDateTime;
                    _ControlObjectContext.RentalItemActivitySet.AddObject(NewRia);

                    // recalc rent price & update the invoice line if there is an invoiceline and the invoicestatus is still open or partially paid
                    ria.RecalcRentPrice(true);
                    ria.CheckInvoiceStatus();
                    ria.UpdateLinkedInvoiceLine();
                    NewRia.RecalcRentPrice(true);

                    LabelNewRIAId.Text = NewRia.Id.ToString() + ";";
                }
            }
        }
        public void GrabUpdatedEndDateTimesForRIAs(ModelTMSContainer ControlObjectContext, bool RecalcIfChanged, bool RestoreWithOriginal)
        {
            Guid Temp;

            foreach (GridViewRow gvr in GridViewRentedOutMaterials.Rows)
            {
                Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);

                // get the corresponding RentalItemActivitySet
//                RentalItemActivity ria = ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
                RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;

                // grab the possible new enddate from the grid
                DateTime OldDateTime = ria.RentEndStartDateTime;
                try
                {
                    if (RestoreWithOriginal)
                    {
                        ria.RentEndStartDateTime = Convert.ToDateTime((gvr.Cells[3].Controls[0] as TextBox).ToolTip);
                    }
                    else
                    {
                        ria.RentEndStartDateTime = Convert.ToDateTime((gvr.Cells[4].Controls[1] as CalendarWithTimeControl).Text);
                    }
                }
                catch { }

                if (OldDateTime != ria.RentEndStartDateTime)
                {
                    ria.RecalcRentPrice(true);

                    // update the invoice line if there is an invoiceline and the invoicestatus is still open or partially paid
                    ria.CheckInvoiceStatus();
                    ria.UpdateLinkedInvoiceLine();
                }
            }
        }
        protected void ButtonUpdate_Click(object sender, EventArgs e)
        {
            // update the availability in the combo box of this line
            Button      btn  = (sender as Button);
            GridViewRow gvr  = btn.Parent.Parent as GridViewRow;
            Guid        Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);

            // get the corresponding RentalItemActivitySet
//            RentalItemActivity ria = ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
            RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;


            // grab the possible new enddate from the grid
            DateTime EndDateRent = ria.RentEndStartDateTime;

            try
            {
                EndDateRent = Convert.ToDateTime((gvr.Cells[4].Controls[1] as CalendarWithTimeControl).Text);
            }
            catch { }

            (gvr.Cells[4].Controls[1] as CalendarWithTimeControl).Text = EndDateRent.ToString();


            ObjectQuery Results = ControlObjectContext.CreateQuery <RentalItem>(MaterialAvailableQuery,
                                                                                new ObjectParameter("RentalType", ria.RentalItem.RentalType.Id),
                                                                                new ObjectParameter("LocationId", ria.RentLedger.Location.Id),
                                                                                new ObjectParameter("StartDate", ria.RentStartDateTime),
                                                                                new ObjectParameter("EndDate", EndDateRent),
                                                                                new ObjectParameter("BorderEndDate", new DateTime(2100, 1, 1)));

            // get the combobox to reload
            ComboBox cbx = (gvr.Cells[8].Controls[3] as ComboBox);

            LoadComboBox(cbx, Results);
        }
        public void CreateNewInvoice()
        {
            bool Success = false;

            // start transaction
            using (TransactionScope TS = new TransactionScope())
            {
                try
                {
                    Invoice inv = new Invoice();

                    ControlObjectContext.AddToInvoiceSet(inv);

                    foreach (GridViewRow gvr in GridViewSelectedRentOuts.Rows)
                    {
                        if ((gvr.Cells[0].Controls[1] as CheckBox).Checked)
                        {
                            String RentID = (gvr.Cells[0].Controls[1] as CheckBox).ToolTip;

                            RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", new System.Guid(RentID))) as RentalItemActivity;

                            ria.AddRentToInvoice(ControlObjectContext, inv);
                            inv.Location = ria.RentLedger.Location;
                        }
                    }
                    inv.GenerateInvoiceNumber(ControlObjectContext);

                    inv.Relation = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RelationSet", "Id", Guid.Parse(DropDownListCustomers.SelectedValue))) as Relation;

                    inv.Description     = TextBoxDescription.Text;
                    inv.InvoiceType     = "Sell";
                    inv.InvoiceSubType  = "Rent";
                    inv.BookingDateTime = Common.CurrentClientDateTime(Session);
                    inv.Ledger          = inv.Location.BankLedger;
                    try
                    {
                        inv.DiscountPercentage = Convert.ToDouble("0" + TextBoxInvoiceDiscount.Text);
                    }
                    catch {}

                    // add bail to the invoice
                    double Bail = Convert.ToDouble(TextBoxBail.Text); // except if this fails, this should be a valid number
                    if (Bail != 0)
                    {
                        InvoiceLine iline = new InvoiceLine();
                        iline.Description       = "Borg";
                        iline.OriginalPrice     = -Bail;
                        iline.AllowDiscount     = false;
                        iline.VATPercentage     = 0;
                        iline.VATPrice          = 0;
                        iline.TotalPrice        = -Bail;
                        iline.Invoice           = inv;
                        iline.LineNumber        = iline.Invoice.InvoiceLine.Count;
                        iline.LedgerBookingCode = iline.Invoice.Location.DefaultBailPriceBookingCode;
                    }


                    LabelGeneratedInvoiceNr.Text = inv.InvoiceNumber.ToString();
                    LabelGeneratedInvoiceId.Text = inv.Id.ToString();

                    if (LabelGroupId.Text == "")
                    {
                        LabelGroupId.Text = inv.GroupCode.ToString();
                    }

                    inv.GroupCode   = new Guid(LabelGroupId.Text);
                    inv.InvoiceNote = TextBoxInvoiceNote.Text;

                    // all invoice lines to the same ledger
                    inv.AllInvoiceLinesToSameLedger(inv.Ledger);
                    inv.RecalcTotals();

                    // save the data
                    ControlObjectContext.SaveChanges(System.Data.Objects.SaveOptions.DetectChangesBeforeSave);

                    // commit the transaciton
                    TS.Complete();

                    Success = true;
                }
                catch (Exception ex)
                {
                    // rollback transaction
                    TS.Dispose();

                    // inform user
                    Common.InformUserOnTransactionFail(ex, Page);
                }
            }

            if (!Success)
            {
                CurrentPageNr--;
                EnableCurrentPageElements();
            }
        }
        public void UnprocessInvoice()
        {
            bool Success = false;

            ModelTMSContainer _ControlObjectContext = new ModelTMSContainer(Session["CustomerConnectString"].ToString(), Session);

            // start transaction
            using (TransactionScope TS = new TransactionScope())
            {
                try
                {
                    // roll back order

                    // correct invoice if there
                    if (LabelInvoiceId.Text != "")
                    {
                        Invoice CorrInvoice = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.InvoiceSet", "Id", Guid.Parse(LabelInvoiceId.Text))) as Invoice;

                        // unprocess
                        CorrInvoice.UnprocessInvoice(_ControlObjectContext, CorrInvoice.GroupCode, Common.CurrentClientDateTime(Session));
                    }

                    // correct rentalitemactivity status
                    ResetRentalItemStatus(_ControlObjectContext);

                    // remove any generated swap
                    if (LabelNewRIAId.Text != "")
                    {
                        string[] IDs = LabelNewRIAId.Text.Split(';');
                        foreach (string IDstring in IDs)
                        {
                            if (IDstring.Trim() != "")
                            {
                                RentalItemActivity NewRia = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Guid.Parse(IDstring))) as RentalItemActivity;
                                if (NewRia != null)
                                {
                                    _ControlObjectContext.RentalItemActivitySet.DeleteObject(NewRia);
                                }
                            }
                        }
                    }

                    // enable any disabled item
                    if (LabelDisabledItems.Text != "")
                    {
                        string[] IDs = LabelDisabledItems.Text.Split(';');
                        foreach (string IDstring in IDs)
                        {
                            if (IDstring.Trim() != "")
                            {
                                RentalItem NewRI = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemSet", "Id", Guid.Parse(IDstring))) as RentalItem;

                                if (NewRI != null)
                                {
                                    NewRI.ItemState = "Available";
                                }
                            }
                        }
                    }

                    // update the datetime from the original values in the grid.
                    GrabUpdatedEndDateTimesForRIAs(_ControlObjectContext, true, true);

                    // and save to persistent storage
                    _ControlObjectContext.SaveChanges(System.Data.Objects.SaveOptions.DetectChangesBeforeSave);

                    // commit
                    TS.Complete();

                    Success = true;
                }
                catch (Exception ex)
                {
                    // rollback transaction
                    TS.Dispose();

                    // inform user
                    Common.InformUserOnTransactionFail(ex, Page);
                }
            }

            if (Success)
            {
                // when success revert
                PageNr--;
                ShowCorrectElements();
            }
        }
        public void CreateNewInvoice(ModelTMSContainer ControlObjectContext)
        {
            LabelInvoiceId.Text = "";

            if ((CheckBoxInvoice.Visible && CheckBoxInvoice.Checked) ||
                (CheckBoxBailReturn.Visible && CheckBoxBailReturn.Checked))
            {
                Invoice inv = new Invoice();
                ControlObjectContext.InvoiceSet.AddObject(inv);
                Guid Temp;
                inv.Relation = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RelationSet", "Id", Guid.Parse(DropDownListCustomers.SelectedValue))) as Relation;
                inv.Ledger   = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.LedgerSet", "Id", Guid.Parse(ComboBoxLedger.SelectedValue))) as Ledger;

                // determine location
                inv.Location = GetFirstLocation(ControlObjectContext);

                inv.Description     = "Verhuurfactuur dd " + Common.CurrentClientDateTime(Session).ToString();
                inv.InvoiceType     = "Sell";
                inv.InvoiceSubType  = "Rent";
                inv.BookingDateTime = Common.CurrentClientDateTime(Session);
                if (LabelGroupId.Text == "")
                {
                    LabelGroupId.Text = Guid.NewGuid().ToString();
                }
                inv.GroupCode          = new Guid(LabelGroupId.Text);
                inv.DiscountPercentage = Convert.ToDouble("0" + TextBoxDiscount.Text);

                if ((CheckBoxInvoice.Visible && CheckBoxInvoice.Checked))
                {
                    // invoice rental item activities
                    foreach (GridViewRow gvr in GridViewRentedOutMaterials.Rows)
                    {
                        Temp = new Guid((gvr.Cells[0].Controls[1] as CheckBox).ToolTip);

                        // get the corresponding RentalItemActivitySet
//                        RentalItemActivity ria = ControlObjectContext.RentalItemActivitySet.Where(m => m.Id == Temp).First<RentalItemActivity>();
                        RentalItemActivity ria = ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RentalItemActivitySet", "Id", Temp)) as RentalItemActivity;

                        if ((CheckBoxInvoice.Visible && CheckBoxInvoice.Checked) && (ria.InvoiceLine == null))
                        {
                            ria.AddRentToInvoice(ControlObjectContext, inv);
                        }

                        if (!ria.RentLedger.Invoice.Contains(inv))
                        {
                            ria.RentLedger.Invoice.Add(inv);
                        }
                    }
                }

                // add bail to invoice if required
                if (CheckBoxBailReturn.Visible && CheckBoxBailReturn.Checked && (TextBoxBail.Text.Trim() != "0"))
                {
                    // add bail to the invoice
                    double Bail = Convert.ToDouble(TextBoxBail.Text); // except if this fails, this should be a valid number
                    if (Bail != 0)
                    {
                        InvoiceLine iline = new InvoiceLine();
                        iline.Description       = "Borg";
                        iline.OriginalPrice     = -Bail;
                        iline.AllowDiscount     = false;
                        iline.VATPercentage     = 0;
                        iline.VATPrice          = 0;
                        iline.TotalPrice        = -Bail;
                        iline.Invoice           = inv;
                        iline.LineNumber        = iline.Invoice.InvoiceLine.Count;
                        iline.LedgerBookingCode = iline.Invoice.Location.DefaultBailPriceBookingCode;
                    }
                }

                if (inv.InvoiceLine.Count > 0)
                {
                    // recalc & process invoice
                    inv.GenerateInvoiceNumber(ControlObjectContext);
                    inv.AllInvoiceLinesToSameLedger(inv.Ledger);
                    inv.RecalcTotals();

                    // save invoice id
                    LabelInvoiceId.Text = inv.Id.ToString();
                }
                else
                {
                    ControlObjectContext.InvoiceSet.DeleteObject(inv);
                }
            }
        }