Пример #1
0
    static void Main()
    {
        Deposit deposit = new Deposit(new Individual("Phili Fry"), 5000m, 5);
        deposit.DepositIn(1000m);
        Console.WriteLine(deposit.Balance);
        deposit.Withdraw(1500m);
        Console.WriteLine(deposit.Balance);
        Console.WriteLine(deposit.CalculateInterest(5));

        Console.WriteLine("-------------------");

        Loan loan = new Loan(new Individual("James"), 2000m, 20);
        loan.DepositIn(2000m);
        Console.WriteLine(loan.Balance);
        Console.WriteLine(loan.CalculateInterest(5));

        Console.WriteLine("-------------------");

        Loan companyLoan = new Loan(new Company("Telecom"), 2000m, 20);
        companyLoan.DepositIn(3000m);
        Console.WriteLine(companyLoan.Balance);
        Console.WriteLine(companyLoan.CalculateInterest(5));

        Console.WriteLine("-------------------");

        Mortgage mortgage = new Mortgage(new Individual("Bart"), 2000m, 20);
        mortgage.DepositIn(3000m);
        Console.WriteLine(mortgage.Balance);
        Console.WriteLine(mortgage.CalculateInterest(8));

        Console.WriteLine("-------------------");

        Mortgage companyMortgate = new Mortgage(new Company("Airline"), 2000m, 20);
        Console.WriteLine(companyMortgate.CalculateInterest(16));
    }
Пример #2
0
 static void Main()
 {
     //Deposit test
     Console.WriteLine("Deposit account test:");
     Deposit deposit = new Deposit(Customer.Individual, 2000m, 12.3m);
     Console.Write("Deposite interest for 3 months and 12.3 interest rate = ");
     Console.WriteLine(deposit.CalculateInterestAmount(3));
     Console.WriteLine();
     //Loan test
     Console.WriteLine("Loan account test:");
     Loan loanIndividual = new Loan(Customer.Individual, 1000m, 1.2m);
     Loan loanCompany = new Loan(Customer.Company, 4000m, 3.3m);
     Console.Write("Individual interest for 4 months and 1.2 interest rate = ");
     Console.WriteLine(loanIndividual.CalculateInterestAmount(4));
     Console.Write("Company interest for 3 months and 3.3 interest rate = ");
     Console.WriteLine(loanCompany.CalculateInterestAmount(3));
     Console.WriteLine();
     //Mortgage test
     Console.WriteLine("Mortgage account test:");
     Mortgage mortgageIndividual = new Mortgage(Customer.Individual, 40000m, 5.4m);
     Mortgage mortgageCompany = new Mortgage(Customer.Company, 120000m, 6.5m);
     Console.Write("Individual interest for 4 months and {0} interest rate = ", mortgageIndividual.InterestRate);
     Console.WriteLine(mortgageIndividual.CalculateInterestAmount(4));
     Console.Write("Individual interest for 15 months and 5.4 interest rate = ");
     Console.WriteLine(mortgageIndividual.CalculateInterestAmount(15));
     Console.Write("Company interest for 3 months and 6.5 interest rate = ");
     Console.WriteLine(mortgageCompany.CalculateInterestAmount(3));
 }
Пример #3
0
    private static void Main()
    {
        Customer customerOne = new Individual("Radka Piratka");
        Customer customerTwo = new Company("Miumiunali Brothers");

        Account[] accounts =
        {
            new Deposit(customerOne, 7000, 5.5m, 18),
            new Deposit(customerOne, 980, 5.9m, 12),
            new Loan(customerOne, 20000, 7.2m, 2),
            new Loan(customerOne, 2000, 8.5m, 9),
            new Mortgage(customerOne, 14000, 5.4m, 5),
            new Mortgage(customerOne, 5000, 4.8m, 10),
            new Deposit(customerTwo, 10000, 6.0m, 12),
            new Mortgage(customerTwo, 14000, 6.6m, 18),
            new Loan(customerTwo, 15000, 8.9m, 2),
            new Loan(customerTwo, 7000, 7.5m, 12),
        };

        foreach (Account account in accounts)
        {
            Console.WriteLine(account);
        }

        Deposit radkaDeposit = new Deposit(customerOne, 980, 5.9m, 12);
        Deposit miumiuDeposit = new Deposit(customerTwo, 10000, 6.0m, 12);

        Console.WriteLine();
        Console.WriteLine("Current balance: {0}", radkaDeposit.WithdrawMoney(150));
        Console.WriteLine("Current balance: {0}", radkaDeposit.DepositMoney(1500));
        Console.WriteLine("Current balance: {0}", miumiuDeposit.WithdrawMoney(5642));
        Console.WriteLine("Current balance: {0}", miumiuDeposit.DepositMoney(1247));
    }
Пример #4
0
 ///<summary>Inserts one Deposit into the database.  Returns the new priKey.</summary>
 internal static long Insert(Deposit deposit)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         deposit.DepositNum=DbHelper.GetNextOracleKey("deposit","DepositNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(deposit,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     deposit.DepositNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(deposit,false);
     }
 }
 static void Main()
 {
     Console.WriteLine("Enter number");
     int number = int.Parse(Console.ReadLine());
     try
     {
         for (int count = 0; count < number; count++)
         {
             Console.WriteLine("Enter customer kind");               //true equals to individual, and false to company
             bool customerKind = bool.Parse(Console.ReadLine());
             Console.WriteLine("Enter customer name");
             string customerName = Console.ReadLine();
             Customer customer = new Customer(customerKind, customerName);
             Console.WriteLine("Enter interest rate");
             float currentInterestRate = float.Parse(Console.ReadLine());
             Console.WriteLine("Enter account balance");
             double currentBalance = double.Parse(Console.ReadLine());
             Deposit deposit = new Deposit(customer, currentInterestRate, currentBalance);
             Loan loan = new Loan(customer, currentInterestRate, currentBalance);
             Mortgage mortgage = new Mortgage(customer, currentInterestRate, currentBalance);
             Console.WriteLine("Enter start month");
             byte startMonth = byte.Parse(Console.ReadLine());
             Console.WriteLine("Enter end month");
             byte endMonth = byte.Parse(Console.ReadLine());
             Console.WriteLine("Interest for the deposit is {0}", deposit.CalculateInterest(startMonth, endMonth));
             Console.WriteLine("Interest for the loan is {0}", loan.CalculateInterest(startMonth, endMonth));
             Console.WriteLine("Interest for the morgage is {0}", mortgage.CalculateInterest(startMonth, endMonth));
         }
     }
     catch (ArgumentException ae)
     {
         Console.WriteLine(ae.Message);
     }
 }
Пример #6
0
 ///<summary>Inserts one Deposit into the database.  Provides option to use the existing priKey.</summary>
 internal static long Insert(Deposit deposit,bool useExistingPK)
 {
     if(!useExistingPK && PrefC.RandomKeys) {
         deposit.DepositNum=ReplicationServers.GetKey("deposit","DepositNum");
     }
     string command="INSERT INTO deposit (";
     if(useExistingPK || PrefC.RandomKeys) {
         command+="DepositNum,";
     }
     command+="DateDeposit,BankAccountInfo,Amount) VALUES(";
     if(useExistingPK || PrefC.RandomKeys) {
         command+=POut.Long(deposit.DepositNum)+",";
     }
     command+=
              POut.Date  (deposit.DateDeposit)+","
         +"'"+POut.String(deposit.BankAccountInfo)+"',"
         +"'"+POut.Double(deposit.Amount)+"')";
     if(useExistingPK || PrefC.RandomKeys) {
         Db.NonQ(command);
     }
     else {
         deposit.DepositNum=Db.NonQ(command,true);
     }
     return deposit.DepositNum;
 }
Пример #7
0
        private static void Main()
        {
            var deposit = new Deposit(400m, 0.01m, Customer.Individual);
            Console.WriteLine("Deposit Account: ");
            Console.WriteLine("Interest rate: " + deposit.CalculateRate(20));

            deposit.DepositMoney(100000m);
            Console.WriteLine("Balance after depositing: " + deposit.Balance);
            Console.WriteLine("Interest rate: " + deposit.CalculateRate(20));

            deposit.WithdrawMoney(100400m);
            Console.WriteLine("Balance after withdrawing: " + deposit.Balance);
            Console.WriteLine();

            var mortgage = new Mortgage(500000m, 0.02m, Customer.Company);
            Console.WriteLine("Mortgage Account: ");
            Console.WriteLine("Interest rate for company: " + mortgage.CalculateRate(12));
            mortgage.Customer = Customer.Individual;
            Console.WriteLine("Interest rate for individual: " + mortgage.CalculateRate(7));
            Console.WriteLine();

            var loan = new Loan(500000m, 0.02m, Customer.Company);
            Console.WriteLine("Loan Account: ");
            Console.WriteLine("Interest rate for company: " + loan.CalculateRate(24));
            loan.Customer = Customer.Individual;
            Console.WriteLine("Interest rate for individual: " + loan.CalculateRate(3));
        }
Пример #8
0
    static void Main(string[] args)
    {
        //Pesho's Account
        Deposit peshosAccount = new Deposit(new Individual("Pesho"), 100000m, 25.3f);

        Console.WriteLine("Pesho's current balance: {0}", peshosAccount.Balance);
        Console.WriteLine("Pesho's interest amount: {0}", peshosAccount.CalculateInterestAmount(12));
        //Add some money in the Pesho's account
        peshosAccount.Deposit(2131m);
        Console.WriteLine("Pesho's balance after the deposit: {0}", peshosAccount.Balance);
        peshosAccount.WithDraw(35000m);
        Console.WriteLine("Pesho's balance after the draw: {0}", peshosAccount.Balance);

        //Let us calculate the Pesho's interest amount
        Console.WriteLine("Pesho's account interest amount: {0}", peshosAccount.CalculateInterestAmount(4));
        Console.WriteLine();
        
        //Ivan's Account
        Account ivansAccount = new Loan(new Company("Ivan"), 1040.4m, 23.3f);
        
        Console.WriteLine("Ivan's interest amount: {0}", ivansAccount.CalculateInterestAmount(7));
        Console.WriteLine();
        
        //Dido's Account
        Account didosAccount = new Mortgage(new Individual("Dido"), 3422m, 5.4f);
        Console.WriteLine("Ivan's interest amount: {0}", didosAccount.CalculateInterestAmount(13));
    }
