protected void btnSave_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                // AccountType accType = db.AccountTypes.FirstOrDefault(a => a.AccountTypeId == Convert.ToInt32(Request.QueryString["accType"]));
                AccountTypeFeature _accountFeature;//

                if (Request.QueryString["fid"] != null)
                {
                    _accountFeature = db.AccountTypeFeatures.FirstOrDefault(f => f.AccountFeatureID == Convert.ToInt32(Request.QueryString["fid"]));
                }
                else
                {
                    _accountFeature = new AccountTypeFeature();
                }

                //_accountFeature.AccountTypeID = Convert.ToInt32(Request.QueryString["accType"]);
                _accountFeature.IsDeduction = rbtnIsDeduction.Checked;

                if (rbtnListPercentageOrFixed.SelectedIndex == 0)
                {
                    _accountFeature.IsPercentage = true;
                }
                else if (rbtnListPercentageOrFixed.SelectedIndex == 1)
                {
                    _accountFeature.IsPercentage = false;
                }

                _accountFeature.CalculateOn = Convert.ToInt32(cboCalculateOn.SelectedValue);
                _accountFeature.CalculationFrequencyID = Convert.ToInt32(cboCalulationFreq.SelectedValue);
                _accountFeature.AccountTypeID = Convert.ToInt32(Request.QueryString["accType"]);
                _accountFeature.RunByEndOfFay = chkRunByEndOfDay.Checked;
                _accountFeature.ValueToApply = Convert.ToDecimal( txtValueToApply.Text);
                _accountFeature.FeatureDescription = txtFeatureDescription.Text;

                switch (_accountFeature.CalculationFrequencyID)
                {
                    case 1://monthly
                        _accountFeature.MonthlyCalculationDay = Convert.ToInt32(cboDayOfMonth.SelectedValue);
                        break;
                    case 2://annially
                        _accountFeature.AnnualCalculationMonth = Convert.ToInt32(cboAnnualMonth.SelectedValue);
                        _accountFeature.AnnualCalculationDay = Convert.ToInt32(cboAnnualDayOfMonth.SelectedValue);
                        break;
                    case 3://custom
                        _accountFeature.HasCustomCalculationFrequency = true;
                        _accountFeature.CustomCalculationFreqNumberOfDays = Convert.ToInt32(txtCustomInterval.Text);
                        break;
                }
                // _accountFeature.IsPercentage = rbtnListPercentageOrFixed

                if (Request.QueryString["fid"] == null)
                {
                    db.AccountTypeFeatures.InsertOnSubmit(_accountFeature);
                }
                //save and redirect
                db.SubmitChanges();
                Response.Redirect("AccountTypeFeatures.aspx?accType=" + Request.QueryString["accType"]);
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                foreach (DataListItem item in DataList1.Items)
                {
                    if (((TextBox)item.FindControl("TextBox2")).Text.Trim() == "0" || ((TextBox)item.FindControl("TextBox2")).Text.Trim().Length == 0)
                    {
                        continue;
                    }
             string dd = ((TextBox)item.FindControl("TextBox1")).Text;
                    clsMobileBankerMember _tempMember = CurrentMobileBanker.Members.FirstOrDefault(m => m.MemberId == Convert.ToInt32(((HiddenField)item.FindControl("HiddenField1")).Value));
                    db.Contributions.InsertOnSubmit(new Contribution()
                                        {
                                            InvestmentId = _tempMember.CurrentSUSUInvestmentID,
                                            ContributionAmount = Convert.ToDecimal(((TextBox)item.FindControl("TextBox2")).Text),
                                            ContributionAmountInWords = Utils.ConvertMoneyToText(((TextBox)item.FindControl("TextBox2")).Text),
                                            ContributionBy = ((TextBox)item.FindControl("TextBox3")).Text,
                                            CreatedBy = HttpContext.Current.User.Identity.Name,
                                            CreatedDate = Convert.ToDateTime(((TextBox)item.FindControl("TextBox1")).Text),
                                            Description = "SUSU contribution submitted by mobile banker",
                                            RecievedBy = HttpContext.Current.User.Identity.Name,
                                            IsDeleted = false,
                                            WasReceivedByMobileBanker = true,
                                            MobileBankerID = CurrentMobileBanker.MobileBankerId
                                        });

                    db.SubmitChanges();
                }

                //get the values that were entered.
                //foreach (clsMobileBankerMember item in CurrentMobileBanker.Members)
                //{
                //    db.Contributions.InsertOnSubmit(new Contribution()
                //    {
                //        InvestmentId = item.CurrentSUSUInvestmentID,
                //        ContributionAmount = item.PaidAmount,
                //        ContributionAmountInWords = Utils.ConvertMoneyToText(item.PaidAmount.ToString()),
                //        ContributionBy = item.ContributedBy,
                //        CreatedBy = HttpContext.Current.User.Identity.Name,
                //        CreatedDate = item.CreatedDate,
                //        Description = "SUSU contribution submitted by mobile banker",
                //        RecievedBy = HttpContext.Current.User.Identity.Name,
                //        IsDeleted = false,
                //        WasReceivedByMobileBanker = true
                //    });
                //    db.SubmitChanges();
                //}
            }
            Response.Redirect("MobileBankersList.aspx");
        }