Пример #9
0
        static void Main()
        {
            IndividualCustomer pesho = new IndividualCustomer("Petar", "Petrov", "+359894011468",
                "Sofia, bul.Tcarigradsko shose 15");
            IndividualCustomer mimi = new IndividualCustomer("Maria", "Nikolova", "+359894011468",
                "Sofia, bul.Vitoshka 35");
            CompanyCustomer softUni = new CompanyCustomer("Software University Ltd.", "+359894011468",
                "Sofia, bul.NqkoiSi 9");
            CompanyCustomer hardUni = new CompanyCustomer("Hardware University Ltd.", "+359894011468",
                "Sofia, bul.EdiKoiSi 6");

            Deposit d1 = new Deposit(pesho, 1000, 0.1m);
            Deposit d2 = new Deposit(softUni, 50000, 0.15m);
            Loan l1 = new Loan(mimi, 5500, 0.2m);
            Loan l2 = new Loan(hardUni, 90000, 0.18m);
            Mortgage m1 = new Mortgage(pesho, 60000, 0.12m);
            Mortgage m2 = new Mortgage(hardUni, 160000, 0.1m);

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Deposits and withdraws:");
            Console.ForegroundColor = ConsoleColor.Black;
            Console.Write("Old balance " + d1.Balance + ", new balance: ");
            d1.DepositMoney(500);
            Console.WriteLine(d1.Balance);
            Console.Write("Old balance " + d2.Balance + ", new balance: ");
            d2.WithdrawMoney(12500.50m);
            Console.WriteLine(d2.Balance);
            Console.Write("Old balance " + l1.Balance + ", new balance: ");
            l1.DepositMoney(500);
            Console.WriteLine(l1.Balance);
            Console.Write("Old balance " + m1.Balance + ", new balance: ");
            m1.DepositMoney(10000.90m);
            Console.WriteLine(m1.Balance);
            Console.WriteLine();

            IList<Account> accounts = new List<Account>
            {
                d1, d2, l1, l2, m1, m2
            };

            Bank bank = new Bank(accounts);

            Console.WriteLine("The bank:");
            Console.WriteLine(bank);

            // I have changed the formula for calculating the interest, because
            // the given formula returns interest plus amount which is not correct
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Calculated interests:");
            Console.ForegroundColor = ConsoleColor.Black;

            Console.WriteLine("Interest = {0:F2} BGN", d1.CalculateInteres(6));
            Console.WriteLine("Interest = {0:F2} BGN", l1.CalculateInteres(3));
            Console.WriteLine("Interest = {0:F2} BGN", l2.CalculateInteres(6));
            Console.WriteLine("Interest = {0:F2} BGN", d2.CalculateInteres(6));
            Console.WriteLine("Interest = {0:F2} BGN", m1.CalculateInteres(6));
            Console.WriteLine("Interest = {0:F2} BGN", m1.CalculateInteres(13));
            Console.WriteLine("Interest = {0:F2} BGN", m2.CalculateInteres(6));
        }
Пример #10
0
 public void CreateDeposit(Deposit deposit)
 {
     using (var context = new FinanceEntities())
     {
         context.Deposit.Add(deposit);
         context.SaveChanges();
     }
 }
Пример #11
0
 public void UpdateDeposit(Deposit deposit)
 {
     using (var context = new FinanceEntities())
     {
         context.Deposit.Attach(deposit);
         context.Entry(deposit).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
Пример #12
0
 public DepositReturn(int returnID, Deposit deposit, Profile profile, User user, int count, DateTime created)
 {
     this.returnID = returnID;
     this.deposit = deposit;
     this.profile = profile;
     this.user = user;
     this.count = count;
     this.created = created;
 }
Пример #13
0
 // END CUT HERE
 // BEGIN CUT HERE
 public static void Main()
 {
     try {
     Deposit ___test = new Deposit();
     ___test.run_test(-1);
     } catch(Exception e) {
     //Console.WriteLine(e.StackTrace);
     Console.WriteLine(e.ToString());
     }
 }
Пример #14
0
 static void Main(string[] args)
 {
     Deposit deposit = new Deposit(new Individual("me", 123), 499, 0.1m, 2);
     Console.WriteLine(deposit.InterestRate);
     deposit.Deposit(10);
     Console.WriteLine(deposit.Balance);
     Loan myLoan = new Loan(new Company("MT", 11), 1000, 0.3m, 2);
     Console.WriteLine(myLoan.CalculateInterest());
     var morgage = new Mortgage(new Individual("me again", 1), 1000, 0.1m, 7);
     Console.WriteLine(morgage.CalculateInterest());
     morgage = new Mortgage(new Company("me ET", 1), 2000, 0.4m, 7);
     Console.WriteLine(morgage.CalculateInterest());
 }
Пример #15
0
		///<summary>Converts a DataTable to a list of objects.</summary>
		public static List<Deposit> TableToList(DataTable table){
			List<Deposit> retVal=new List<Deposit>();
			Deposit deposit;
			for(int i=0;i<table.Rows.Count;i++) {
				deposit=new Deposit();
				deposit.DepositNum     = PIn.Long  (table.Rows[i]["DepositNum"].ToString());
				deposit.DateDeposit    = PIn.Date  (table.Rows[i]["DateDeposit"].ToString());
				deposit.BankAccountInfo= PIn.String(table.Rows[i]["BankAccountInfo"].ToString());
				deposit.Amount         = PIn.Double(table.Rows[i]["Amount"].ToString());
				deposit.Memo           = PIn.String(table.Rows[i]["Memo"].ToString());
				retVal.Add(deposit);
			}
			return retVal;
		}
Пример #16
0
    static void Main()
    {
        Console.WriteLine("This program tests the Bank project. It will run a few tests to determine if the code has been written correctly.");
        Console.WriteLine();

        Individual ind1 = new Individual("Petar Atanasov");
        Company comp1 = new Company("Telerik");

        Deposit depInd = new Deposit(ind1, 500, 5, 12);
        Deposit depComp = new Deposit(comp1, 40000, 100, 6);

        Loan loanInd = new Loan(ind1, -5000, 50, 25);
        Loan loanComp = new Loan(comp1, -2000000, 1000, 20);

        Mortgage mortInd = new Mortgage(ind1, -50000, 150, 36);
        Mortgage mortComp = new Mortgage(comp1, -500000, 200, 48);

        Account[] accounts =
        {
            depInd, depComp, loanInd, loanComp, mortInd, mortComp
        };

        foreach (var acc in accounts)
        {
            Console.WriteLine(acc.ToString());
            Console.WriteLine("Interest amount is {0}", acc.InterestAmount());
            Console.WriteLine();
        }
        Console.Write("Press any key to continue testing:");
        Console.ReadKey();
        Console.WriteLine();

        Console.WriteLine("Trying to deposit 100 in each account:");
        foreach (var acc in accounts)
        {
            Console.WriteLine("Account balance before: {0}", acc.Balance);
            acc.Deposit(100);
            Console.WriteLine("Account balance after: {0}", acc.Balance);
            Console.WriteLine();
        }

        Console.WriteLine("Withdrawing 200 from individual deposit:");
        Console.WriteLine("Account balance before: {0}", depInd.Balance);
        depInd.Withdraw(200);
        Console.WriteLine("Account balance after: {0}", depInd.Balance);
        Console.WriteLine();

        Console.WriteLine("Testing is complete.");
    }
Пример #17
0
 static void Main()
 {
     // creating 3 different accounts
     Account acc1 = new Deposit(Custemer.Individual, 1234, 0.75m);
     Account acc2 = new Loan(Custemer.Companie, 100052, 1.2m);
     Account acc3 = new Mortgage(Custemer.Individual, 754, 0.98m);
     acc1.PrintBalance();
     acc1.CalcInterest(7);
     acc1.PrintBalance();
     acc1.Deposit(300);
     //acc1.Draw- it is Account
     Deposit acc4 = new Deposit(Custemer.Individual, 2222, 0.35m);
     acc4.Draw(1111);
     acc2.CalcInterest(7);
     acc2.Deposit(555);
 }
Пример #18
0
        static void Main()
        {
            Person person1 = new Person("Cheplyat 4711, ul. Kriva 7", "+35930143285", "Georgi", "Nashmatliyski", 44, "7104254323");
            Person person2 = new Person("Lovech 7611, ul. Prava 10", "+35940165883", "Kaymet", "Dertliev", 31, "8401055374");
            Person person3 = new Person("Gudevitza 1691, ul. Glavna 1", "+35988765373", "Evlampi", "Svetlozarov", 52, "6401055374");

            Company company1 = new Company("Sofia 1000, ul. Buren 23", "024446667", "Bastuni Unlimited EOOD", "Tenko Gazarliev", "BG237452357");
            Company company2 = new Company("Sofia 1000, ul. Kiryak Stefchov 13", "026236305", "Kloshari Incorporated OOD", "Ceko Minev", "BG127722365");
            Company company3 = new Company("Plovdiv 2030, ul. Tepe 5", "032481690", "ET Bass Tune", "Stamat Kazandjiev", "BG224711902");

            Loan loan1 = new Loan(person1, -1000m, 0.12m);
            Loan loan2 = new Loan(company1, -20000m, 0.08m);
            Loan loan3 = new Loan(company2, -10010m, 0.10m);

            Mortgage mort1 = new Mortgage(person1, -100000m, 0.06m);
            Mortgage mort2 = new Mortgage(person2, -200000m, 0.05m);
            Mortgage mort3 = new Mortgage(person3, -50000m, 0.055m);

            Deposit deposit1 = new Deposit(person1, 500m, 0.02m);
            Deposit deposit2 = new Deposit(company3, 15000m, 0.02m);
            Deposit deposit3 = new Deposit(person3, 5500m, 0.02m);

            loan1.DepositMoney(1500);
            mort2.DepositMoney(15000);
            deposit3.WithdrawMoney(1000);

            int period = 2; // <<-- months; change the period to see how interest calculation differs according to the problem description

            Account[] allAccounts = { loan1, loan2, loan3, mort1, mort2, mort3, deposit1, deposit2, deposit3 };
            foreach (var account in allAccounts)
            {
                Console.WriteLine("{2} {0} account\nCurrent Ballance = {1} BGN", account.Type, account.Ballance, account.Customer.Type);
                Console.WriteLine("Ballance in {0} months\n(Interest: {2:P}) = {1} BGN", period, account.CalcInterest(period), account.InterestRate);
                Console.WriteLine(new string('+', 50));
                if (account.Customer is Person)
                {
                    Person temp = (Person)account.Customer;
                    Console.WriteLine("Owner: {0} {1} (EGN {2}), Age: {3}\nAddress: {4}\nPhone: {5}", temp.FirstName, temp.LastName, temp.EGN, temp.Age, temp.Address, temp.Phone);
                }
                else if (account.Customer is Company)
                {
                    Company temp = (Company)account.Customer;
                    Console.WriteLine("Company name: {0} (Bulstat: {1})\nMOL: {2}\nAddress: {3}\nPhone: {4}", temp.Name, temp.Bulstat, temp.MOL, temp.Address, temp.Phone);
                }
                Console.WriteLine(new string('=', 50));
            }
        }
Пример #19
0
    private void ShowDeposit()
    {
        deposit = new DepositManager(this).GetDeposit(Convert.ToInt32(Page.ViewState["DepositId"]));

        txtName.Text = deposit.Name;
        ucCurrFieldFifthWeekGoal.CurrencyValue = deposit.FifthWeekGoal;
        ucCurrFieldFirstWeekGoal.CurrencyValue = deposit.FirstWeekGoal;
        ucCurrFieldForthWeekGoal.CurrencyValue = deposit.ForthWeekGoal;
        ucCurrFieldMonthlyGoal.CurrencyValue = deposit.MonthlyGoal;
        ucCurrFieldSecondWeekGoal.CurrencyValue = deposit.SecondWeekGoal;
        ucCurrFieldThirdWeekGoal.CurrencyValue = deposit.ThirdWeekGoal;
        ucDepositAddress.AddressComp = deposit.AddressComp;
        ucDepositAddress.PostalCode = deposit.PostalCode;
        ucDepositAddress.AddressNumber = deposit.AddressNumber;
        ucDepositAddress.AddressNumber = deposit.AddressNumber;

    }
Пример #20
0
 public static void Main()
 {
     CompanyCustomer company = new CompanyCustomer("Company");
     IndividualCustomer pesho = new IndividualCustomer("Pesho");
     IndividualCustomer ivan = new IndividualCustomer("Ivan");
     IAccount peshoLoan = new Loan(pesho, 2500, 6.5m);
     IAccount companyMortgage = new Mortgage(company, 15000, 8.8m);
     IAccount ivanDeposit = new Deposit(ivan, 8000, 3.5m);
     List<IAccount> myAccounts = new List<IAccount>{peshoLoan, companyMortgage, ivanDeposit};
     Bank bigBank = new Bank(myAccounts);
     Console.WriteLine();
     bigBank.ListAllAccounts();
     Console.WriteLine();
     bigBank.InterestForAll(12);
     Console.WriteLine("\nPesho's interest for 30 months: {0}", peshoLoan.CalculateInterest(30));
     Console.WriteLine();
 }
Пример #21
0
    static void Main()
    {
        Individual someone = new Individual();

        Account someonesAccount = new Loan((decimal)123.54, (float)2.3, someone);

        someonesAccount.Deposit(20);

        Company someCompany = new Company();

        Account someCompanyAccount = new Deposit((decimal)-1434.23, (float)4.5, someCompany);

        Console.WriteLine( someCompanyAccount.CalculateInterestAmount(13) );

        Account someonesMortgageAcc = new Mortgage((decimal)1243.1, (float)45.3, someone);

        Console.WriteLine(someonesMortgageAcc.CalculateInterestAmount(7));
    }
Пример #22
0
    private void SaveDeposit()
    {

        depositManager = new DepositManager(this);
        original_deposit = depositManager.GetDeposit(Convert.ToInt32(Page.ViewState["DepositId"]));
        deposit = new Deposit();

        if (original_deposit != null)
            deposit.CopyPropertiesFrom(original_deposit);

        deposit.Name = txtName.Text;
        deposit.CompanyId = Company.CompanyId;
        deposit.PostalCode = ucDepositAddress.PostalCode;
        deposit.AddressComp = ucDepositAddress.AddressComp;
        deposit.AddressNumber = ucDepositAddress.AddressNumber;


        if (ucCurrFieldFirstWeekGoal.CurrencyValue.HasValue)
            deposit.FirstWeekGoal = ucCurrFieldFirstWeekGoal.CurrencyValue.Value;

        if (ucCurrFieldSecondWeekGoal.CurrencyValue.HasValue)
            deposit.SecondWeekGoal = ucCurrFieldSecondWeekGoal.CurrencyValue.Value;

        if (ucCurrFieldThirdWeekGoal.CurrencyValue.HasValue)
            deposit.ThirdWeekGoal = ucCurrFieldThirdWeekGoal.CurrencyValue.Value;

        if (ucCurrFieldForthWeekGoal.CurrencyValue.HasValue)
            deposit.ForthWeekGoal = ucCurrFieldForthWeekGoal.CurrencyValue.Value;

        if (ucCurrFieldFirstWeekGoal.CurrencyValue.HasValue)
            deposit.FifthWeekGoal = ucCurrFieldFifthWeekGoal.CurrencyValue.Value;

        if(ucCurrFieldMonthlyGoal.CurrencyValue.HasValue)
            deposit.MonthlyGoal = ucCurrFieldMonthlyGoal.CurrencyValue.Value;


        if (original_deposit != null)
            depositManager.Update(original_deposit, deposit);
        else
            depositManager.Insert(deposit);

        Response.Redirect("Deposits.aspx");

    }
Пример #23
0
        public static void Main()
        {
            Console.Title = "Problem 2.	Bank of Kurtovo Konare";

            Deposit goshoDeposit = new Deposit(Customer.Individuals, 1000m, 0.05m);
            goshoDeposit.DepositMoney(450);
            goshoDeposit.WithdrawMoney(400);
            Console.WriteLine(goshoDeposit + "Interest = " + goshoDeposit.CalculateInterest(10));
            Console.WriteLine();

            Loan carskiZaem = new Loan(Customer.Companies, 50000m, 0.1m);
            carskiZaem.DepositMoney(1);
            Console.WriteLine(carskiZaem + "Interest = " + carskiZaem.CalculateInterest(5));
            Console.WriteLine();

            Mortgage bmwPesho = new Mortgage(Customer.Individuals, 10000m, 0.01m);
            bmwPesho.DepositMoney(5000);
            Console.WriteLine(bmwPesho + "Interest = " + bmwPesho.CalculateInterest(30));
        }
Пример #24
0
        static void Main()
        {
            Bank bank = new Bank("Bank Antinari inc.");

            Customer newOwner = new Customer("Tano Caridi", CustomerType.Individual);
            Deposit myDeposit = new Deposit(newOwner, 120000000, 13.45m);
            bank.AddAccount(myDeposit);

            Customer secondOwner = new Customer("Bai Ivan", CustomerType.Company);
            Mortage GoshoLoan = new Mortage(secondOwner, 50000, 25.99m);
            bank.AddAccount(GoshoLoan);

            Console.WriteLine(bank);

            for (int i = 0; i < bank.AllAccounts.Count; i++)
            {
                Console.WriteLine();
                Console.WriteLine("Account {0}: ", i + 1);
                Console.WriteLine(bank.AllAccounts[i]);
            }
        }
        static void Main(string[] args)
        {
            try
            {
                Deposit deposit = new Deposit(Customer.Company, 20000m, 3.4m);
                deposit.Withdraw(345m);
                deposit.DepositMoney(1000m);
                deposit.CalculateInterest(10);
                Console.WriteLine("Deposit:\n{0}", deposit);

                Loan loanIndividual = new Loan(Customer.Individual, 1000m, 20m);
                loanIndividual.DepositMoney(3000m);
                loanIndividual.CalculateInterest(5);
                Console.WriteLine("Loan individual:\n{0}", loanIndividual);

                Loan loanCompalny = new Loan(Customer.Company, 200000m, 5m);
                loanCompalny.DepositMoney(30000m);
                loanCompalny.CalculateInterest(4);
                Console.WriteLine("Loan company:\n{0}", loanCompalny);

                Mortgage mortageIndividual = new Mortgage(Customer.Individual, 500, 3.3m);
                mortageIndividual.DepositMoney(200m);
                mortageIndividual.CalculateInterest(7);
                Console.WriteLine("Mortage individual:\n{0}", mortageIndividual);

                Mortgage mortageCompany = new Mortgage(Customer.Company, 50000, 4m);
                mortageIndividual.DepositMoney(2000m);
                mortageIndividual.CalculateInterest(13);
                Console.WriteLine("Mortage individual:\n{0}", mortageIndividual);
            }
            catch (OverflowException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #26
0
        static void Main()
        {
            Customer pesho = new Individual("Pesho");
            Customer firmataNaPesho = new Company("Pesho Inc");

            Account loan1 = new Loan(pesho,12.2M);
            Account loan2 = new Loan(firmataNaPesho, 12.2M);

            loan1.DepositMoney(1000M);
            loan2.DepositMoney(1000M);

            System.Console.WriteLine(string.Format("Loan {0}. Interest amount: {1:C}", loan1.Customer.Name, loan1.CalculateInterestAmount(24)));
            System.Console.WriteLine(string.Format("Loan {0}. Interest amount: {1:C}", loan2.Customer.Name, loan2.CalculateInterestAmount(24)));

            Account deposit1 = new Deposit(pesho, 13M);
            Account deposit2 = new Deposit(firmataNaPesho, 13M);

            deposit1.DepositMoney(15M);
            deposit2.DepositMoney(2000M);

            System.Console.WriteLine(string.Format(
                "Deposit {0}. Interest amount: {1:C}", deposit1.Customer.Name, deposit1.CalculateInterestAmount(24)));
            System.Console.WriteLine(string.Format(
                "Deposit {0}. Interest amount: {1:C}", deposit2.Customer.Name, deposit2.CalculateInterestAmount(24)));

            Account mortage1 = new Mortgage(pesho, 10.2M);
            Account mortage2 = new Mortgage(firmataNaPesho , 10.2M);

            mortage1.DepositMoney(200M);
            mortage2.DepositMoney(200M);

            System.Console.WriteLine(string.Format(
                "Mortage {0}. Interest amount: {1:C}", mortage1.Customer.Name, mortage1.CalculateInterestAmount(24)));
            System.Console.WriteLine(string.Format(
                "Mortage {0}. Interest amount: {1:C}", mortage2.Customer.Name, mortage2.CalculateInterestAmount(24)));
        }
Пример #27
0
        public static void DepositHasStartDateTest()
        {
            Deposit deposit = _depositRepository.CreateDeposit(_client, _accountDeposit);

            Assert.AreEqual(deposit.StartDate, DateTime.Today);
        }
Пример #28
0
 // Start is called before the first frame update
 void Start()
 {
     deposit    = gameObject.GetComponentInParent <Deposit>();
     tryHarvest = true;
 }
Пример #29
0
 internal void InitializeDeposit(string depositInstanceID)
 {
     attachedDeposit = FlowManager.Instance.DepositMap[depositInstanceID];
 }
Пример #30
0
 private void CreateDeposit()
 {
     CurrentDeposit = Instantiate(depositPrefab, depositInstntiationPosition.position, Quaternion.identity);
     CurrentDeposit.transform.SetParent(depositInstntiationPosition);
 }
Пример #31
0
 /// <summary>
 /// Конструктор стандартного аккаунта
 /// </summary>
 /// <param name="card">карта</param>
 /// <param name="deposit">депозит</param>
 public RegularAccount(Card card, Deposit deposit) : base(card, deposit)
 {
 }
Пример #32
0
        private void BtnCancelDepositClick(object sender, EventArgs e)
        {
            var briefMsg  = "អំពី​សិទ្ឋិ​ប្រើ​ប្រាស់";
            var detailMsg = Resources.MsgUserPermissionDeny;

            if (!UserService.AllowToPerform(Resources.PermissionCancelDeposit))
            {
                using (var frmMessageBox = new FrmExtendedMessageBox())
                {
                    frmMessageBox.BriefMsgStr    = briefMsg;
                    frmMessageBox.DetailMsgStr   = detailMsg;
                    frmMessageBox.IsCanceledOnly = true;
                    frmMessageBox.ShowDialog(this);
                    return;
                }
            }

            if (_depositList == null)
            {
                return;
            }

            if (_depositList.Count == 0)
            {
                return;
            }

            if (dgvDeposit.CurrentRow == null)
            {
                return;
            }

            _deposit = _depositList[dgvDeposit.CurrentRow.Index];
            if (_deposit == null)
            {
                return;
            }

            _depositItemList = new List <DepositItem>();
            //_DepositService.GetDepositItems(_Deposit.DepositId);

            //if (_Deposit == null)
            //    return;

            //if (_DepositItemList.Count == 0)
            //    return;

            briefMsg  = "អំពីការបោះបង់";
            detailMsg = "សូម​មេត្តា​ចុច​លើ​ប៊ូតុង យល់​ព្រម ដើម្បី​បញ្ជាក់​ពី​ការ​ប្រគល់​សង​។";
            using (var frmMessageBox = new FrmExtendedMessageBox())
            {
                frmMessageBox.BriefMsgStr  = briefMsg;
                frmMessageBox.DetailMsgStr = detailMsg;
                if (frmMessageBox.ShowDialog(this) != DialogResult.OK)
                {
                    return;
                }
            }

            _deposit.DepositDate = DateTime.Now;
            _deposit             = _depositService.RecordDeposit(
                _depositItemList,
                _deposit.AmountSoldInt,
                _deposit.AmountPaidInt,
                0,
                _deposit.FkCustomer,
                _deposit.DepositNumber,
                _deposit.Discount,
                true);

            var paymentService = ServiceFactory.GenerateServiceInstance().GeneratePaymentService();
            var payment        =
                new Model.Payments.Payment
            {
                PaymentDate   = _deposit.DepositDate,
                PaymentAmount = _deposit.AmountPaidInt,
                SalesOrderId  = _deposit.DepositId,
                CashierId     = _deposit.CashierId
            };

            paymentService.ManagePayment(Resources.OperationRequestInsert, payment);

            RetrieveDataHandler();
        }
Пример #33
0
        private void BtnDeliverClick(object sender, EventArgs e)
        {
            try
            {
                if (_depositList == null)
                {
                    return;
                }

                if (_depositList.Count == 0)
                {
                    return;
                }

                if (dgvDeposit.CurrentRow == null)
                {
                    return;
                }

                _deposit = _depositList[dgvDeposit.CurrentRow.Index];
                if (_deposit == null)
                {
                    return;
                }

                var briefMsg  = "អំពី​សិទ្ឋិ​ប្រើ​ប្រាស់";
                var detailMsg = Resources.MsgUserPermissionDeny;
                if (!UserService.AllowToPerform(Resources.PermissionEditDeposit))
                {
                    using (var frmMessageBox = new FrmExtendedMessageBox())
                    {
                        frmMessageBox.BriefMsgStr    = briefMsg;
                        frmMessageBox.DetailMsgStr   = detailMsg;
                        frmMessageBox.IsCanceledOnly = true;
                        frmMessageBox.ShowDialog(this);
                        return;
                    }
                }

                var saleOrder = _saleOrderService.GetSaleOrder(_deposit);
                if (saleOrder == null)
                {
                    return;
                }

                briefMsg  = "អំពីការប្រគល់របស់";
                detailMsg = Resources.MsgConfirmDeliverProduct;
                using (var frmMessageBox = new FrmExtendedMessageBox())
                {
                    frmMessageBox.BriefMsgStr  = briefMsg;
                    frmMessageBox.DetailMsgStr = detailMsg;
                    if (frmMessageBox.ShowDialog(this) != DialogResult.OK)
                    {
                        return;
                    }
                }

                _depositItemList = _depositService.GetDepositItems(_deposit.DepositId);
                var saleItemList = _saleOrderService.GetSaleItems(_depositItemList);

                _saleOrderService.RecordSaleOrder(
                    saleItemList,
                    saleOrder.AmountSoldInt,
                    saleOrder.AmountSoldInt - saleOrder.AmountPaidInt,
                    0,
                    0,
                    saleOrder.FkCustomer,
                    false,
                    _deposit.DepositNumber,
                    saleOrder.Discount,
                    _deposit.AmountPaidInt,
                    true);

                _deposit.AmountPaidInt   += (_deposit.AmountSoldInt - _deposit.AmountPaidInt);
                _deposit.AmountReturnInt  = 0f;
                _deposit.AmountReturnRiel = 0f;
                _deposit.UpdateDate       = DateTime.Now;
                _depositService.UpdateDeposit(_deposit);

                var paymentService = ServiceFactory.GenerateServiceInstance().GeneratePaymentService();
                var payment        =
                    new Model.Payments.Payment
                {
                    PaymentDate   = _deposit.DepositDate,
                    PaymentAmount = _deposit.AmountPaidInt,
                    SalesOrderId  = _deposit.DepositId,
                    CashierId     = _deposit.CashierId
                };
                paymentService.ManagePayment(Resources.OperationRequestInsert, payment);

                RetrieveDataHandler();
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(Resources.MsgCaptionUnknownError, exception.Message);
            }
        }
Пример #34
0
 ///<summary>Inserts one Deposit into the database.  Returns the new priKey.  Doesn't use the cache.</summary>
 public static long InsertNoCache(Deposit deposit)
 {
     return(InsertNoCache(deposit, false));
 }
Пример #35
0
        ///<summary>Updates one Deposit in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.  Returns true if an update occurred.</summary>
        public static bool Update(Deposit deposit, Deposit oldDeposit)
        {
            string command = "";

            if (deposit.DateDeposit.Date != oldDeposit.DateDeposit.Date)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "DateDeposit = " + POut.Date(deposit.DateDeposit) + "";
            }
            if (deposit.BankAccountInfo != oldDeposit.BankAccountInfo)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "BankAccountInfo = " + DbHelper.ParamChar + "paramBankAccountInfo";
            }
            if (deposit.Amount != oldDeposit.Amount)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Amount = '" + POut.Double(deposit.Amount) + "'";
            }
            if (deposit.Memo != oldDeposit.Memo)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Memo = '" + POut.String(deposit.Memo) + "'";
            }
            if (deposit.Batch != oldDeposit.Batch)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Batch = '" + POut.String(deposit.Batch) + "'";
            }
            if (deposit.DepositAccountNum != oldDeposit.DepositAccountNum)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "DepositAccountNum = " + POut.Long(deposit.DepositAccountNum) + "";
            }
            if (command == "")
            {
                return(false);
            }
            if (deposit.BankAccountInfo == null)
            {
                deposit.BankAccountInfo = "";
            }
            OdSqlParameter paramBankAccountInfo = new OdSqlParameter("paramBankAccountInfo", OdDbType.Text, POut.StringParam(deposit.BankAccountInfo));

            command = "UPDATE deposit SET " + command
                      + " WHERE DepositNum = " + POut.Long(deposit.DepositNum);
            Db.NonQ(command, paramBankAccountInfo);
            return(true);
        }