Пример #3
0
 void CheckDueInvestments()
 {
     using (FinanceManagerDataContext db = new FinanceManagerDataContext())
     {
         foreach (Investment item in db.Investments.Where(i => i.InvestmentTypeId == (int)Utils.EnumInvestmentTypes.FixedDeposit))
         {
             if (DateTime.Today.Date >= item.MaturityDate.Value.Date)
             {
                 item.IsMatured = true;
                 db.SubmitChanges();
             }
         }
     }
 }
        //save investment
        protected void Button1_Click1(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                Investment inv = new Investment();
                inv.IsActive = true;
                if (RadioButtonList1.SelectedIndex == 0) //individual
                {
                    //no member selected
                    if (DropDownList1.SelectedIndex == 0)
                        return;

                    inv.Balance = 0;
                    inv.MemberID = Convert.ToInt32(DropDownList1.SelectedValue);
                    inv.InsterstRate = 0;

                    inv.InvestmentTypeId = 2; //2 for susu investments
                    db.Investments.InsertOnSubmit(inv);
                    db.SubmitChanges();

                    //audit
                    Utils.logAction("Insert", inv);

                    Response.Redirect("SUSUInvestmentContribution.aspx?InvId=" + inv.InvestmentID + "&mid=" + inv.MemberID);

                }
                else // group
                {
                    //no group selected
                    if (cboGroupName.SelectedIndex == 0)
                        return;

                    inv.Balance = 0;
                    inv.GroupId = Convert.ToInt32(cboGroupName.SelectedValue);

                    inv.InvestmentTypeId = 2; //2 for susu investments
                    db.Investments.InsertOnSubmit(inv);
                    db.SubmitChanges();

                    //audit
                    Utils.logAction("Insert", inv);

                    Response.Redirect("GroupsSUSUInvestmentContribution.aspx?InvId=" + inv.InvestmentID + "&gid=" + inv.GroupId);
                }

            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Utils.IsAuthorized("Settings_CompanyProfile", "Open");

            if(!IsPostBack)
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();
                 addressTextBox.Text=cProfile.address;

                CompanyNameTextBox.Text = cProfile.CompanyName;
                EmailTextBox.Text = cProfile.Email;
                websiteTextBox.Text = cProfile.website;
                RMFICategoryText.Text = cProfile.RMFICategory;

            }
        }
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                if (db.Loans.Any(l => l.MemberId == Convert.ToInt32(Request.QueryString["mid"]) && l.IsPaidup == false))
                {
                    //Response.Write("<script> alert('The current member has an unpaid loan. A new loan cannot be created for this member.')</script>");

                    ClientScript.RegisterClientScriptBlock(GetType(), "Javascript",
            "<script>alert('The current member has an unpaid loan. A new loan cannot be created for this member.')</script>");
                }
                else
                {
                    Response.Redirect("NewLoan_MemberPreSelected.aspx?mid=" + Request.QueryString["mid"]);
                }
            }
        }
        protected void UpdateButton_Click(object sender, EventArgs e)
        {
            Utils.IsAuthorized("Settings_CompanyProfile", "Create");

            using (FinanceManagerDataContext db = new FinanceManagerDataContext())

            {
                LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();
                cProfile.address = addressTextBox.Text;
                if(FileUpload1.HasFile){
                cProfile.CompanyLogo = FileUpload1.FileBytes;
                cProfile.LogoFileExt = Path.GetExtension(FileUpload1.FileName);
                };
                cProfile.CompanyName = CompanyNameTextBox.Text;
                cProfile.Email = EmailTextBox.Text;
                cProfile.website = websiteTextBox.Text;
                cProfile.RMFICategory = RMFICategoryText.Text;

                db.SubmitChanges();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //fix Account types
            FinanceManagerDataContext db = new FinanceManagerDataContext();
            foreach (Member item in db.Members)
            {
                try
                {
                    Investment tempInvestment = item.Investments.FirstOrDefault(i => i.InvestmentTypeId == 1 || i.InvestmentTypeId == 2);
                    tempInvestment.InvestmentTypeId = 1; //change investment type to local ....This applies tp Imperial trust
                    tempInvestment.AccountTypeId = item.AccountTypeID;

                    //create investments for those accounts that dont have investment
                    if (item.Investments.Count == 0)
                    {
                        item.Investments.Add(new Investment()
                        {
                            AccountTypeId = item.AccountTypeID,
                            CreatedBy = User.Identity.Name,
                            CreatedDate = DateTime.Now,
                            InvestmentTypeId = 1,
                            IsActive = true,
                            IsDeleted = false
                        });

                        db.SubmitChanges();
                    }
                }
                catch (Exception)
                {

                }
                finally
                {
                    db.SubmitChanges();
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //set invevstment date to current date
                txtInvestmentDate.Text = DateTime.Today.ToString("dd/MM/yyyy");

                using (FinanceManagerDataContext db = new FinanceManagerDataContext())
                {
                    LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();
                    InterestTextBox.Text = cProfile.CompoundInterestRate.ToString();

                }

                //load data if investment id is passed
                if (Request.QueryString["InvId"] != null)
                {
                    LoadData(Convert.ToInt32(Request.QueryString["InvId"]));
                }

                if (Request.QueryString["mid"] != null)
                {
                    dataSection.Visible = true;
                    loanDataSection.Visible = true;
                    memberHeader.Visible = true;
                    LoanHeader.Visible = true;

                    Image1.ImageUrl = "ImageDisplay.ashx?mid=" + Request.QueryString["mid"];
                    MultiView1.SetActiveView(View1);
                }
                else if (Request.QueryString["gid"] != null)
                {

                    dvGroupdataSection.Visible = true;
                    loanDataSection.Visible = true;
                    memberHeader.Visible = true;
                    LoanHeader.Visible = true;
                    MultiView1.SetActiveView(View1);
                }

                txtStartCalculationFrom_CalendarExtender.SelectedDate = DateTime.Today.Date;
                cboInterestDuration.Items.Insert(0, new ListItem() { Value = "[Select Interest Duration]", Text = "[Select Interest Duration]" });
            }
        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();

                double principal = double.Parse(PrincipalTextBox.Text);

                // double interestRate = Convert.ToDouble(InterestTextBox.Text); //Convert.ToDouble(cProfile.CompoundInterestRate.Value);
                LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == Convert.ToInt32(cboLoanDurationType.SelectedValue));
                if (_loanDuration == null)
                    return;

                decimal period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value / 12;

                //LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue));
                double interestRate = double.Parse(InterestTextBox.Text);//Utils.CalculateInterestRateByDuration(decimal.Parse(InterestTextBox.Text), period);

                // int period = int.Parse(DurationTextBox.Text);
                int compoundType = cProfile.CompoundFrequency.Value;
                RepaymentFrequency _repaymentFrequency = null;

                //check if repayment frequency has been selected
                int _repaymentFrequencyID;
                int.TryParse(RepaymentFrequencyDropdownList.SelectedValue, out _repaymentFrequencyID);

                if (_repaymentFrequencyID > 0)
                 _repaymentFrequency = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue));

                double amount;

                if (InterestTypeDropDownList.SelectedValue == "1") //compound
                {
                    amount = Utils.calculateCompoundInterest(principal, interestRate, period, Utils.GetCompoundType(compoundType));
                }
                else //2 for simple interest
                {
                    amount = Utils.calculateSimpleInterest(principal, interestRate, period);
                }

                lblTotalAmount.Text = amount.ToString("C");

                //variable to hold period for the calculation of expectedEndDate calculation
                int tempPeriod;
                tempPeriod = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;

                DateTime expectedRepaymentEndDate = DateTime.Parse(txtStartCalculationFrom.Text).AddMonths(tempPeriod);
                TimeSpan tSpan = expectedRepaymentEndDate - DateTime.Parse(txtStartCalculationFrom.Text);
                double numberOfDaysBetweenExpectedEndDateAndNow = tSpan.TotalDays;//30 * period; //assuming there are 30 days in a month
                if (_repaymentFrequencyID > 0)
                {
                    int xx = (int)numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;
                    lblRepaymentAmountByFrequency.Text = (double.Parse(PrincipalTextBox.Text) / xx).ToString("C");
                    litFrequencyDescription.Text = RepaymentFrequencyDropdownList.SelectedItem.Text;
                    litFrequencyDescription0.Text = RepaymentFrequencyDropdownList.SelectedItem.Text;
                }
                else
                {
                    lblRepaymentAmountByFrequency.Text = "N/A";
                    litFrequencyDescription.Text = "N/A";
                    litFrequencyDescription0.Text = String.Empty;
                }

                lblDuration.Text = DurationTextBox.Text + " (" + cboLoanDurationType.SelectedItem.Text + ")";
                lblPrincipal.Text = Convert.ToDecimal(PrincipalTextBox.Text).ToString("C");
                lblInterestRate.Text = InterestTextBox.Text + "%";
            }
        }
        protected void cboInterestDuration_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                try
                {
                    LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue));
                    InterestTextBox.Text = _loanPreset.InsterestRate.ToString();
                }
                catch (Exception)
                {

                }
            }
        }
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DropDownList1.SelectedIndex > 0)
            {
                plDetails.Visible = true;
                using (FinanceManagerDataContext db = new FinanceManagerDataContext())
                {
                    int _fixedDepositeInvestmentTypeId = 3;
                    var _vwInvestments = db.vwMemberInvestmentWithTotalContributionAndWithdrawals.Where(m => m.MemberID == Convert.ToInt32(DropDownList1.SelectedValue) && DateTime.Today.Date >= m.MaturityDate.Value.Date && m.InvestmentTypeId == _fixedDepositeInvestmentTypeId);
                    FriendGridView.DataSource = _vwInvestments;
                    FriendGridView.DataBind();

                }
            }
            else
            {
                plDetails.Visible = false;
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            //withdraw all money
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                MemberWithdrawal _memberWithdrawal = new MemberWithdrawal() {
                    CreatedBy = HttpContext.Current.User.Identity.Name,
                    DateCreated = DateTime.Now,
                    IsDeleted = false,
                    InvestmentID = Convert.ToInt32( InvestmentIDHiddenField.Value),
                    Narration = "Withdrawal For Rollover",
                    WithdrawalIssuedByUserName = HttpContext.Current.User.Identity.Name, WithdrawnBy = "System", WithdrawalAmount = Convert.ToDecimal( txtFriend.Text)

                };

                //submit withdrawal changes
                db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal);

                //update the status of the current investment
                Investment _currentinvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(InvestmentIDHiddenField.Value));
                _currentinvestment.IsActive = false;

                //get company profile
                 LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();

                //get compound type -- thus, annully, monthly, weekly etc
                int compoundType = cProfile.CompoundFrequency.Value;

                LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == _currentinvestment.DurationTypeId.Value);//Convert.ToInt32(cboLoanDurationType.SelectedValue));
                if (_loanDuration == null)
                    return;

                //calculate matured amount for the new investment
                double _maturedAmountForNewInvestment;
                DateTime _maturityDate = DateTime.Now;

                decimal period = _currentinvestment.Duration.Value * _loanDuration.NumberOfMonths.Value / 12;
                if (_currentinvestment.InterestTypeId.Value == 1) //compound
                {
                    _maturedAmountForNewInvestment = Utils.calculateCompoundInterest(Convert.ToDouble(_currentinvestment.MaturedAmount.Value), Convert.ToDouble(_currentinvestment.InsterstRate.Value), period, Utils.GetCompoundType(compoundType));
                }
                else //2 for simple interest
                {
                    _maturedAmountForNewInvestment = Utils.calculateSimpleInterest(Convert.ToDouble(_currentinvestment.MaturedAmount.Value), Convert.ToDouble(_currentinvestment.InsterstRate.Value), period);
                }

                //create new investment
                Investment _newInvestment = new Investment()
                {
                    IsActive = true,
                    InvestmentTypeId = _currentinvestment.InvestmentTypeId,
                    IsMatured = false,
                    //ContributionFreqAmount = _currentinvestment.ContributionFreqAmount, //not calculating ContributionFreqAmount because after an investment is rolled over it becomes a fixed deposit
                    Duration = _currentinvestment.Duration,
                    DurationTypeId = _currentinvestment.DurationTypeId,
                    GroupId = RadioButtonList1.SelectedIndex == 1 ? _currentinvestment.GroupId : null,
                    InterestTypeId = _currentinvestment.InterestTypeId,
                    InvestmentAmount = _currentinvestment.MaturedAmount,
                    MaturedAmount = (decimal)_maturedAmountForNewInvestment,
                    InvestmentCalculationStartDate = DateTime.Today,
                    MaturityDate = _maturityDate,
                    MemberID = RadioButtonList1.SelectedIndex == 0 ? _currentinvestment.MemberID : null,
                    ParentInvestmentID = _currentinvestment.InvestmentID,
                    InsterstRate = _currentinvestment.InsterstRate
                };

                //calculate maturity date
                //variable to hold period for the calculation of MaturityDate calculation
                int tempPeriod;
                tempPeriod = Convert.ToInt32(_currentinvestment.Duration.Value) * _loanDuration.NumberOfMonths.Value;

                //start calculation from the LoanCalculationStartDate specified
                _newInvestment.MaturityDate = _newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod);

                //if the expected repayment end date falls on a weekend, move it to a working
                if (_newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday)
                {
                    _newInvestment.MaturityDate = _newInvestment.MaturityDate.Value.AddDays(2);
                }
                else if (_newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    _newInvestment.MaturityDate = _newInvestment.MaturityDate.Value.AddDays(1);
                }

                db.Investments.InsertOnSubmit(_newInvestment);
                db.SubmitChanges();

                //audit
                Utils.logAction("Insert", _newInvestment);
                Utils.logAction("Insert", _memberWithdrawal);

                //set current receipt number
                Parameter prm = db.Parameters.FirstOrDefault();

                //increase receipt number by one
                prm.ReceiptNumber++;
                Contribution _newDeposit = new Contribution()
                {
                    ContributionAmount = _currentinvestment.MaturedAmount,
                    InvestmentId = _currentinvestment.InvestmentID,
                    ContributionAmountInWords = Utils.ConvertMoneyToText(_currentinvestment.MaturedAmount.ToString()),
                    ContributionBy = "System",
                    Description = "Rollover from Investment: " + _currentinvestment.InvestmentID.ToString(),
                    ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'),
                    RecievedBy = User.Identity.Name
                };

                Response.Redirect(DropDownList1.SelectedIndex > 0 ? "MemberInvestments.aspx?mid=" + DropDownList1.SelectedValue : "GroupInvestments.aspx?gid=" + cboGroupName.SelectedValue);
            }
        }
        void runAppliedInterest(DateTime dateToApply)
        {
            //if(dateToApply.Date == ()
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                AccountType accType = db.AccountTypes.FirstOrDefault(a => a.AccountTypeId == Convert.ToInt32(DropDownList1.SelectedValue));

                //clear fail messages
                db.FailMessages.DeleteAllOnSubmit(db.FailMessages);
                db.SubmitChanges();

               #region LoopRegion

                foreach (AccountTypeFeature item in accType.AccountTypeFeatures)
                {
                    AppliedFeatureHistory _appHistory = item.AppliedFeatureHistories.LastOrDefault();
                    if (_appHistory != null)
                    {
                        if (item.CalculationFrequencyID.Value == 1) //monthly
                        {
                            //AppliedFeatureHistory _appHistory = item.AppliedFeatureHistories.LastOrDefault();
                            DateTime tempDateTime = _appHistory.AppliedForDate.Value.AddMonths(1);
                            if (tempDateTime.Date != dateToApply.Date)
                            {
                                db.FailMessages.InsertOnSubmit(new FailMessage() { FailMessageId = Guid.NewGuid(), Message = "Monthly feature was last applied on " + item.AppliedFeatureHistories.LastOrDefault().AppliedDate.Value + " which is less than a month. This feature was skipped." });
                                db.SubmitChanges();

                                continue;
                            }
                        }
                        else if (item.CalculationFrequencyID.Value == 2) //annually
                        {
                            DateTime tempDateTime = _appHistory.AppliedForDate.Value.AddYears(1);
                            if (tempDateTime != dateToApply.Date)
                            {
                                db.FailMessages.InsertOnSubmit(new FailMessage() { Message = "Annual feature was last applied on " + item.AppliedFeatureHistories.LastOrDefault().AppliedDate.Value + " which is less than a year. This feature was skipped." });
                                db.SubmitChanges();
                                continue;
                            }
                        }
                        else if (item.CalculationFrequencyID.Value == 3) //custom
                        {
                            DateTime tempDateTime = _appHistory.AppliedForDate.Value.AddDays(item.CustomCalculationFreqNumberOfDays.Value);
                            if (_appHistory.AppliedForDate.Value.AddDays(item.CustomCalculationFreqNumberOfDays.Value) != dateToApply.Date)
                            {
                                db.FailMessages.InsertOnSubmit(new FailMessage() { Message = "Custom feature was last applied on " + item.AppliedFeatureHistories.LastOrDefault().AppliedDate.Value + " which is less than " + item.CustomCalculationFreqNumberOfDays.Value + " day(s). This feature was skipped." });
                                db.SubmitChanges();
                                continue;
                            }
                        }
                    }

                    AppliedFeatureHistory appliedFeatureHistory = new AppliedFeatureHistory();
                    appliedFeatureHistory.AccountTypeFeatureID = item.AccountFeatureID;
                    appliedFeatureHistory.ActionInitiatedBy = "Manually run";
                    appliedFeatureHistory.AppliedBy = User.Identity.Name;
                    switch (item.CalculateOn)
                    {
                        case 1:
                            #region MemberRegion
                            List<Member> accountMembers = new List<Member>();

                           accountMembers.AddRange(accType.Members.Where(m => m.IsDeleted == false && (dateToApply - m.CreatedDate.Value.AddMonths(1)).Days >= 0));
                            //accountMembers.AddRange(accType.Members.Where(m => m.IsDeleted == false && (dateToApply - m.CreatedDate.Value.AddMonths(1)).Days >= 28));

                            foreach (Member Memberitem in accType.Members)
                            {

                            }

                            foreach (Member item_member in accType.Members.Where(m => m.IsDeleted == false && (dateToApply - m.CreatedDate.Value.AddMonths(1)).Days >= 29))
                            {
                                //accountMembers.Add(item_member);
                            }

                            foreach (Member member in accountMembers)
                            {
                                Investment tempInv = member.Investments.FirstOrDefault(i => i.AccountTypeId == member.AccountType.AccountTypeId);

                                if (tempInv == null) //for some reason member doesn't have an investment. Add an investment
                                {
                                    continue;
                                }

                                int investmentID = tempInv.InvestmentID;

                                decimal valueToapply; decimal balance;
                                balance = Utils.GetMemberBalance(member.MemberId, dateToApply.Date);
                                if (item.IsPercentage.Value)
                                {
                                    valueToapply = (item.ValueToApply.Value / 100) * balance;
                                }
                                else
                                {
                                    valueToapply = item.ValueToApply.Value;
                                }

                                AppliedAccountFeature aFeature = new AppliedAccountFeature();
                                aFeature.AccountNumber = member.AccountNumber;
                                aFeature.AccountTypeFeatureID = item.AccountFeatureID;
                                aFeature.AppliedValue = item.IsDeduction.Value ? valueToapply * -1 : valueToapply;
                                aFeature.CreatedBy = User.Identity.Name;
                                aFeature.CreatedDate = DateTime.Now;
                                aFeature.InvestmentID = investmentID;
                                aFeature.Narration = "Account type feature manually applied.";

                                appliedFeatureHistory.AppliedAccountFeatures.Add(aFeature);
                                // db.AppliedAccountFeatures.InsertOnSubmit(aFeature);

                                if (item.IsDeduction.Value) //insert into appliedCharges Table
                                {
                                    AppliedDeduction aDeduction = new AppliedDeduction();
                                    aDeduction.CreatedBy = User.Identity.Name;
                                    aDeduction.CreatedDate = DateTime.Now;
                                    aDeduction.DeductionAmount = valueToapply;
                                    aDeduction.InvestmentID = aFeature.InvestmentID;
                                    aDeduction.Rate = item.ValueToApply;
                                    aDeduction.Narration = "Service charge";
                                    aDeduction.AppliedFor = dateToApply;
                                    aDeduction.IsDeleted = false;

                                    //db.AppliedDeductions.InsertOnSubmit(aDeduction);
                                    appliedFeatureHistory.AppliedDeductions.Add(aDeduction);
                                }

                                else //insert into Applied interest table
                                {
                                    AppliedInterest aInterest = new AppliedInterest();
                                    aInterest.CreatedBy = User.Identity.Name;
                                    aInterest.CreatedDate = DateTime.Now;
                                    aInterest.InterestAmount = valueToapply;
                                    aInterest.InvestmentID = aFeature.InvestmentID;
                                    aInterest.Rate = item.ValueToApply;
                                    aInterest.Narration = "Applied interest";
                                    aInterest.AppliedFor = dateToApply;
                                    aInterest.IsDeleted = false;
                                    appliedFeatureHistory.AppliedInterests.Add(aInterest);
                                    // db.AppliedInterests.InsertOnSubmit(aInterest);
                                }

                            }
                            #endregion
                            #region groupRegion
                            //run on group

                            List<LoanGroup> accountGroups = new List<LoanGroup>();

                            accountGroups.AddRange(accType.LoanGroups.Where(m => m.IsDeleted == false | m.IsDeleted == null && m.CreatedDate.Value.AddMonths(1) >= DateTime.Today.Date));

                            foreach (LoanGroup group in accountGroups)
                            {
                                int investmentTypeID = group.Investments.FirstOrDefault(i => i.InvestmentTypeId == db.AccountTypes.FirstOrDefault(a => a.AccountTypeId == group.AccountTypeId.Value).DefaultInvestmentTypeID.Value).InvestmentID;
                                decimal valueToapply; decimal balance;
                                balance = Utils.GetGroupBalance(group.GroupId, dateToApply);
                                if (item.IsPercentage.Value)
                                {
                                    valueToapply = (item.ValueToApply.Value / 100) * balance;
                                }
                                else
                                {
                                    valueToapply = item.ValueToApply.Value;
                                }

                                AppliedAccountFeature aFeature = new AppliedAccountFeature();
                                aFeature.AccountNumber = group.AccountNumber;
                                aFeature.AccountTypeFeatureID = item.AccountFeatureID;
                                aFeature.AppliedValue = item.IsDeduction.Value ? valueToapply * -1 : valueToapply;
                                aFeature.CreatedBy = User.Identity.Name;
                                aFeature.CreatedDate = DateTime.Now;
                                aFeature.InvestmentID = investmentTypeID;
                                aFeature.Narration = "Account type feature manually applied.";

                                appliedFeatureHistory.AppliedAccountFeatures.Add(aFeature);
                                //db.AppliedAccountFeatures.InsertOnSubmit(aFeature);

                                if (item.IsDeduction.Value) //insert into appliedCharges Table
                                {
                                    AppliedDeduction aDeduction = new AppliedDeduction();
                                    aDeduction.CreatedBy = User.Identity.Name;
                                    aDeduction.CreatedDate = DateTime.Now;
                                    aDeduction.DeductionAmount = valueToapply;
                                    aDeduction.InvestmentID = aFeature.InvestmentID;
                                    aDeduction.Rate = item.ValueToApply;
                                    //aDeduction.IsDeleted = false;
                                    appliedFeatureHistory.AppliedDeductions.Add(aDeduction);
                                    //db.AppliedDeductions.InsertOnSubmit(aDeduction);
                                }

                                else //insert into Applied interest table
                                {
                                    AppliedInterest aInterest = new AppliedInterest();
                                    aInterest.CreatedBy = User.Identity.Name;
                                    aInterest.CreatedDate = DateTime.Now;
                                    aInterest.InterestAmount = valueToapply;
                                    aInterest.InvestmentID = aFeature.InvestmentID;
                                    aInterest.Rate = item.ValueToApply;
                                    //aInterest.IsDeleted = false;
                                    appliedFeatureHistory.AppliedInterests.Add(aInterest);
                                    //db.AppliedInterests.InsertOnSubmit(aInterest);
                                }

                            }
                            #endregion
                            break;

                        case 4:
                            #region MemberRegion

                            List<Member> accountMembers1 = new List<Member>();

                            accountMembers1.AddRange(accType.Members.Where(m => m.IsDeleted == false && (dateToApply.Date- m.CreatedDate.Value.Date.AddMonths(1)).Days >= 0));

                            foreach (Member member in accountMembers1)
                            {
                                AccountType temAcctounType = db.AccountTypes.FirstOrDefault(a => a.AccountTypeId == member.AccountTypeID.Value);
                                int? invID = temAcctounType.DefaultInvestmentTypeID.Value;

                                Investment tempInvestment = member.Investments.FirstOrDefault(i => i.InvestmentTypeId == invID);
                                if (tempInvestment == null) //for some reason member doesn't have an investment. Add an investment
                                {
                                    continue;
                                    //tempInvestment = new Investment()
                                    //{
                                    //    AccountTypeId = item.AccountTypeID,
                                    //    CreatedBy = User.Identity.Name,
                                    //    CreatedDate = DateTime.Now,
                                    //    InvestmentTypeId = 1,
                                    //    IsActive = true,
                                    //    IsDeleted = false
                                    //};

                                    //member.Investments.Add(tempInvestment);
                                    //db.SubmitChanges();
                                }

                                int investmentTypeID = tempInvestment.InvestmentID;

                                decimal valueToapply; decimal totalWithdrawal;
                                totalWithdrawal = Utils.GetMemberTotalWithdrawalsBetweenDate(member.MemberId, dateToApply.AddMonths(-1), dateToApply);
                                //if withdrawal for the month is 0, do nothing
                                if (totalWithdrawal == 0)
                                {
                                    continue;
                                }

                                if (item.IsPercentage.Value)
                                {
                                    valueToapply = (item.ValueToApply.Value / 100) * totalWithdrawal;
                                }
                                else
                                {
                                    valueToapply = item.ValueToApply.Value;
                                }

                                AppliedAccountFeature aFeature = new AppliedAccountFeature();
                                aFeature.AccountNumber = member.AccountNumber;
                                aFeature.AccountTypeFeatureID = item.AccountFeatureID;
                                aFeature.AppliedValue = item.IsDeduction.Value ? valueToapply * -1 : valueToapply;
                                aFeature.CreatedBy = User.Identity.Name;
                                aFeature.CreatedDate = DateTime.Now;
                                aFeature.InvestmentID = investmentTypeID;
                                aFeature.Narration = "Account type feature manually applied.";

                                appliedFeatureHistory.AppliedAccountFeatures.Add(aFeature);
                                // db.AppliedAccountFeatures.InsertOnSubmit(aFeature);

                                if (item.IsDeduction.Value) //insert into appliedCharges Table
                                {

                                    AppliedDeduction aDeduction = new AppliedDeduction();
                                    aDeduction.CreatedBy = User.Identity.Name;
                                    aDeduction.CreatedDate = DateTime.Now;
                                    aDeduction.DeductionAmount = valueToapply;
                                    aDeduction.InvestmentID = aFeature.InvestmentID;
                                    aDeduction.Rate = item.ValueToApply;
                                    aDeduction.IsDeleted = false;
                                    aDeduction.Narration = "Service charge";
                                    aDeduction.AppliedFor = dateToApply;
                                    appliedFeatureHistory.AppliedDeductions.Add(aDeduction);
                                    //db.AppliedInterests.InsertOnSubmit(aInterest);
                                }

                                else //insert into Applied interest table
                                {

                                    AppliedInterest aInterest = new AppliedInterest();
                                    aInterest.CreatedBy = User.Identity.Name;
                                    aInterest.CreatedDate = DateTime.Now;
                                    aInterest.InterestAmount = valueToapply;
                                    aInterest.InvestmentID = aFeature.InvestmentID;
                                    aInterest.Rate = item.ValueToApply;
                                    aInterest.IsDeleted = false;
                                    aInterest.Narration = "Service charge";
                                    aInterest.AppliedFor = dateToApply;
                                    appliedFeatureHistory.AppliedInterests.Add(aInterest);

                                    //db.AppliedDeductions.InsertOnSubmit(aDeduction);
                                }

                            }
                            #endregion
                            #region groupRegion
                            //run on group
                            List<LoanGroup> accountGroups1 = new List<LoanGroup>();

                            accountGroups1.AddRange(accType.LoanGroups.Where(m => m.IsDeleted == false | m.IsDeleted == null && m.CreatedDate.Value.AddMonths(1) >= DateTime.Today.Date));

                            foreach (LoanGroup group in accountGroups1)
                            {
                                int investmentTypeID = group.Investments.FirstOrDefault(i => i.InvestmentTypeId == db.AccountTypes.FirstOrDefault(a => a.AccountTypeId == group.AccountTypeId.Value).DefaultInvestmentTypeID.Value).InvestmentID;
                                decimal valueToapply; decimal balance;
                                balance = Utils.GetMemberTotalWithdrawalsBetweenDate(group.GroupId, dateToApply.AddMonths(-1), dateToApply);
                                //balance = Utils.GetGroupTotalWithdrawals(group.GroupId, dateToApply);
                                if (item.IsPercentage.Value)
                                {
                                    valueToapply = (item.ValueToApply.Value / 100) * balance;
                                }
                                else
                                {
                                    valueToapply = item.ValueToApply.Value;
                                }

                                AppliedAccountFeature aFeature = new AppliedAccountFeature();
                                aFeature.AccountNumber = group.AccountNumber;
                                aFeature.AccountTypeFeatureID = item.AccountFeatureID;
                                aFeature.AppliedValue = item.IsDeduction.Value ? valueToapply * -1 : valueToapply;
                                aFeature.CreatedBy = User.Identity.Name;
                                aFeature.CreatedDate = DateTime.Now;
                                aFeature.InvestmentID = investmentTypeID;
                                aFeature.Narration = "Account type feature manually applied.";
                                appliedFeatureHistory.AppliedAccountFeatures.Add(aFeature);

                                // db.AppliedAccountFeatures.InsertOnSubmit(aFeature);

                                if (item.IsDeduction.Value) //insert into appliedCharges Table
                                {
                                    AppliedDeduction aDeduction = new AppliedDeduction();
                                    aDeduction.CreatedBy = User.Identity.Name;
                                    aDeduction.CreatedDate = DateTime.Now;
                                    aDeduction.DeductionAmount = valueToapply;
                                    aDeduction.InvestmentID = aFeature.InvestmentID;
                                    aDeduction.Rate = item.ValueToApply;
                                    aDeduction.IsDeleted = false;
                                    aDeduction.Narration = "Service charge";
                                    aDeduction.AppliedFor = dateToApply;
                                    appliedFeatureHistory.AppliedDeductions.Add(aDeduction);
                                    //db.AppliedDeductions.InsertOnSubmit(aDeduction);
                                }

                                else //insert into Applied interest table
                                {
                                    AppliedInterest aInterest = new AppliedInterest();
                                    aInterest.CreatedBy = User.Identity.Name;
                                    aInterest.CreatedDate = DateTime.Now;
                                    aInterest.InterestAmount = valueToapply;
                                    aInterest.InvestmentID = aFeature.InvestmentID;
                                    aInterest.Rate = item.ValueToApply;
                                    aInterest.Narration = "Service charge";
                                    aInterest.AppliedFor = dateToApply;
                                    aInterest.IsDeleted = false;
                                    appliedFeatureHistory.AppliedInterests.Add(aInterest);
                                    //db.AppliedInterests.InsertOnSubmit(aInterest);
                                }
                            }
                            #endregion
                            break;
                    }
                    appliedFeatureHistory.AppliedDate = DateTime.Now;
                    appliedFeatureHistory.AppliedForDate = dateToApply;

                    if (appliedFeatureHistory.AppliedInterests.Count > 0 || appliedFeatureHistory.AppliedDeductions.Count > 0)
                    {
                        db.AppliedFeatureHistories.InsertOnSubmit(appliedFeatureHistory);
                        db.SubmitChanges();
                    }
                }
                 #endregion
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //bind months
                var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
                for (int i = 0; i < months.Length; i++)
                {
                    cboAnnualMonth.Items.Add(new ListItem(months[i], (i + 1).ToString()));
                }
                using (FinanceManagerDataContext db = new FinanceManagerDataContext())
                {
                    if (Request.QueryString["accType"] != null)
                    {

                        lblActionType.Text = "Edit";
                        lblAccountTypeName.Text = db.AccountTypes.FirstOrDefault(a => a.AccountTypeId == Convert.ToInt32(Request.QueryString["accType"])).Description;

                    }
                    else
                    {
                        lblActionType.Text = "New";
                    }

                    if (Request.QueryString["fid"] != null) //load existing account Type feature
                    {
                         AccountTypeFeature _accountFeature = db.AccountTypeFeatures.FirstOrDefault(f => f.AccountFeatureID == Convert.ToInt32(Request.QueryString["fid"]));
                        rbtnIsDeduction.Checked =  _accountFeature.IsDeduction.Value;
             rbtnAddition.Checked = !_accountFeature.IsDeduction.Value;
                        if (_accountFeature.IsPercentage.Value)
                        {
                            rbtnListPercentageOrFixed.SelectedIndex = 0;
                        }
                        else
                        {
                            rbtnListPercentageOrFixed.SelectedIndex = 1;
                        }

                       cboCalculateOn.SelectedValue = _accountFeature.CalculateOn.ToString();
                       cboCalulationFreq.SelectedValue = _accountFeature.CalculationFrequencyID.ToString();
                       txtValueToApply.Text = _accountFeature.ValueToApply.ToString();
                       chkRunByEndOfDay.Checked = _accountFeature.RunByEndOfFay.Value;

            txtFeatureDescription.Text = _accountFeature.FeatureDescription  ;
                        switch (_accountFeature.CalculationFrequencyID)
                        {
                            case 1://monthly
                              cboDayOfMonth.SelectedValue =  _accountFeature.MonthlyCalculationDay.ToString();
                                break;
                            case 2://annially
                                cboAnnualMonth.SelectedValue = _accountFeature.AnnualCalculationMonth.ToString();
                                cboAnnualDayOfMonth.SelectedValue = _accountFeature.AnnualCalculationDay.ToString();
                                break;
                            case 3://custom
                                //_accountFeature.HasCustomCalculationFrequency = true;
                                txtCustomInterval.Text = _accountFeature.CustomCalculationFreqNumberOfDays.Value.ToString();
                                break;
                        }
                        RadioButtonList1_SelectedIndexChanged(sender, e);
                        cboAnnualMonth_SelectedIndexChanged(sender, e);
                        cboCalulationFreq_SelectedIndexChanged(sender, e);

                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["load"] != null)
                {
                    if (Request.QueryString["load"] == "1")
                    {
                        LoadCachedData();
                    }
                }
            }

            if (Request.QueryString["lid"] != null)
            {
                if (!IsPostBack)
                {
                    LoadExistingLoanData(Convert.ToInt32(Request.QueryString["lid"]));
                }
            }
            else
            {
                txtStartCalculationFromNew.DtSelectedDate = DateTime.Today.Date;
                txtLoanDateNew.DtSelectedDate = DateTime.Today.Date;
            }

            if (Request.QueryString["mid"] != null)
            {
                dataSection.Visible = true;
                loanDataSection.Visible = true;
                memberHeader.Visible = true;
                LoanHeader.Visible = true;

                Image1.ImageUrl = "ImageDisplay.ashx?mid=" + Request.QueryString["mid"];
                MultiView1.SetActiveView(View1);

            }
            else if (Request.QueryString["gid"] != null)
            {
                dvGroupdataSection.Visible = true;
                loanDataSection.Visible = true;
                memberHeader.Visible = true;
                LoanHeader.Visible = true;
            }

            if (!IsPostBack)
            {

                using (FinanceManagerDataContext db = new FinanceManagerDataContext())
                {
                    LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();
                    InterestTextBox.Text = cProfile.CompoundInterestRate.ToString();

                }

                cboInterestDuration.Items.Insert(0, new ListItem() { Value = "[Select Interest Duration]", Text = "[Select Interest Duration]" });
            }
        }
        decimal GetLoanBalance()
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                try
                {
                    decimal totalRepayment = 0;
                    totalRepayment = db.Loans.FirstOrDefault(l => l.LoanID == Convert.ToInt32(Request.QueryString["lid"])).Repayments.Where(r => r.isDeleted == false). Sum(r => r.RepaymentAmount).Value;
                    Loan _loan = db.Loans.FirstOrDefault(l => l.LoanID == Convert.ToInt32(Request.QueryString["lid"]));
                    lblTotalRepayment.Text = totalRepayment.ToString("C");

                    decimal totalPenalty =0;
                    //caculate total balance
                    try
                    {
                         totalPenalty = db.LoanPenalties.Where<LoanPenalty>(p => p.LoanID == _loan.LoanID && p.IsReleived == false).Sum(lp => lp.PenaltyAmount.Value);
                    }
                    catch (Exception)
                    {
                        totalPenalty = 0;
                    }
                    lblTotalPenalty.Text = totalPenalty.ToString("C");

                    if (totalPenalty <= 0)
                    {
                        lblTotalPenalty.Visible = false;
                        LitPenaltyLabel.Visible = false;
                    }
                    else
                    {
                        //change color scheme
                        DivMemberDetails.Attributes["class"] = "OverDueDataSection";
                        DivRepaymentDetails.Attributes["class"] = "OverDueDataSection";
                        DivNewRepayment .Attributes["class"] = "OverDueDataSection";
                    }

                    if (_loan.Amount.Value - totalRepayment <= 0)
                    {
                        _loan.IsPaidup = true;
                        db.SubmitChanges();

                        DivRepaymentDetails.Attributes["class"] = "DataSectionGreen";
                        DivMemberDetails.Attributes["class"] = "DataSectionGreen";
                        DivNewRepayment.Attributes["class"] = "DataSectionGreen";
                       // DivNewRepayment.Style = new CssStyleCollection(

                       Style style = new Style();
                       CssStyleCollection css = style.GetStyleAttributes(DivMemberDetails);
                        css.Add("height", "800px");

                    }

                    return _loan.Amount.Value - totalRepayment;
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }
        void loadMembers()
        {
            List<vwMembersWithInvestment> membersWithInvestments = new List<vwMembersWithInvestment>();
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                AccountType accType = db.AccountTypes.FirstOrDefault(a => a.AccountTypeId == Convert.ToInt32(DropDownList1.SelectedValue));
                if (chkOnlyMembersOlderThanAMonth.Checked )
                {
                    membersWithInvestments.AddRange(db.vwMembersWithInvestments.Where(a => a.AccountTypeID == Convert.ToInt32(DropDownList1.SelectedValue) && (DateTime.Today.Date - a.CreatedDate.Value.AddMonths(1)).Days >= 30));

                }
                else
                {
                    membersWithInvestments.AddRange(db.vwMembersWithInvestments.Where(a => a.AccountTypeID == Convert.ToInt32(DropDownList1.SelectedValue)));
                }
            }
               GridView1.DataSource = membersWithInvestments;
            GridView1.DataBind();
        }
        decimal GetLoanBalance()
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                try
                {
                    decimal totalRepayment = 0;
                    totalRepayment = db.Loans.FirstOrDefault(l => l.LoanID == Convert.ToInt32(Request.QueryString["lid"])).Repayments.Sum(r => r.RepaymentAmount).Value;
                    Loan _loan = db.Loans.FirstOrDefault(l => l.LoanID == Convert.ToInt32(Request.QueryString["lid"]));
                    lblTotalRepayment.Text = totalRepayment.ToString("C");

                    if (_loan.Amount.Value - totalRepayment <= 0)
                    {
                        _loan.IsPaidup = true;
                        db.SubmitChanges();

                       // DivMemberDetails.Style.Clear();// = "DataSectionGreen";
                       // DivMemberDetails.Attributes["class"] = "DataSectionGreen";

                    }

                    return _loan.Amount.Value - totalRepayment;
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (RadioButtonList1.SelectedIndex == 0) //individuals selected
            //{
            //    if (DropDownList1.SelectedIndex == 0 || DropDownList1.SelectedIndex == -1)
            //    {
            //        dataSection.Visible = false;
            //        loanDataSection.Visible = false;
            //        memberHeader.Visible = false;
            //        LoanHeader.Visible = false;

            //    }
            //    else
            //    {
            //        dataSection.Visible = true;
            //        loanDataSection.Visible = true;
            //        memberHeader.Visible = true;
            //        LoanHeader.Visible = true;

            //    }
            //}
            //else
            //{
            //    if (cboGroupName.SelectedIndex == 0 || cboGroupName.SelectedIndex == -1)
            //    {
            //        dvGroupdataSection.Visible = false;
            //        loanDataSection.Visible = false;
            //        memberHeader.Visible = false;
            //        LoanHeader.Visible = false;
            //    }
            //    else
            //    {
            //        dvGroupdataSection.Visible = true;
            //        loanDataSection.Visible = true;
            //        memberHeader.Visible = true;
            //        LoanHeader.Visible = true;
            //    }
            //}

            if (!IsPostBack)
            {
                //hide member and group combos
                //tblMember.Visible = false;
                //tblGroup.Visible = false;

                using (FinanceManagerDataContext db = new FinanceManagerDataContext())
                {
                    LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();
                    InterestTextBox.Text = cProfile.CompoundInterestRate.ToString();

                }

                if (Request.QueryString["InvId"] != null)
                {
                    LoadData(Convert.ToInt32(Request.QueryString["InvId"]));
                }

                if (Request.QueryString["mid"] != null)
                {
                    dataSection.Visible = true;
                    loanDataSection.Visible = true;
                    memberHeader.Visible = true;
                    LoanHeader.Visible = true;
                    Image1.ImageUrl = "ImageDisplay.ashx?mid=" + Request.QueryString["mid"];
                    MultiView1.SetActiveView(View1);
                }
                else if (Request.QueryString["gid"] != null)
                {

                    dvGroupdataSection.Visible = true;
                    loanDataSection.Visible = true;
                    memberHeader.Visible = true;
                    LoanHeader.Visible = true;

                    //dvGroupdataSection.Visible = true;
                    //loanDataSection.Visible = true;
                    //memberHeader.Visible = true;
                    //LoanHeader.Visible = true;
                }
                //txtStartCalculationFrom_CalendarExtender.SelectedDate = DateTime.Today.Date;
                //cboInterestDuration.Items.Insert(0, new ListItem() { Value = "[Select Interest Duration]", Text = "[Select Interest Duration]" });
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();

                double InvsetmentAmount = double.Parse(PrincipalTextBox.Text);
                double MaturedInvestmentAmount;// = double.Parse(lblTotalAmount.Text);

                // double interestRate = Convert.ToDouble(InterestTextBox.Text); //Convert.ToDouble(cProfile.CompoundInterestRate.Value);
                LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == Convert.ToInt32(cboLoanDurationType.SelectedValue));
                if (_loanDuration == null)
                    return;

                //int period = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;
                decimal period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value / 12;

                //LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue));
                //double interestRate = Utils.CalculateInterestRateByDuration(_loanPreset.InsterestRate.Value, period);

                //double interestRate = Utils.CalculateInterestRateByDuration(decimal.Parse(InterestTextBox.Text), period);
                double interestRate = double.Parse(InterestTextBox.Text);

                // int period = int.Parse(DurationTextBox.Text);
                int compoundType = cProfile.CompoundFrequency.Value;

                //using repayment frequency for contribution frequency
                //RepaymentFrequency _repaymentFrequency = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue));
                double amount;

                if (InterestTypeDropDownList.SelectedValue == "1") //compound
                {
                    amount = Utils.calculateCompoundInterest(InvsetmentAmount, interestRate, period, Utils.GetCompoundType(compoundType));
                }
                else //2 for simple interest
                {
                    amount = Utils.calculateSimpleInterest(InvsetmentAmount, interestRate, period);
                }

                decimal _originalInvestmentAmount = 0;
                //get an existing investment or create a new one
                Investment newInvestment;
                if (Request.QueryString["InvId"] != null)
                {
                    newInvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(Request.QueryString["InvId"]));
                    _originalInvestmentAmount = newInvestment.InvestmentAmount.Value;
                }
                else
                {
                    newInvestment = new Investment();
                }

                //set invementType to 3 for fixed deposit investment
                newInvestment.InvestmentTypeId = 3;

                //newLoan.ActualRepaymentEndDate = DateTime.Today.AddMonths(period);
               // newLoan.Amount = (decimal)amount;

                if (Request.QueryString["mid"] != null)
                {
                    newInvestment.MemberID = Convert.ToInt32(Request.QueryString["mid"]);
                }
                else
                {
                    newInvestment.GroupId = Convert.ToInt32(Request.QueryString["gid"]);
                }

                newInvestment.IsDeleted = false;
                newInvestment.InvestmentAmount = (decimal)InvsetmentAmount;
                //newInvestment.ContributionFrequencyId = _repaymentFrequency.RepaymentFrequencyId;
                newInvestment.IsMatured = false;
                newInvestment.InsterstRate = (decimal)interestRate;
                newInvestment.Duration = decimal.Parse(DurationTextBox.Text);
                newInvestment.InterestTypeId = Convert.ToInt32(InterestTypeDropDownList.SelectedValue);
                //newLoan.payWithContribution = false;
                newInvestment.InvestmentCalculationStartDate = DateWebUserControl1.DtSelectedDate;
                newInvestment.IsActive = true;
                newInvestment.InterestDurationTypeID = Convert.ToInt32(cboLoanDurationType.SelectedValue);
                //variable to hold period for the calculation of MaturityDate calculation
                int tempPeriod;
                tempPeriod = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;

                //start calculation from the LoanCalculationStartDate specified
                newInvestment.MaturityDate = newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod);

                //if the expected repayment end date falls on a weekend, move it to a working
                if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday)
                {
                   newInvestment.MaturityDate =  newInvestment.MaturityDate.Value.AddDays(2);
                }
                else if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(1);
                }

                newInvestment.DurationTypeId = Convert.ToInt32(cboLoanDurationType.SelectedValue);
                //newLoan.RawDurationEntered = DurationTextBox.Text;

                newInvestment.InvestmentCalculationStartDate = DateTime.Now;

                TimeSpan tSpan = newInvestment.MaturityDate.Value - newInvestment.InvestmentCalculationStartDate.Value;// -DateTime.Today;
                double numberOfDaysBetweenExpectedEndDateAndNow = tSpan.TotalDays;

                //int xx = (int)numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;

                //int numberOfDaysBetweenExpectedEndDateAndNow = 30 * period; //assuming there are 30 days in a month
                //decimal xx = numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;
                //newInvestment.ContributionFreqAmount = ((decimal)newInvestment.InvestmentAmount / xx);

                //maturity amount
                MaturedInvestmentAmount = amount;
                newInvestment.CreatedBy = this.User.Identity.Name;
                newInvestment.MaturedAmount = (decimal)amount;

                //set invementType to 3 for fixed deposit investment
                newInvestment.InvestmentTypeId = 3;

                Parameter prm = db.Parameters.FirstOrDefault();

                //increase receipt number by one
                prm.ReceiptNumber++;

                if (Request.QueryString["InvId"] != null)
                {
                    newInvestment.ModifiedDate = DateTime.Now;
                    newInvestment.ModifiedBy = HttpContext.Current.User.Identity.Name;

                    //audit
                    Utils.logAction("Edit", newInvestment);
                    db.SubmitChanges();

                    //make contibution if the original amount is less than the new amount otherwise make a withrawal
                    if (newInvestment.InvestmentAmount > _originalInvestmentAmount)
                    {
                        //make contribution
                        Contribution _contribution = new Contribution()
                        {
                            ContributionAmount = newInvestment.InvestmentAmount - _originalInvestmentAmount,
                            ContributionBy = "Self",
                            ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()),
                            Description = "Fixed deposit contribution as a result of a edit action on an the investment",
                            ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'),
                            RecievedBy = User.Identity.Name,
                            InvestmentId = newInvestment.InvestmentID,
                            PaymentMethodId = PaymentMethodWebUserControl1.PaymentTypeID,
                            ChequeNumber = PaymentMethodWebUserControl1.ChequeNumber,
                            IsDeleted = false,
                            CreatedDate = DateWebUserControl1.DtSelectedDate,
                            CreatedBy = HttpContext.Current.User.Identity.Name
                        };
                        _contribution.CreatedDate = DateWebUserControl1.DtSelectedDate;

                        db.Contributions.InsertOnSubmit(_contribution);
                        db.SubmitChanges();

                        //audit
                        Utils.logAction("Insert", _contribution);

                    }
                    else  if (newInvestment.InvestmentAmount < _originalInvestmentAmount)
                    {
                        //make withdrawal
                        MemberWithdrawal _memberWithdrawal = new MemberWithdrawal()
                        {
                            CreatedBy = HttpContext.Current.User.Identity.Name,
                            DateCreated = DateTime.Now,
                            IsDeleted = false,
                            WithdrawalAmount = _originalInvestmentAmount - newInvestment.InvestmentAmount ,
                            WithdrawnBy = "Self",
                            //ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()),
                            Narration = "Fixed deposit withdrawal as a result of a edit action on an the investment",
                            //ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'),
                            WithdrawalIssuedByUserName = User.Identity.Name,
                            InvestmentID = newInvestment.InvestmentID
                        };

                        db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal);
                        db.SubmitChanges();

                        //audit
                        Utils.logAction("Insert", _memberWithdrawal);
                    }
                }
                else
                {
                    newInvestment.CreatedDate = DateTime.Now;
                    db.Investments.InsertOnSubmit(newInvestment);

                    db.SubmitChanges();
                    //audit
                    Utils.logAction("Insert", newInvestment);

                    //make initial contribution if fixed deposit investment is a new one
                    //add contribution since it a fixed deposit
                    Contribution _contribution = new Contribution()
                    {
                        ContributionAmount = newInvestment.InvestmentAmount,
                        ContributionBy = "Self",
                        ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()),
                        Description = "Fixed deposit contribution",
                        ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'),
                        RecievedBy = User.Identity.Name,
                        InvestmentId = newInvestment.InvestmentID,
                        IsDeleted = false,
                        CreatedDate = DateWebUserControl1.DtSelectedDate,
                        CreatedBy = HttpContext.Current.User.Identity.Name
                    };

                    db.Contributions.InsertOnSubmit(_contribution);
                    db.SubmitChanges();

                    //audit
                    Utils.logAction("Insert", _contribution);

                }
                //ResponseHelper.Redirect(this.Response, "ContributionReceipt.aspx?cid=" + _contribution.ContributionId.ToString() + "&mid=" + _contribution.Investment.MemberID, "_blank", "menubar=0,width=100,height=100");
                if (Request.QueryString["mid"] != null)
                {
                    Response.Redirect("FixedDepositInvestmentStatement.aspx?invID=" + newInvestment.InvestmentID + "&mid=" + Request.QueryString["mid"]);
                }
                else if(Request.QueryString["gid"] != null)
                {
                    Response.Redirect("FixedDepositInvestmentStatement.aspx?invID=" + newInvestment.InvestmentID + "&gid=" + Request.QueryString["gid"]);
                }

            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();

                double InvsetmentAmount = double.Parse(PrincipalTextBox.Text);
                double MaturedInvestmentAmount;// = double.Parse(lblTotalAmount.Text);

                // double interestRate = Convert.ToDouble(InterestTextBox.Text); //Convert.ToDouble(cProfile.CompoundInterestRate.Value);
                LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == Convert.ToInt32(cboLoanDurationType.SelectedValue));
                if (_loanDuration == null)
                    return;

                //int period = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;
                decimal period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value / 12;

                //LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue));
                //double interestRate = Utils.CalculateInterestRateByDuration(_loanPreset.InsterestRate.Value, period);

                //double interestRate = Utils.CalculateInterestRateByDuration(decimal.Parse(InterestTextBox.Text), period);
                double interestRate = double.Parse(InterestTextBox.Text);

                // int period = int.Parse(DurationTextBox.Text);
                int compoundType = cProfile.CompoundFrequency.Value;

                //using repayment frequency for contribution frequency
                RepaymentFrequency _repaymentFrequency = null;            // = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue));
                //check if repayment frequency has been selected
                int _repaymentFrequencyID;
                int.TryParse(RepaymentFrequencyDropdownList.SelectedValue, out _repaymentFrequencyID);

                if (_repaymentFrequencyID > 0)
                    _repaymentFrequency = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue));

                double amount;

                if (InterestTypeDropDownList.SelectedValue == "1") //compound
                {
                    amount = Utils.calculateCompoundInterest(InvsetmentAmount, interestRate, period, Utils.GetCompoundType(compoundType));
                }
                else //2 for simple interest
                {
                    amount = Utils.calculateSimpleInterest(InvsetmentAmount, interestRate, period);
                }

                //get an existing investment or create a new one
                Investment newInvestment;
                if (Request.QueryString["InvId"] != null)
                {
                    newInvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(Request.QueryString["InvId"]));
                }
                else
                {
                    newInvestment = new Investment();
                }

                //set invementType to 1 for regular investment
                newInvestment.InvestmentTypeId = 1;

                //newLoan.ActualRepaymentEndDate = DateTime.Today.AddMonths(period);
                // newLoan.Amount = (decimal)amount;

                if (Request.QueryString["mid"] != null)
                {
                    newInvestment.MemberID = Convert.ToInt32(Request.QueryString["mid"]);
                }
                else if (Request.QueryString["gid"] != null)
                {
                    newInvestment.GroupId = Convert.ToInt32(Request.QueryString["gid"]);
                }

                newInvestment.InvestmentAmount = (decimal)InvsetmentAmount;
                if (_repaymentFrequencyID > 0)
                {
                    newInvestment.ContributionFrequencyId = _repaymentFrequency.RepaymentFrequencyId;
                }
                newInvestment.IsMatured = false;
                newInvestment.InsterstRate = (decimal)interestRate;
                newInvestment.Duration = decimal.Parse(DurationTextBox.Text);
                newInvestment.InterestTypeId = Convert.ToInt32(InterestTypeDropDownList.SelectedValue);
                //newLoan.payWithContribution = false;
                newInvestment.InvestmentCalculationStartDate = DateTime.Parse(txtStartCalculationFrom.Text);
                newInvestment.InvestmentDescriptionId = Convert.ToInt32(cboInvestmentDescription.SelectedValue);
                newInvestment.CreatedDate = Convert.ToDateTime(txtInvestmentDate.Text);

                //variable to hold period for the calculation of MaturityDate calculation
                int tempPeriod;
                tempPeriod = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;

                //start calculation from the LoanCalculationStartDate specified
                newInvestment.MaturityDate = newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod);

                //if the expected repayment end date falls on a weekend, move it to a working
                if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday)
                {
                    newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(2);
                }
                else if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(1);
                }

                newInvestment.DurationTypeId = Convert.ToInt32(cboLoanDurationType.SelectedValue);
                //newLoan.RawDurationEntered = DurationTextBox.Text;

                newInvestment.InvestmentCalculationStartDate = DateTime.Parse(txtStartCalculationFrom.Text);

                TimeSpan tSpan = newInvestment.MaturityDate.Value - newInvestment.InvestmentCalculationStartDate.Value;// -DateTime.Today;
                double numberOfDaysBetweenExpectedEndDateAndNow = tSpan.TotalDays;

                if (_repaymentFrequencyID > 0)
                {
                    int xx = (int)numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;

                    //int numberOfDaysBetweenExpectedEndDateAndNow = 30 * period; //assuming there are 30 days in a month
                    //decimal xx = numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;
                    newInvestment.ContributionFreqAmount = ((decimal)newInvestment.InvestmentAmount / xx);
                }
                else
                {
                    newInvestment.ContributionFreqAmount = 0;
                }

                //maturity amount
                MaturedInvestmentAmount = amount;
                newInvestment.CreatedBy = this.User.Identity.Name;
                newInvestment.MaturedAmount = (decimal)amount;
                newInvestment.InvestmentTypeId = 1; //investmentTypeId 1 means regular investment
                newInvestment.IsActive = true;

                if (Request.QueryString["InvId"] != null)
                {
                    newInvestment.ModifiedDate = DateTime.Now;
                    newInvestment.ModifiedBy = HttpContext.Current.User.Identity.Name;
                   // db.Investments.InsertOnSubmit(newInvestment);

                    //audit
                    Utils.logAction("Edit", newInvestment);
                }
                else
                {
                    newInvestment.CreatedDate = DateTime.Now;
                    newInvestment.CreatedBy = HttpContext.Current.User.Identity.Name;
                    db.Investments.InsertOnSubmit(newInvestment);

                    //audit
                    Utils.logAction("Insert", newInvestment);
                }
                db.SubmitChanges();

                //if (_repaymentFrequencyID > 0)
                //{
                //    Utils.GenerateContributionSchedule(tempPeriod, _repaymentFrequency, newInvestment);
                //}
                if (Request.QueryString["gid"] != null)
                {
                    Response.Redirect("InvestmentStatement_Real_Group.aspx?invID=" + newInvestment.InvestmentID + "&gid=" + Request.QueryString["gid"]);
                }
                else
                {
                    Response.Redirect("InvestmentStatement_real.aspx?invID=" + newInvestment.InvestmentID + "&mid=" + Request.QueryString["mid"]);
                }

            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();

                double principal = double.Parse(PrincipalTextBox.Text);

                // double interestRate = Convert.ToDouble(InterestTextBox.Text); //Convert.ToDouble(cProfile.CompoundInterestRate.Value);
                LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == Convert.ToInt32(cboLoanDurationType.SelectedValue));
                if (_loanDuration == null)
                    return;

                decimal period;
                if (DurationTextBox.Text.ToLower().Contains("annual") || DurationTextBox.Text.ToLower().Contains("year"))
                {
                    period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value / 12;
                }
                else
                {
                    period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;
                }

                //LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue));
                double interestRate = double.Parse(InterestTextBox.Text);//Utils.CalculateInterestRateByDuration(decimal.Parse(InterestTextBox.Text), period);

                // int period = int.Parse(DurationTextBox.Text);
                int compoundType = cProfile.CompoundFrequency.Value;
                RepaymentFrequency _repaymentFrequency = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue));
                double amount;

                if (InterestTypeDropDownList.SelectedValue == "1") //compound
                {
                    amount = Utils.calculateCompoundInterest(principal, interestRate, period, Utils.GetCompoundType(compoundType));
                }
                else //2 for simple interest
                {
                    amount = Utils.calculateSimpleInterest(principal, interestRate, period);
                }

                Loan newLoan = null;
                if (Request.QueryString["lid"] != null)
                {
                    newLoan = db.Loans.FirstOrDefault(l => l.LoanID == Convert.ToInt32(Request.QueryString["lid"]));
                }
                else
                {
                    newLoan = new Loan();
                }

                //newLoan.ActualRepaymentEndDate = DateTime.Today.AddMonths(period);
                newLoan.Amount = (decimal)amount;

                if (Request.QueryString["mid"] != null) // individuals
                {
                    newLoan.MemberId = Convert.ToInt32(Request.QueryString["mid"]);
                }
                else if (Request.QueryString["gid"] != null)// groups selected
                {
                    newLoan.GroupID = Convert.ToInt32(Request.QueryString["gid"]);
                }

                newLoan.Principal = (decimal)principal;
                newLoan.RepaymentFrequencyId = _repaymentFrequency.RepaymentFrequencyId;
                newLoan.IsPaidup = false;
                newLoan.Interest = (decimal)interestRate;
                newLoan.Duration = decimal.Parse(DurationTextBox.Text);
                newLoan.InterestTypeId = Convert.ToInt32(InterestTypeDropDownList.SelectedValue);
                newLoan.payWithContribution = false;
                newLoan.LoanCalculationStartDate = txtStartCalculationFromNew.DtSelectedDate;
                newLoan.LoanTypeID = Convert.ToInt32(cboLoanType.SelectedValue);
                newLoan.IsDeleted = false;
                newLoan.LoanDurationTypeID = Convert.ToInt32(cboLoanDurationType.SelectedValue);
                newLoan.DurationType = Convert.ToInt32(cboInterestDuration.SelectedValue);
                newLoan.CreatedDate = txtLoanDateNew.DtSelectedDate;
                //if (FileUpload1.HasFile)
                //{
                //    newLoan.LoanCollateralDocuments.Add(new LoanCollateralDocument() { DocumentContent = FileUpload1.FileBytes, FileExtension= Path.GetExtension(  FileUpload1.FileName), DocumentName = FileUpload1.FileName });
                //}
                //if (FileUpload2.HasFile)
                //{
                //    newLoan.LoanCollateralDocuments.Add(new LoanCollateralDocument() { DocumentContent = FileUpload2.FileBytes, FileExtension = Path.GetExtension(FileUpload2.FileName), DocumentName = FileUpload2.FileName });
                //}
                //if (FileUpload3.HasFile)
                //{
                //    newLoan.LoanCollateralDocuments.Add(new LoanCollateralDocument() { DocumentContent = FileUpload3.FileBytes, FileExtension = Path.GetExtension(FileUpload3.FileName), DocumentName = FileUpload3.FileName });
                //}
                //if (FileUpload4.HasFile)
                //{
                //    newLoan.LoanCollateralDocuments.Add(new LoanCollateralDocument() { DocumentContent = FileUpload4.FileBytes, FileExtension = Path.GetExtension(FileUpload4.FileName), DocumentName = FileUpload4.FileName });
                //}

                //variable to hold period for the calculation of expectedEndDate calculation
                int tempPeriod;
                tempPeriod = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;

                //start calculation from the LoanCalculationStartDate specified
                newLoan.ExpectedRepaymentEndDate = newLoan.LoanCalculationStartDate.Value.AddMonths(tempPeriod);

                //if the expected repayment end date falls on a weekend, move it to a working
                if (newLoan.ExpectedRepaymentEndDate.Value.DayOfWeek == DayOfWeek.Saturday)
                {
                    newLoan.ExpectedRepaymentEndDate = newLoan.ExpectedRepaymentEndDate.Value.AddDays(2);
                }
                else if (newLoan.ExpectedRepaymentEndDate.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    newLoan.ExpectedRepaymentEndDate = newLoan.ExpectedRepaymentEndDate.Value.AddDays(1);
                }

                newLoan.DurationType = Convert.ToInt32(cboLoanDurationType.SelectedValue);
                newLoan.RawDurationEntered = DurationTextBox.Text;

                //ensure that nothing gets assigned to the collateral ID field if nothing is selected
                if (cboCollateral.SelectedIndex > 0)
                    newLoan.CollateralID = Convert.ToInt16(cboCollateral.SelectedValue);
                newLoan.CollateralDescription = txtCollateralDesc.Text;

                //do not insert guarantor if its not selected
                if (cboGuarantor.SelectedIndex > 0)
                {
                    newLoan.GuarantorID = Convert.ToInt16(cboGuarantor.SelectedValue);
                }

               newLoan.LoanCalculationStartDate = txtStartCalculationFromNew.DtSelectedDate;

                TimeSpan tSpan = newLoan.ExpectedRepaymentEndDate.Value - newLoan.LoanCalculationStartDate.Value;
                double numberOfDaysBetweenExpectedEndDateAndNow = tSpan.TotalDays;

                // numberOfDaysBetweenExpectedEndDateAndNow = 30 * period; //assuming there are 30 days in a month
                //decimal xx = numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;
                int xx = (int)numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;
                newLoan.RepaymentFreqAmount = ((decimal)amount / xx);

                //current user
                newLoan.CreatedBy = this.User.Identity.Name;
                newLoan.CreatedDate = txtLoanDateNew.DtSelectedDate;

                if (Request.QueryString["lid"] == null)
                {
                    Utils.IsAuthorized("Loans", "Create");
                    db.Loans.InsertOnSubmit(newLoan);
                    //audit

                    newLoan.CreatedBy = HttpContext.Current.User.Identity.Name;
                    Utils.logAction("Insert", newLoan);
                }
                else
                {
                    Utils.IsAuthorized("Loans", "Edit");
                    newLoan.ModifiedBy = HttpContext.Current.User.Identity.Name;
                    newLoan.ModifiedDate = DateTime.Now;
                    Utils.logAction("Edit", newLoan);
                }

                db.SubmitChanges();

                Utils.GenerateRepaymentSchedule_new(tempPeriod, _repaymentFrequency, newLoan);

                //Response.Redirect("MemberDetails.aspx?mid=" + DropDownList1.SelectedValue);
                if (Request.QueryString["mid"] != null)
                {
                    Response.Redirect("LoanStatement.aspx?lid=" + newLoan.LoanID + "&mid=" + Request.QueryString["mid"]);
                }
                else
                {
                    Response.Redirect("LoanStatement_group.aspx?lid=" + newLoan.LoanID + "&gid=" + Request.QueryString["gid"]);
                }
            }
        }
 protected void cboGroupName_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (cboGroupName.SelectedIndex > 0)
     {
         plDetails.Visible = true;
         using (FinanceManagerDataContext db = new FinanceManagerDataContext())
         {
             var _vwInvestments = db.vwMemberInvestmentWithTotalContributionAndWithdrawals.Where(m => m.GroupId == Convert.ToInt32(cboGroupName.SelectedValue));
             FriendGridView.DataSource = _vwInvestments;
             FriendGridView.DataBind();
         }
     }
     else
     {
         plDetails.Visible = false;
     }
 }
        protected void Button1_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                decimal _currentBalance;
                bool _isChecked = false;
                int _currentInvestmentId = 0;
                bool IsAccountsSelected = false;

                //clear everthing in AppliedInterest_Temps
                db.AppliedInterest_Temps.DeleteAllOnSubmit(db.AppliedInterest_Temps);
                db.SubmitChanges();

                foreach (GridViewRow item in GridView1.Rows)
                {
                    IsAccountsSelected = true;

                    //get the current balance
                    _currentBalance = Convert.ToDecimal((item.FindControl("Label1") as Label).Text);

                    //get investmentId
                    _currentInvestmentId = Convert.ToInt32( (item.FindControl("HiddenField1") as HiddenField).Value);

                    //check if the account is selected
                    _isChecked = (item.FindControl("CheckBox1") as CheckBox).Checked;
                    if (_isChecked)
                    {
                        AppliedInterest _appliedInterest = new AppliedInterest();
                        _appliedInterest.CreatedBy = HttpContext.Current.User.Identity.Name;
                        _appliedInterest.CreatedDate = DateTime.Now;
                       // _currentInvestmentId = Convert.ToInt32(item.Cells[0].Text);
                        _appliedInterest.InterestAmount = _currentBalance * Convert.ToDecimal(TextBox1.Text)/100;
                        _appliedInterest.InvestmentID = _currentInvestmentId;
                        _appliedInterest.Rate = Convert.ToDecimal(TextBox1.Text);
                        _appliedInterest.InvestmentID = _currentInvestmentId;

                        db.AppliedInterests.InsertOnSubmit(_appliedInterest);

                        AppliedInterest_Temp _appliedInterest_temp = new AppliedInterest_Temp();
                        _appliedInterest_temp.CreatedBy = HttpContext.Current.User.Identity.Name;
                        _appliedInterest_temp.CreatedDate = DateTime.Now;
                        // _currentInvestmentId = Convert.ToInt32(item.Cells[0].Text);
                        _appliedInterest_temp.InterestAmount = _currentBalance * Convert.ToDecimal(TextBox1.Text) / 100;
                        _appliedInterest_temp.InvestmentID = _currentInvestmentId;
                        _appliedInterest_temp.Rate = Convert.ToDecimal(TextBox1.Text);
                        //_appliedInterest_temp.AppliedInterestID = _appliedInterest.AppliedInterestID;
                        _appliedInterest_temp.InvestmentID = _currentInvestmentId;

                        db.AppliedInterest_Temps.InsertOnSubmit(_appliedInterest_temp);

                    }
                }

                if (IsAccountsSelected)
                {
                    //try to see if everything will get inserted
                    db.SubmitChanges();
                    Response.Redirect("AppliedInterestForPrintReport.aspx");
                }

            }
        }
        protected void InsertButton_Click(object sender, EventArgs e)
        {
            Utils.IsAuthorized("LoanRepayment", "Create");

            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                //check if investment has any contributions that can be used as loan payment
                //update investment
                Investment _investment;
                Loan _loan = db.Loans.FirstOrDefault(l => l.LoanID == Convert.ToInt32(Request.QueryString["lid"]));
                // int _investmentID ;
                //if (Request.QueryString["invID"] == null || Request.QueryString["invID"] == "")
                if (InvestmentID != null && InvestmentID > 0)
                {
                    // _investmentID = Convert.ToInt32(Request.QueryString["invID"]);

                    _investment = Utils.GetDataContext().Investments.FirstOrDefault(i => i.InvestmentID == InvestmentID);

                    //total contributions towards the selected investment
                    decimal? totalContributions = _investment.Contributions.Sum(c => c.ContributionAmount.Value);
                    if (totalContributions != null)
                    {
                        if (totalContributions < Convert.ToDecimal(RepaymentAmountTextBox.Text))
                        {
                            ErrorLabel.Text = "Repayment amount cannot be greater than the selected investment amount.";
                            ErrorLabel.Visible = true;
                            return;
                        }
                        else
                        {
                            //update investment withdrawal
                            MemberWithdrawal _memberWithdrawal = new MemberWithdrawal()
                            {
                                CreatedBy = HttpContext.Current.User.Identity.Name,
                                DateCreated = DateTime.Now,
                                IsDeleted = false,
                                InvestmentID = InvestmentID,
                                Narration = "Payment For Loan",
                                WithdrawalAmount = Convert.ToDecimal(RepaymentAmountTextBox.Text),
                                WithdrawalIssuedByUserName = User.Identity.Name,
                                WithdrawnBy = PaidTextBox.Text //,
                               // groupi = Convert.ToInt32(Request.QueryString["gid"])
                            };
                            db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal);
                            db.SubmitChanges();

                            //audit
                            Utils.logAction("Insert", _memberWithdrawal);
                        }
                    }
                    else //contributions
                    {
                        ErrorLabel.Text = "Repayment amount cannot be greater than the selected investment amount.";
                        ErrorLabel.Visible = true;
                        return;
                    }
                }

                //set discription for repayment; payment by cash or with investment.
                string _description = Request.QueryString["invID"] == null || Request.QueryString["invID"] == "" ? "Loan repayment by cash" : "Loan repayment with investment";

                int? _repaidWithInvestmentID = InvestmentID;
                if (InvestmentID == 0)
                    _repaidWithInvestmentID = null;

                decimal _repaymentAmount = Convert.ToDecimal(RepaymentAmountTextBox.Text);
                decimal _interestRepayment = (_loan.Interest.Value / 100) * _repaymentAmount;

                Repayment _loanRepayment = new Repayment()
                {
                    LoanId = Convert.ToInt32(Request.QueryString["lid"]),
                    Description = _description,
                    RepaymentAmount = _repaymentAmount,
                    RepaymentBy = PaidTextBox.Text,
                    // CreatedDate = DateTime.Now,
                    CreatedBy = User.Identity.Name,
                    RepaidWithInvestmentID = _repaidWithInvestmentID,
                    InterestPayment = _interestRepayment,
                    PrincipalPayment = _repaymentAmount - _interestRepayment, isDeleted = false,
                    CreatedDate = DateWebUserControl1.DtSelectedDate
                };

                //set current receipt number
                Parameter prm = db.Parameters.FirstOrDefault();

                //set vale for receipt number if its zero
                if (prm.ReceiptNumber == null)
                    prm.ReceiptNumber = 0;

                prm.ReceiptNumber++;
                //pad current receipt number with zeros
                _loanRepayment.ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0');

                //set repayment amount in wores value
                _loanRepayment.RepaymentAmountInWords = Utils.ConvertMoneyToText(_loanRepayment.RepaymentAmount.ToString());

                db.Repayments.InsertOnSubmit(_loanRepayment);

                //update the selected schedule date
                if (ScheduleIDHiddenField.Value != "")
                {
                    RepaymentSchedule _repaymentSchedule = db.RepaymentSchedules.FirstOrDefault(r => r.RepaymentScheduleId == Convert.ToInt32(ScheduleIDHiddenField.Value));
                    if (_repaymentSchedule != null)
                        _repaymentSchedule.IsPaymentMade = true;
                }

                //submit changes to the database
                db.SubmitChanges();

                //audit
                Utils.logAction("Insert", _loanRepayment);

                //rebind the repayment history data
                GridView1.DataBind();

                //update the total repayment date in the UI
                GetLoanBalance();

                //rebind loan schedules dropdown
                var loanSchedules = Utils.GetDataContext().RepaymentSchedules.Where(l => l.LoanId == Convert.ToInt32(Request.QueryString["lid"]) && Convert.ToBoolean(l.IsPaymentMade) == false).OrderBy(r => r.RepaymentDate);
                FriendGridView.DataSource = loanSchedules;
                FriendGridView.DataBind();

                //clear controls
                PaidTextBox.Text = "";
                txtFriend.Text = "";
                RepaymentAmountTextBox.Text = "";

                // ScriptManager.RegisterStartupScript(this, GetType(), "Receipt", "openWindow('RepaymentReceipt.aspx?rid='" +  _loanRepayment.RepaymentId.ToString() + "&mid=" + _loanRepayment.Loan.MemberId + "');", true);
                //Response.Write("<SCRIPT language=javascript>var w=window.open('RepaymentReceipt.aspx?rid=' +  _loanRepayment.RepaymentId.ToString() + '&mid=' + _loanRepayment.Loan.MemberId','OrderStatus','height=800,width=800');</SCRIPT>");
                Response.Redirect("RepaymentReceipt_Group.aspx?rid=" + _loanRepayment.RepaymentId.ToString() + "&gid=" + _loanRepayment.Loan.GroupID);
            }
        }