Пример #36
0
        //    Run ``process_deposit``, yielding:
        //  - pre-state('pre')
        //  - deposit('deposit')
        //  - post-state('post').
        //If ``valid == False``, run expecting ``AssertionError``
        private void RunDepositProcessing(IServiceProvider testServiceProvider, BeaconState state, Deposit deposit, ValidatorIndex validatorIndex, bool expectValid, bool effective)
        {
            var gweiValues            = testServiceProvider.GetService <IOptions <GweiValues> >().Value;
            var beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

            var preValidatorCount = state.Validators.Count;
            var preBalance        = Gwei.Zero;

            if ((int)(ulong)validatorIndex < preValidatorCount)
            {
                preBalance = TestState.GetBalance(state, validatorIndex);
            }

            if (!expectValid)
            {
                Should.Throw <Exception>(() =>
                {
                    beaconStateTransition.ProcessDeposit(state, deposit);
                });
                return;
            }

            beaconStateTransition.ProcessDeposit(state, deposit);

            if (!effective)
            {
                state.Validators.Count.ShouldBe(preValidatorCount);
                state.Balances.Count.ShouldBe(preValidatorCount);
                if ((int)(ulong)validatorIndex < preValidatorCount)
                {
                    var balance = TestState.GetBalance(state, validatorIndex);
                    balance.ShouldBe(preBalance);
                }
            }
            else
            {
                if ((int)(ulong)validatorIndex < preValidatorCount)
                {
                    // top up
                    state.Validators.Count.ShouldBe(preValidatorCount);
                    state.Balances.Count.ShouldBe(preValidatorCount);
                }
                else
                {
                    // new validator
                    state.Validators.Count.ShouldBe(preValidatorCount + 1);
                    state.Balances.Count.ShouldBe(preValidatorCount + 1);
                }

                var balance         = TestState.GetBalance(state, validatorIndex);
                var expectedBalance = preBalance + deposit.Data.Amount;
                balance.ShouldBe(expectedBalance);

                var expectedEffectiveBalance = Gwei.Min(gweiValues.MaximumEffectiveBalance, expectedBalance);
                expectedEffectiveBalance -= expectedEffectiveBalance % gweiValues.EffectiveBalanceIncrement;
                state.Validators[(int)(ulong)validatorIndex].EffectiveBalance.ShouldBe(expectedEffectiveBalance);
            }

            state.Eth1DepositIndex.ShouldBe(state.Eth1Data.DepositCount);
        }
Пример #37
0
 ///<summary>Inserts one Deposit into the database.  Returns the new priKey.</summary>
 public static long Insert(Deposit deposit)
 {
     return(Insert(deposit, false));
 }
Пример #38
0
        public void Beacon_state_there_and_back()
        {
            Eth1Data eth1Data = new Eth1Data(
                Sha256.RootOfAnEmptyString,
                1,
                Sha256.Bytes32OfAnEmptyString);

            BeaconBlockHeader beaconBlockHeader = new BeaconBlockHeader(
                new Slot(14),
                Sha256.RootOfAnEmptyString,
                Sha256.RootOfAnEmptyString,
                Sha256.RootOfAnEmptyString);

            Deposit         zeroDeposit     = new Deposit(Enumerable.Repeat(Bytes32.Zero, Ssz.DepositContractTreeDepth + 1), DepositData.Zero);
            BeaconBlockBody beaconBlockBody = new BeaconBlockBody(
                TestSig1,
                eth1Data,
                new Bytes32(new byte[32]),
                Enumerable.Repeat(ProposerSlashing.Zero, 2).ToArray(),
                Enumerable.Repeat(AttesterSlashing.Zero, 3).ToArray(),
                Enumerable.Repeat(Attestation.Zero, 4).ToArray(),
                Enumerable.Repeat(zeroDeposit, 5).ToArray(),
                Enumerable.Repeat(SignedVoluntaryExit.Zero, 6).ToArray()
                );

            BeaconBlock beaconBlock = new BeaconBlock(
                new Slot(1),
                Sha256.RootOfAnEmptyString,
                Sha256.RootOfAnEmptyString,
                beaconBlockBody);

            BeaconState container = new BeaconState(
                123,
                new Slot(1),
                new Fork(new ForkVersion(new byte[] { 0x05, 0x00, 0x00, 0x00 }),
                         new ForkVersion(new byte[] { 0x07, 0x00, 0x00, 0x00 }), new Epoch(3)),
                beaconBlockHeader,
                Enumerable.Repeat(Root.Zero, Ssz.SlotsPerHistoricalRoot).ToArray(),
                Enumerable.Repeat(Root.Zero, Ssz.SlotsPerHistoricalRoot).ToArray(),
                Enumerable.Repeat(Root.Zero, 13).ToArray(),
                eth1Data,
                Enumerable.Repeat(Eth1Data.Zero, 2).ToArray(),
                1234,
                Enumerable.Repeat(Validator.Zero, 7).ToArray(),
                new Gwei[3],
                Enumerable.Repeat(Bytes32.Zero, Ssz.EpochsPerHistoricalVector).ToArray(),
                new Gwei[Ssz.EpochsPerSlashingsVector],
                Enumerable.Repeat(PendingAttestation.Zero, 1).ToArray(),
                Enumerable.Repeat(PendingAttestation.Zero, 11).ToArray(),
                new BitArray(new byte[] { 0x09 }),
                new Checkpoint(new Epoch(3), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(5), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(7), Sha256.RootOfAnEmptyString)
                );

            JsonSerializerOptions options = new JsonSerializerOptions {
                WriteIndented = true
            };

            options.ConfigureNethermindCore2();
            TestContext.WriteLine("Original state: {0}", JsonSerializer.Serialize(container, options));

            int encodedLength = Ssz.BeaconStateLength(container);

            TestContext.WriteLine("Encoded length: {0}", encodedLength);
            Span <byte> encoded = new byte[encodedLength];

            Ssz.Encode(encoded, container);
            BeaconState decoded = Ssz.DecodeBeaconState(encoded);

            TestContext.WriteLine("Decoded state: {0}", JsonSerializer.Serialize(decoded, options));

            AssertBeaconStateEqual(container, decoded);

            Span <byte> encodedAgain = new byte[Ssz.BeaconStateLength(decoded)];

            Ssz.Encode(encodedAgain, decoded);

            byte[] encodedArray      = encoded.ToArray();
            byte[] encodedAgainArray = encodedAgain.ToArray();

            encodedAgainArray.Length.ShouldBe(encodedArray.Length);
            //encodedAgainArray.ShouldBe(encodedArray);
            //Assert.True(Bytes.AreEqual(encodedAgain, encoded));

            Merkle.Ize(out UInt256 root, container);
        }
Пример #39
0
        static void Main(string[] args)
        {
            Console.WriteLine("Glad to welcome you to the bank");
            Console.WriteLine("Сhoose a service: \n 1.\tСumulative card;\n 2.\tDeposit card;\n 3.\tCredit card;\n 4.\tExit;\n  ");
            int answer = Convert.ToInt32(Console.ReadLine());

            switch (answer)
            {
            case 1:
                Сumulative cumulative = new Сumulative("Client", 0, "Сumulative");
                Console.WriteLine("Enter your name: ");
                cumulative.setName(Console.ReadLine());
                Console.WriteLine("Enter amount of money: ");
                cumulative.setMoney(Convert.ToDouble(Console.ReadLine()));
                cumulative.getInfo();
                Console.WriteLine("Фdding, withdrawing money");
                Console.WriteLine("Сhoose a operation: \n 1.\tAdd money;\n 2.\tWithdraw money;\n 3.\tExit;\n ");
                int choose = Convert.ToInt32(Console.ReadLine());
                switch (choose)
                {
                case 1:
                    Console.WriteLine("Enter recharge amount: ");
                    cumulative.Put(Convert.ToDouble(Console.ReadLine()));
                    cumulative.getInfo();
                    break;

                case 2:
                    Console.WriteLine("Enter withdrawal amount: ");
                    cumulative.Withdraw(Convert.ToDouble(Console.ReadLine()));
                    cumulative.getInfo();
                    break;

                case 3:
                    Console.WriteLine("You enter exit");
                    break;
                }
                break;

            case 2:
                Deposit deposit = new Deposit("Client", 0, "Deposit", 0);
                Console.WriteLine("Enter your name: ");
                deposit.setName(Console.ReadLine());
                Console.WriteLine("Enter deposit amount: ");
                deposit.setMoney(Convert.ToDouble(Console.ReadLine()));
                Console.WriteLine("Enter deposit period: ");
                deposit.setPeriod(Convert.ToDouble(Console.ReadLine()));
                deposit.getInfo();
                double money  = deposit.getMoney();
                double period = deposit.getPeriod();
                deposit.setRate(money, period);
                double rate     = deposit.getRate();
                double depMoney = deposit.GetSum(money, rate, period);
                double result   = depMoney - money;
                result = Math.Round(result, 2);
                Console.WriteLine("You've earned  " + result);
                break;

            case 3:
                Credit credit = new Credit("Client", 0, "Deposit", 0);
                Console.WriteLine("Enter your name: ");
                credit.setName(Console.ReadLine());
                Console.WriteLine("Enter deposit amount: ");
                credit.setMoney(Convert.ToDouble(Console.ReadLine()));
                Console.WriteLine("Enter deposit period: ");
                credit.setPeriod(Convert.ToDouble(Console.ReadLine()));
                credit.getInfo();
                double money1  = credit.getMoney();
                double period1 = credit.getPeriod();
                credit.setRate(money1, period1);
                double rate1 = credit.getRate();
                Console.WriteLine($"This is a rate  {rate1}");
                double procents = credit.GetSum(money1, rate1, period1);
                procents = Math.Round(procents, 2);
                Console.WriteLine("You overpaid  " + procents);
                break;

            case 4:
                Console.WriteLine("You enter exit");
                break;

            default:
                Console.WriteLine("Erroneous input");
                break;
            }
        }
Пример #40
0
        private void OpenSessionClick(object sender)
        {
            List <DepositCashDetail> depositCashDetail = new List <DepositCashDetail>();

            if (HundredValue != 0)
            {
                depositCashDetail.Add(new DepositCashDetail {
                    amount_unit = 100000,
                    qty         = HundredValue
                });
            }
            if (FiftyValue != 0)
            {
                depositCashDetail.Add(new DepositCashDetail
                {
                    amount_unit = 50000,
                    qty         = FiftyValue
                });
            }
            if (TwentyValue != 0)
            {
                depositCashDetail.Add(new DepositCashDetail
                {
                    amount_unit = 20000,
                    qty         = TwentyValue
                });
            }
            if (TenValue != 0)
            {
                depositCashDetail.Add(new DepositCashDetail
                {
                    amount_unit = 10000,
                    qty         = TenValue
                });
            }
            if (FiveValue != 0)
            {
                depositCashDetail.Add(new DepositCashDetail
                {
                    amount_unit = 5000,
                    qty         = FiveValue
                });
            }
            if (TwoValue != 0)
            {
                depositCashDetail.Add(new DepositCashDetail
                {
                    amount_unit = 2000,
                    qty         = TwoValue
                });
            }
            if (OneValue != 0)
            {
                depositCashDetail.Add(new DepositCashDetail
                {
                    amount_unit = 1000,
                    qty         = OneValue
                });
            }
            PrinterRepository printerRepository = new PrinterRepository();

            linedata = new List <string>();
            linedata.Add("DEPOSIT KASIR - " + ConfigList[0].current_ip);
            linedata.Add("garis");
            linedata.Add("TOTAL DEPOSIT : " + String.Format("{0:N}", OpeningBalanceInt));
            linedata.Add("garis");
            linedata.Add("100,000 X " + HundredValue + " = " + String.Format("{0:N}", (100000 * HundredValue)));
            linedata.Add(" 50,000 X " + FiftyValue + " = " + String.Format("{0:N}", (50000 * FiftyValue)));
            linedata.Add(" 20,000 X " + TwentyValue + " = " + String.Format("{0:N}", (20000 * TwentyValue)));
            linedata.Add(" 10,000 X " + TenValue + " = " + String.Format("{0:N}", (10000 * TenValue)));
            linedata.Add("  5,000 X " + FiveValue + " = " + String.Format("{0:N}", (5000 * FiveValue)));
            linedata.Add("  2,000 X " + TwoValue + " = " + String.Format("{0:N}", (2000 * TwoValue)));
            linedata.Add("  1,000 X " + OneValue + " = " + String.Format("{0:N}", (1000 * OneValue)));
            linedata.Add(" ");
            linedata.Add(" ");
            //linedata.Add( (char)27 + "@" + (char)27 + "p" + (char)0 + ".}");

            //printerRepository.CetakReceiptLine(ConfigList[0].pos_printer, linedata);
            printerRepository.PrintReceipt(ConfigList[0].pos_printer, linedata);

            linedata = new List <string>();
            //linedata.Add("\x1b" + "\x69"); cut
            linedata.Add((char)27 + "@" + (char)27 + "p" + (char)0 + ".}");
            printerRepository.CetakReceiptLine(ConfigList[0].pos_printer, linedata);
            //sementara
            DepositData _depositData = new DepositData
            {
                pos_ip = IpAddressValue,
                opening_cash_balance = OpeningBalanceInt,
                cash_detail          = depositCashDetail
            };
            Deposit _depositRequest = new Deposit {
                data = _depositData
            };

            SendDepositData(_depositRequest);
        }
Пример #41
0
 public AddDepositView(Deposit deposit)
 {
     InitializeComponent();
     this.DataContext = new AddDepositViewModel(deposit);
 }
Пример #42
0
        public ViewResult Deposit()
        {
            var deposit = new Deposit();

            return(View(deposit));
        }
Пример #43
0
 public async Task <PosSession> GetDepositAsync(Deposit depositRequest)
 {
     Repository = new DepositRepository();
     return(await Repository.SendDepositAsync(depositRequest));
 }
Пример #44
0
 public void SetUp()
 {
     _deposit = new Deposit();
 }
 public static void GetDescription(Deposit deposit)
 {
     deposit.Description = "Deposit to " + deposit.Account.Name + " on " + deposit.Date;
 }
Пример #46
0
 ///<summary>Updates one Deposit in the database.</summary>
 internal static void Update(Deposit deposit)
 {
     string command="UPDATE deposit SET "
         +"DateDeposit    =  "+POut.Date  (deposit.DateDeposit)+", "
         +"BankAccountInfo= '"+POut.String(deposit.BankAccountInfo)+"', "
         +"Amount         = '"+POut.Double(deposit.Amount)+"' "
         +"WHERE DepositNum = "+POut.Long(deposit.DepositNum);
     Db.NonQ(command);
 }
 /// <summary>
 /// Method to add a new deposit
 /// </summary>
 /// <param name="companyId"></param>
 /// <returns></returns>
 private Deposit CreateMatrixDeposit(int companyId)
 {
     var dep = new Deposit();
     dep.CompanyId = companyId;
     dep.Name = "Matriz";
     new DepositManager(this).Insert(dep);
     return dep;
 }
Пример #48
0
        public void Beacon_block_body_more_detailed()
        {
            AttestationData data = new AttestationData(
                new Slot(1),
                new CommitteeIndex(4),
                Sha256.RootOfAnEmptyString,
                new Checkpoint(new Epoch(2), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(3), Sha256.RootOfAnEmptyString));

            Attestation attestation = new Attestation(
                new BitArray(new byte[5]),
                data,
                TestSig1);

            DepositData depositData = new DepositData(
                TestKey1,
                Sha256.Bytes32OfAnEmptyString,
                new Gwei(7),
                TestSig1);

            Deposit deposit = new Deposit(Enumerable.Repeat(Bytes32.Zero, Ssz.DepositContractTreeDepth + 1), depositData);

            IndexedAttestation indexedAttestation1 = new IndexedAttestation(
                new ValidatorIndex[8],
                data,
                TestSig1);

            IndexedAttestation indexedAttestation2 = new IndexedAttestation(
                new ValidatorIndex[8],
                data,
                TestSig1);

            AttesterSlashing slashing = new AttesterSlashing(indexedAttestation1, indexedAttestation2);

            Eth1Data eth1Data = new Eth1Data(
                Sha256.RootOfAnEmptyString,
                9,
                Sha256.Bytes32OfAnEmptyString);

            Attestation[] attestations = Enumerable.Repeat(Attestation.Zero, 3).ToArray();
            attestations[1] = attestation;

            Deposit zeroDeposit = new Deposit(Enumerable.Repeat(Bytes32.Zero, Ssz.DepositContractTreeDepth + 1), DepositData.Zero);

            Deposit[] deposits = Enumerable.Repeat(zeroDeposit, 3).ToArray();
            deposits[2] = deposit;

            Bytes32 graffiti = new Bytes32(new byte[32]);

            AttesterSlashing[] attesterSlashings = Enumerable.Repeat(AttesterSlashing.Zero, 3).ToArray();
            attesterSlashings[0] = slashing;

            ProposerSlashing[] proposerSlashings = Enumerable.Repeat(ProposerSlashing.Zero, 10).ToArray();

            SignedVoluntaryExit[] signedVoluntaryExits = Enumerable.Repeat(SignedVoluntaryExit.Zero, 11).ToArray();

            BeaconBlockBody body = new BeaconBlockBody(
                TestSig1,
                eth1Data,
                graffiti,
                proposerSlashings,
                attesterSlashings,
                attestations,
                deposits,
                signedVoluntaryExits
                );

            byte[] encoded = new byte[Ssz.BeaconBlockBodyLength(body)];
            Ssz.Encode(encoded, body);
        }
Пример #49
0
 public TakeBikeCommandContext(Bike bike, Client client, Deposit deposit)
 {
     Bike    = bike;
     Client  = client;
     Deposit = deposit;
 }
Пример #50
0
    // return object of specified Transaction derived class
    private Transaction CreateTransaction( int type )
    {
        Transaction temp = null; // null Transaction reference

          // determine which type of Transaction to create
          switch ( ( MenuOption ) type )
          {
         // create new BalanceInquiry transaction
         case MenuOption.BALANCE_INQUIRY:
            temp = new BalanceInquiry( currentAccountNumber,
               screen, bankDatabase);
            break;
         case MenuOption.WITHDRAWAL: // create new Withdrawal transaction
            temp = new Withdrawal( currentAccountNumber, screen,
               bankDatabase, keypad, cashDispenser);
            break;
         case MenuOption.DEPOSIT: // create new Deposit transaction
            temp = new Deposit( currentAccountNumber, screen,
               bankDatabase, keypad, depositSlot);
            break;
          } // end switch

          return temp;
    }
Пример #51
0
        public void Can_claim_early_refund()
        {
            uint timestamp = 1546871954;

            _bridge.NextBlockPlease(timestamp);

            DepositService depositService = new DepositService(_bridge, _abiEncoder, _wallet, _ndmConfig, LimboLogs.Instance);
            Keccak         headerId       = Keccak.Compute("data header");
            uint           expiryTime     = timestamp + (uint)TimeSpan.FromDays(4).TotalSeconds;
            UInt256        value          = 1.Ether();
            uint           units          = 10U;

            byte[] pepper = new byte[16];

            AbiSignature depositAbiDef = new AbiSignature("deposit",
                                                          new AbiBytes(32),
                                                          new AbiUInt(32),
                                                          new AbiUInt(96),
                                                          new AbiUInt(32),
                                                          new AbiBytes(16),
                                                          AbiType.Address,
                                                          AbiType.Address);

            byte[] depositData = _abiEncoder.Encode(AbiEncodingStyle.Packed, depositAbiDef, headerId.Bytes, units, value, expiryTime, pepper, _providerAccount, _consumerAccount);
            Keccak depositId   = Keccak.Compute(depositData);

            Deposit   deposit          = new Deposit(depositId, units, expiryTime, value);
            Keccak    depositTxHash    = depositService.MakeDeposit(_consumerAccount, deposit);
            TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash);

            TestContext.WriteLine("GAS USED FOR DEPOSIT: {0}", depositTxReceipt.GasUsed);
            Assert.AreEqual(StatusCode.Success, depositTxReceipt.StatusCode, $"deposit made {depositTxReceipt.Error} {Encoding.UTF8.GetString(depositTxReceipt.ReturnValue ?? new byte[0])}");

            // calls revert and cannot reuse the same state - use only for manual debugging
            // Assert.True(depositService.VerifyDeposit(deposit.Id), "deposit verified");

            uint         claimableAfter    = timestamp + (uint)TimeSpan.FromDays(1).TotalSeconds;
            AbiSignature earlyRefundAbiDef = new AbiSignature("earlyRefund", new AbiBytes(32), new AbiUInt(32));

            byte[]        earlyRefundData = _abiEncoder.Encode(AbiEncodingStyle.Packed, earlyRefundAbiDef, depositId.Bytes, claimableAfter);
            RefundService refundService   = new RefundService(_bridge, _abiEncoder, _wallet, _ndmConfig, LimboLogs.Instance);

            // it will not work so far as we do everything within the same block and timestamp is wrong

            uint newTimestamp = 1546871954 + (uint)TimeSpan.FromDays(2).TotalSeconds;

            _bridge.NextBlockPlease(newTimestamp);

            Signature        earlySig         = _wallet.Sign(Keccak.Compute(earlyRefundData), _providerAccount);
            EarlyRefundClaim earlyRefundClaim = new EarlyRefundClaim(depositId, headerId, units, value, expiryTime, pepper, _providerAccount, claimableAfter, earlySig, _consumerAccount);
            UInt256          balanceBefore    = _state.GetBalance(_consumerAccount);

            Keccak    refundTxHash  = refundService.ClaimEarlyRefund(_consumerAccount, earlyRefundClaim);
            TxReceipt refundReceipt = _bridge.GetReceipt(refundTxHash);

            TestContext.WriteLine("GAS USED FOR EARLY REFUND CLAIM: {0}", refundReceipt.GasUsed);
            Assert.AreEqual(StatusCode.Success, refundReceipt.StatusCode, $"early refund claim {refundReceipt.Error} {Encoding.UTF8.GetString(refundReceipt.ReturnValue ?? new byte[0])}");
            UInt256 balanceAfter = _state.GetBalance(_consumerAccount);

            Assert.Greater(balanceAfter, balanceBefore);
        }
Пример #52
0
        public async Task <Keccak> MakeAsync(Keccak assetId, uint units, UInt256 value, Address address,
                                             UInt256?gasPrice = null)
        {
            if (!_wallet.IsUnlocked(address))
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn($"Account: '{address}' is locked, can't make a deposit.");
                }

                return(null);
            }

            var dataAsset = _dataAssetService.GetDiscovered(assetId);

            if (dataAsset is null)
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn($"Available data asset: '{assetId}' was not found.");
                }

                return(null);
            }

            if (!_dataAssetService.IsAvailable(dataAsset))
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn($"Data asset: '{assetId}' is unavailable, state: {dataAsset.State}.");
                }

                return(null);
            }

            if (dataAsset.KycRequired && !await _kycVerifier.IsVerifiedAsync(assetId, address))
            {
                return(null);
            }

            var providerAddress = dataAsset.Provider.Address;
            var provider        = _providerService.GetPeer(providerAddress);

            if (provider is null)
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn($"Provider nodes were not found for address: '{providerAddress}'.");
                }

                return(null);
            }

            if (dataAsset.MinUnits > units || dataAsset.MaxUnits < units)
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn($"Invalid data request units: '{units}', min: '{dataAsset.MinUnits}', max: '{dataAsset.MaxUnits}'.");
                }

                return(null);
            }

            var unitsValue = units * dataAsset.UnitPrice;

            if (units * dataAsset.UnitPrice != value)
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn($"Invalid data request value: '{value}', while it should be: '{unitsValue}'.");
                }

                return(null);
            }

            var now        = (uint)_timestamper.EpochSeconds;
            var expiryTime = now + (uint)dataAsset.Rules.Expiry.Value;

            expiryTime += dataAsset.UnitType == DataAssetUnitType.Unit ? 0 : units;
            var pepper  = _cryptoRandom.GenerateRandomBytes(16);
            var abiHash = _abiEncoder.Encode(AbiEncodingStyle.Packed, _depositAbiSig, assetId.Bytes,
                                             units, value, expiryTime, pepper, dataAsset.Provider.Address, address);
            var depositId      = Keccak.Compute(abiHash);
            var deposit        = new Deposit(depositId, units, expiryTime, value);
            var depositDetails = new DepositDetails(deposit, dataAsset, address, pepper, now,
                                                    null, 0, requiredConfirmations: _requiredBlockConfirmations);
            var gasPriceValue = gasPrice is null || gasPrice.Value == 0
                ? await _gasPriceService.GetCurrentAsync()
                : gasPrice.Value;

            await _depositRepository.AddAsync(depositDetails);

            var transactionHash = Keccak.Zero;

            if (_logger.IsInfo)
            {
                _logger.Info($"Created a deposit with id: '{depositId}', for data asset: '{assetId}', address: '{address}'.");
            }
            if (_disableSendingDepositTransaction)
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn("*** NDM sending deposit transaction is disabled ***");
                }
            }
            else
            {
                transactionHash = await _depositService.MakeDepositAsync(address, deposit, gasPriceValue);
            }

            if (_logger.IsInfo)
            {
                _logger.Info($"Sent a deposit with id: '{depositId}', transaction hash: '{transactionHash}' for data asset: '{assetId}', address: '{address}', gas price: {gasPriceValue} wei.");
            }

            depositDetails.SetTransaction(new TransactionInfo(transactionHash, deposit.Value, gasPriceValue,
                                                              _depositService.GasLimit, now));
            await _depositRepository.UpdateAsync(depositDetails);

            return(depositId);
        }
Пример #53
0
 public ProgramInvoke(byte[] address, byte[] origin, byte[] caller, long balance,
                      long call_value, long token_value, long token_id, byte[] msg,
                      byte[] last_hash, byte[] coinbase, long timestamp, long number, Deposit deposit,
                      long vm_start, long vm_should_end, bool is_testing_suite, long energy_limit)
     : this(address, origin, caller, balance,
            call_value, token_value, token_id, msg, last_hash, coinbase,
            timestamp, number, deposit, vm_start, vm_should_end, energy_limit)
 {
     this.is_testing_suite = is_testing_suite;
 }
Пример #54
0
        private async Task ProcessTransactions()
        {
            Log.Message(LogLevel.Info, "[ProcessNZDT] - Processing NZDT Transactions...");

            List <NzdtTransaction> nzdtTransactions;

            using (var context = ExchangeDataContextFactory.CreateContext())
            {
                nzdtTransactions = await context.NzdtTransaction
                                   .Where(x => x.TransactionStatus == NzdtTransactionStatus.ReadyForProcessing)
                                   .Where(x => DbFunctions.AddHours(x.CreatedOn, 1) <= DateTime.UtcNow)
                                   .ToListNoLockAsync();

                Log.Message(LogLevel.Info, $"[ProcessNZDT] - {nzdtTransactions.Count()} transactions found, processing...");

                foreach (var transaction in nzdtTransactions)
                {
                    transaction.TransactionStatus = NzdtTransactionStatus.Processed;
                }

                await context.SaveChangesAsync();
            }

            var wallet = new WalletConnector(_nzdtAssetWalletIp, _nzdtAssetWalletPort, _nzdtAssetWalletUserName, _nzdtAssetWalletPassword, 30000);

            foreach (var transaction in nzdtTransactions)
            {
                try
                {
                    var sendResult = await wallet.SendToAddressAsync(Constant.NzdtBaseExchangeAddress, transaction.Amount);

                    using (var context = ExchangeDataContextFactory.CreateContext())
                    {
                        var deposit = new Deposit
                        {
                            Txid          = string.IsNullOrEmpty(sendResult?.Txid) ? $"{transaction.Id}" : sendResult.Txid,
                            Amount        = transaction.Amount,
                            TimeStamp     = DateTime.UtcNow,
                            CurrencyId    = Constant.NZDT_ID,
                            Status        = DepositStatus.Confirmed,
                            Confirmations = 20,
                            UserId        = transaction.UserId.Value,
                            Type          = DepositType.Normal
                        };

                        var tx = await context.NzdtTransaction.FirstNoLockAsync(x => x.Id == transaction.Id);

                        tx.Deposit = deposit;

                        await context.SaveChangesAsync();

                        await context.AuditUserBalance(transaction.UserId.Value, Constant.NZDT_ID);

                        await context.SaveChangesAsync();
                    }
                }
                catch (Exception ex)
                {
                    Log.Exception($"[ProcessNZDT] Insert Deposit failed for transaction {transaction.Id}", ex);
                }
            }

            Log.Message(LogLevel.Info, $"[ProcessNZDT] - Processing NZDT Transactions complete.");
        }
Пример #55
0
 ///<summary>Updates one Deposit in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.</summary>
 internal static void Update(Deposit deposit,Deposit oldDeposit)
 {
     string command="";
     if(deposit.DateDeposit != oldDeposit.DateDeposit) {
         if(command!=""){ command+=",";}
         command+="DateDeposit = "+POut.Date(deposit.DateDeposit)+"";
     }
     if(deposit.BankAccountInfo != oldDeposit.BankAccountInfo) {
         if(command!=""){ command+=",";}
         command+="BankAccountInfo = '"+POut.String(deposit.BankAccountInfo)+"'";
     }
     if(deposit.Amount != oldDeposit.Amount) {
         if(command!=""){ command+=",";}
         command+="Amount = '"+POut.Double(deposit.Amount)+"'";
     }
     if(command==""){
         return;
     }
     command="UPDATE deposit SET "+command
         +" WHERE DepositNum = "+POut.Long(deposit.DepositNum);
     Db.NonQ(command);
 }
Пример #56
0
        private void btnUpload_Click(object sender, EventArgs e)
        {
            //toolStripStatusLabel.Text = "Preparing deposit...";
            //toolStripProgressBar.Value = 0;

            if (profile.GetUsername() == null || "".Equals(profile.GetUsername()) ||
                profile.GetPassword() == null || "".Equals(profile.GetPassword()))
            {
                frmLogin loginDialog = new frmLogin();
                loginDialog.Focus();
                loginDialog.TopMost = true;

                if (profile.GetUsername() != null && !"".Equals(profile.GetUsername()))
                {
                    loginDialog.SetUsername(profile.GetUsername());
                }

                if (loginDialog.ShowDialog() == DialogResult.OK)
                {
                    profile.SetUsername(loginDialog.GetUsername());
                    profile.SetPassword(loginDialog.GetPassword());
                    username = profile.GetUsername();
                    //client = new SwordClientHandler(profile.GetUsername(), profile.GetPassword(), profile.GetDepositUri());
                }
            }

            string emIri    = null;
            string seIri    = null;
            string stateIri = null;

            if (action.Equals("create"))
            {
                sc = new SWORDClient(profile.GetDepositUri(), profile.GetUsername(), profile.GetPassword(), profile.GetOnBehalfOf());
                XmlDocument receipt = new XmlDocument();

                try
                {
                    receipt = sc.PostAtom(getAtomEntry());
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        HttpStatusCode code = ((HttpWebResponse)ex.Response).StatusCode;
                        switch (code)
                        {
                        case HttpStatusCode.InternalServerError:
                            MessageBox.Show("The server responded with an Internal Server Error (500). Please contact your repository system administrator and check your profile configuration", "Error creating deposit entry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;

                        default:
                            MessageBox.Show("Error creating deposit, please check your login details and profile configuration.\nReason: " + code.ToString(), "Error creating deposit entry", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
                    {
                        // handle name resolution failure
                        MessageBox.Show("Could not resolve remote server's hostname. Please check your profile configuration and network connectivity.", "Error resolving remote server", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                //MessageBox.Show("RESPONSE\n" + receipt);

                foreach (XmlNode link in receipt.GetElementsByTagName("link"))
                {
                    switch (link.Attributes["rel"].Value)
                    {
                    case "statement":
                        stateIri = link.Attributes["href"].Value;
                        break;

                    case "edit":
                        seIri = link.Attributes["href"].Value;
                        break;

                    case "edit-media":
                        emIri = link.Attributes["href"].Value;
                        break;

                    case "add":
                        break;

                    default:
                        break;
                    }
                }
            }
            else
            {
                emIri = endpoint;
                seIri = Deposit.loadDeposits(Program.userDataPath)[depositId].GetSeIri();
            }

            // Did we successfully retrieve an EM-IRI / SE-IRI?
            if (emIri != null && !"".Equals(emIri))
            {
                string contentType = filemime;
                if (cmbMime.Text != null && !"".Equals(cmbMime.Text))
                {
                    contentType = cmbMime.Text;
                }

                switch (action)
                {
                case "create":
                    UploadFile(file, emIri, seIri, profile.GetPackaging(), contentType);
                    saveDepositInfo(emIri, seIri, stateIri, filename);
                    break;

                case "delete":
                    DeleteResource(endpoint, seIri);
                    saveDepositInfo(emIri, seIri, stateIri, filename);
                    break;

                case "update":
                    UploadFile(file, emIri, seIri, profile.GetPackaging(), contentType);
                    saveDepositInfo(emIri, seIri, stateIri, filename);
                    break;

                case "complete":
                    sc.CompleteDeposit(seIri, DepositCompleted, UploadDataProgressHandler);
                    saveDepositInfo(emIri, seIri, stateIri, filename);
                    break;

                default:
                    break;
                }
            }
        }
Пример #57
0
        public ActionResult Register(int id, string password, string role)
        {
            Session["RegisterError"] = null;
            Session["LoginError"]    = null;


            if (id <= 0 || password == null || role == null)
            {
                Session["RegisterError"] = "Debe completar todos los datos de forma correcta.";
                return(Redirect("../Home/Index"));
            }

            if (role == "admin")
            {
                Admin admin  = new Admin(id, password);
                var   result = admin.isUserValid();

                bool isCorrect; string resultMessage;
                isCorrect     = result.Item1;
                resultMessage = result.Item2;

                if (!isCorrect)
                {
                    Session["RegisterError"] = resultMessage;
                    return(Redirect("../Home/Index"));
                }
                else
                {
                    IRepository <User> userRepository = new UserRepository();
                    userRepository.Add(admin);

                    Session["RegisterError"] = resultMessage;
                    return(Redirect("../Home/Index"));
                }
            }

            else if (role == "deposito")
            {
                Deposit deposit = new Deposit(id, password);
                var     result  = deposit.isUserValid();

                bool isCorrect; string resultMessage;
                isCorrect     = result.Item1;
                resultMessage = result.Item2;

                if (!isCorrect)
                {
                    Session["RegisterError"] = resultMessage;
                    return(Redirect("../Home/Index"));
                }
                else
                {
                    IRepository <User> userRepository = new UserRepository();
                    userRepository.Add(deposit);

                    Session["RegisterError"] = resultMessage;
                    return(Redirect("../Home/Index"));
                }
            }
            else
            {
                Session["RegisterError"] = "El rol ingresado no es válido";
                return(Redirect("../Home/Index"));
            }
        }
Пример #58
0
        //TODO BookingDocument

        protected override Booking DoPostPutDto(Client currentClient, BookingDTO dto, Booking entity, string path, object param)
        {
            if (entity == null)
            {
                entity = new Booking();
            }
            GetMapper.Map <BookingDTO, Booking>(dto, entity);

            HomeConfig hc = HomeConfigRepository.GetHomeConfigById(entity.HomeId, currentClient.Id);

            if (hc != null)
            {
                if (hc.DefaultHourCheckIn != null)
                {
                    entity.DateArrival = ((DateTime)entity.DateArrival).Date.Add(hc.DefaultHourCheckInToTimeSpan);
                }
                if (hc.DefaultHourCheckOut != null)
                {
                    entity.DateDeparture = ((DateTime)entity.DateDeparture).Date.Add(hc.DefaultHourCheckOutToTimeSpan);
                }
            }
            if (dto.People != null)
            {
                entity.People = PeopleService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, dto.People, currentClient, path);
            }
            if (dto.AdditionalBookings != null)
            {
                AdditionalBookingRepository.DeleteRange(entity.AdditionalBookings.Where(d => !dto.AdditionalBookings.Any(x => x.Id == d.Id)));
                dto.AdditionalBookings.ForEach(additionalBooking =>
                {
                    if (entity.AdditionalBookings.Count != 0 && additionalBooking.Id != 0 &&
                        entity.AdditionalBookings.Find(p => p.Id == additionalBooking.Id) != null)
                    {
                        return;
                    }
                    AdditionalBooking toAdd = AdditionalBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, additionalBooking, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.AdditionalBookings.Add(toAdd);
                    }
                });
            }
            if (dto.BookingStepBooking != null)
            {
                entity.BookingStepBooking = BookingStepBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, dto.BookingStepBooking, currentClient, path);
            }
            if (dto.Deposits != null)
            {
                DepositRepository.DeleteRange(entity.Deposits.Where(d => !dto.Deposits.Any(x => x.Id == d.Id)));
                dto.Deposits.ForEach(deposit =>
                {
                    if (entity.Deposits.Count != 0 && deposit.Id != 0 &&
                        entity.Deposits.Find(p => p.Id == deposit.Id) != null)
                    {
                        return;
                    }
                    Deposit toAdd = DepositService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, deposit, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.Deposits.Add(toAdd);
                    }
                });
            }
            if (dto.DinnerBookings != null)
            {
                DinnerBookingRepository.DeleteRange(entity.DinnerBookings.Where(d => !dto.DinnerBookings.Any(x => x.Id == d.Id)));
                dto.DinnerBookings.ForEach(dinnerBooking =>
                {
                    if (entity.DinnerBookings.Count != 0 && dinnerBooking.Id != 0 &&
                        entity.DinnerBookings.Find(p => p.Id == dinnerBooking.Id) != null)
                    {
                        return;
                    }
                    DinnerBooking toAdd = DinnerBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, dinnerBooking, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.DinnerBookings.Add(toAdd);
                    }
                });
            }
            if (dto.ProductBookings != null)
            {
                ProductBookingRepository.DeleteRange(entity.ProductBookings.Where(d => !dto.ProductBookings.Any(x => x.Id == d.Id)));
                dto.ProductBookings.ForEach(productBooking =>
                {
                    if (entity.ProductBookings.Count != 0 && productBooking.Id != 0 &&
                        entity.ProductBookings.Find(p => p.Id == productBooking.Id) != null)
                    {
                        return;
                    }
                    ProductBooking toAdd = ProductBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, productBooking, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.ProductBookings.Add(toAdd);
                    }
                });
            }
            if (dto.RoomBookings != null)
            {
                RoomBokingRepository.DeleteRange(entity.RoomBookings.Where(d => !dto.RoomBookings.Any(x => x.Id == d.Id)));
                dto.RoomBookings.ForEach(roomBooking =>
                {
                    if (entity.RoomBookings.Count != 0 && roomBooking.Id != 0 &&
                        entity.RoomBookings.Find(p => p.Id == roomBooking.Id) != null)
                    {
                        return;
                    }
                    RoomBooking toAdd = RoomBookingService.PreProcessDTOPostPut(validationDictionnary, dto.HomeId, roomBooking, currentClient, path);

                    if (toAdd != null)
                    {
                        entity.RoomBookings.Add(toAdd);
                    }
                });
            }
            entity.DateCreation = DateTime.UtcNow;
            return(entity);
        }
Пример #59
0
        /// <summary>
        /// Returns a list of deposits. It must return pending and confirmed deposits. Ideally confirmed deposits
        /// should be returned only once, but if they are returned multiple times then it's okay (i.e. they won't be
        /// credited multiple times). Pending deposits can be returned in multiple invocations until they become confirmed.
        /// BatchId is an identifier that is passed between calls to ListDeposits. Each call includes the last returned
        /// BatchId (as part of DepositList object). It can be any string, but it usually is the block ID of the last
        /// processed block.
        /// </summary>
        /// <returns>Batch ID of the previous call, or null on the first time</returns>
        public DepositList ListDeposits(string batchId)
        {
            ulong block_id;
            bool  result = ulong.TryParse(batchId, out block_id);

            if (!result)
            {
                Console.WriteLine("failed");
            }
            Console.WriteLine("block_id: {0}", block_id);
            JObject obj = new JObject();

            obj.Add("msg_type", 6);
            obj.Add("msg_cmd", 7);
            obj.Add("msg_id", ++m_cur_msg_id);
            obj.Add("required_confirms", m_required_confirms);
            obj.Add("block_id", block_id);

            DepositList dlist = new DepositList();

            dlist.Deposits = new List <Deposit>();

            string obj_str = JsonConvert.SerializeObject(obj);

            byte[] arr       = System.Text.Encoding.Default.GetBytes(obj_str);
            var    send_task = m_wsock.SendAsync(new ArraySegment <byte>(arr), WebSocketMessageType.Text, true, m_cancel_token);

            send_task.Wait();


            while (true)
            {
                byte[] recv_arr            = new byte[500 * 1024];
                var    recv_task           = m_wsock.ReceiveAsync(new ArraySegment <byte>(recv_arr), m_cancel_token);
                WebSocketReceiveResult res = recv_task.Result;
                byte[] data_arr            = new byte[res.Count];
                Array.Copy(recv_arr, data_arr, res.Count);
                string recv_str = System.Text.Encoding.Default.GetString(data_arr);
                Console.WriteLine(recv_str);
                var  recv_obj    = (JObject)JsonConvert.DeserializeObject(recv_str);
                uint recv_msg_id = (uint)recv_obj.Property("msg_id");

                if (recv_msg_id == m_cur_msg_id)
                {
                    var deposits_json = recv_obj["deposits"];
                    dlist.BatchId = (string)recv_obj["batchId"];

                    Console.WriteLine("batchId: {0}", dlist.BatchId);

                    foreach (var dobj in deposits_json)
                    {
                        JObject deposit_obj = (JObject)dobj;
                        //Console.WriteLine(deposit_obj);
                        Deposit dp = new Deposit();

                        if (deposit_obj["memo"] != null)
                        {
                            dp.Address = (string)deposit_obj["memo"];
                        }

                        dp.Amount        = (decimal)deposit_obj["amount"];
                        dp.Confirmations = (int)deposit_obj["confirms"];
                        dp.Confirmed     = (bool)deposit_obj["confirmed"];
                        dp.TxId          = (string)deposit_obj["tx_id"];
                        dlist.Deposits.Add(dp);
                    }

                    Console.WriteLine("listdeposits ok");
                    break;
                }
            }

            return(dlist);
        }
        public void DepositCheckNewTransactionsTest_TestIfDepositHandlingIsDoneAsExpected_VerifiesThroughReturnedValue()
        {
            // Submits withdraw to own address, after the first NewTransactionInterval has been elapsed.
            // Checks if new deposit has been created by the DepositAPplicationService and DepositAddress marked used
            if (_shouldRunTests)
            {
                ICoinClientService coinClientService =
                    (ICoinClientService)ContextRegistry.GetContext()["LitecoinClientService"];
                IFundsPersistenceRepository fundsPersistenceRepository =
                    (IFundsPersistenceRepository)ContextRegistry.GetContext()["FundsPersistenceRepository"];
                IDepositAddressRepository depositAddressRepository =
                    (IDepositAddressRepository)ContextRegistry.GetContext()["DepositAddressRepository"];
                IDepositRepository depositRepository =
                    (IDepositRepository)ContextRegistry.GetContext()["DepositRepository"];

                Currency       currency       = new Currency("LTC", true);
                AccountId      accountId      = new AccountId(1);
                string         newAddress     = coinClientService.CreateNewAddress();
                BitcoinAddress bitcoinAddress = new BitcoinAddress(newAddress);
                DepositAddress depositAddress = new DepositAddress(currency, bitcoinAddress,
                                                                   AddressStatus.New, DateTime.Now, accountId);
                fundsPersistenceRepository.SaveOrUpdate(depositAddress);

                // Check that there is no deposit with htis address present
                List <Deposit> deposits = depositRepository.GetDepositsByBitcoinAddress(bitcoinAddress);
                Assert.AreEqual(0, deposits.Count);

                ManualResetEvent manualResetEvent = new ManualResetEvent(false);

                // Wait for the first interval to elapse, and then withdraw, because only then we will be able to figure if a
                // new transaction has been received
                manualResetEvent.WaitOne(Convert.ToInt32(coinClientService.PollingInterval + 3000));

                manualResetEvent.Reset();
                bool eventFired = false;
                coinClientService.DepositArrived += delegate(string curr, List <Tuple <string, string, decimal, string> > pendingList)
                {
                    eventFired = true;
                    manualResetEvent.Set();
                };

                Withdraw withdraw = new Withdraw(currency, Guid.NewGuid().ToString(), DateTime.Now, WithdrawType.Bitcoin,
                                                 Amount, 0.001m, TransactionStatus.Pending, accountId,
                                                 new BitcoinAddress(newAddress));
                string commitWithdraw = coinClientService.CommitWithdraw(withdraw.BitcoinAddress.Value, withdraw.Amount);
                Assert.IsNotNull(commitWithdraw);
                Assert.IsFalse(string.IsNullOrEmpty(commitWithdraw));
                manualResetEvent.WaitOne();

                Assert.IsTrue(eventFired);
                depositAddress = depositAddressRepository.GetDepositAddressByAddress(bitcoinAddress);
                Assert.IsNotNull(depositAddress);
                Assert.AreEqual(AddressStatus.Used, depositAddress.Status);

                // See If DepositApplicationService created the deposit instance
                deposits = depositRepository.GetDepositsByBitcoinAddress(bitcoinAddress);
                Deposit deposit = deposits.Single();
                Assert.IsNotNull(deposit);
                Assert.AreEqual(Amount, deposit.Amount);
                Assert.AreEqual(currency.Name, deposit.Currency.Name);
                Assert.IsFalse(string.IsNullOrEmpty(deposit.TransactionId.Value));
                Assert.AreEqual(bitcoinAddress.Value, deposit.BitcoinAddress.Value);
                Assert.AreEqual(DepositType.Default, deposit.Type);
                Assert.AreEqual(0, deposit.Confirmations);
                Assert.AreEqual(accountId.Value, deposit.AccountId.Value);
                Assert.AreEqual(TransactionStatus.Pending, deposit.Status);
            }
        }