How to use a changed value (C# / WCF) - c#

So I need to create this bank service. I have everything except I am trying to use the updated balance from a customer after a transaction such a withdraw or deposit. For example the customer starts off with $1000, and customer 1 deposits $300. The updated balance should be $1300, but once I do another transaction it goes back to the default $1000, instead of the new balance of $1300. The customers are in a list.
[ServiceContract(SessionMode=SessionMode.Allowed)]
public interface IBankService
{
[OperationContract]
string GetCustDetails(int act);
[OperationContract]
string WithdrawMoney(int act, double amt);
[OperationContract]
string DepositMoney(int act,double amt);
[OperationContract]
string ViewBalance(int act);
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class Customer
{
private int accountNumber; private double viewBalance, depositMoney;
private string customerName, customerAddress;
public Customer(int act, string str_name, string adrs, double bal)
{
accountNumber = act;
customerName = str_name;
customerAddress = adrs;
viewBalance = bal;
}
[DataMember(Name = "Name")]
public string CustomerName
{
get { return customerName; }
set { customerName = value; }
}
[DataMember(Name = "Address")]
public string CustomerAddress
{
get { return customerAddress; }
set { customerAddress = value; }
}
[DataMember(Name = "Account")]
public int AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
[DataMember(Name = "Balance", EmitDefaultValue = true)]
public double ViewBalance
{
get { return viewBalance; }
set
{
if (value <= 0.0)
viewBalance = 0.0;
else
viewBalance = value;
}
}
[DataMember(Name = "Credit")]
public double DepositMoney
{
get { return depositMoney; }
set { depositMoney = value; }
}
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class BankService : IBankService
{
List<Customer> custList;
static double balance1 = 1000;
static double balance2 = 1000;
static double balance3 = 1000;
static double balance4 = 1000;
static double balance5 = 1000;
public BankService()
{
custList = new List<Customer>();
custList.Add(new Customer(100, "Jack", "404 Bay Avenue", balance1));
custList.Add(new Customer(200, "Jeff", "255 Wade Avenue",balance2));
custList.Add(new Customer(300, "Lou", "984 Leslie Road", balance3));
custList.Add(new Customer(400, "Johnson","1080 Queen Street", balance4));
custList.Add(new Customer(500, "Alex","777 Jane Street", balance5));
}
public string GetCustDetails(int act)
{
foreach (Customer cust in custList)
{
if (cust.AccountNumber == act)
{
return string.Format("Account Number: " + cust.AccountNumber + "\n" +
"Name: " + cust.CustomerName + "\n" +
"Address: " + cust.CustomerAddress + "\n" +
"Balance: $" + cust.ViewBalance);
}
} // end foreach
return string.Format("{0}", "Customer does not exists!");
}
//public string DepositMoney(int act, double amt)
//{
// string balance = null;
// foreach (Customer cust in custList)
// {
// if (cust.AccountNumber == act)
// {
// bal = bal + Dep;
// }
// }
// return balance;
//}
public string DepositMoney(int act, double amt)
{
foreach (Customer cust in custList)
{
if (cust.AccountNumber == act)
{
cust.ViewBalance = cust.ViewBalance + amt;
return string.Format("Account Number : " + cust.AccountNumber + "\n" +
"Name : " + cust.CustomerName + "\n" +
"Address : " + cust.CustomerAddress + "\n" +
"Balance :$ " + cust.ViewBalance);
}
}
return string.Format("{0}", "Customer does not exists!");
}
//public double WithdrawMoney(double widraw)
//{
// return bal = bal - widraw;
//}
// public double ViewBalance(int act)
//{
// return bal;
//}
public string WithdrawMoney(int act, double amt)
{
foreach (Customer cust in custList)
{
if (cust.AccountNumber == act)
{
cust.ViewBalance = cust.ViewBalance - amt;
return string.Format("Account Number : " + cust.AccountNumber + "\n" +
"Name : " + cust.CustomerName + "\n" +
"Address : " + cust.CustomerAddress + "\n" +
"Balance :$ " + cust.ViewBalance);
}
}
return string.Format("{0}", "Customer does not exists!");
}
public string ViewBalance(int act)
{
foreach (Customer cust in custList)
{
if (cust.AccountNumber == act)
{
return string.Format("Balance : $" + cust.ViewBalance);
}
}
return string.Format("{0}", "Customer does not exists!");
}
}
Each customer has their own account number that is already assigned.

How are you consuming this service ?
I mean to say how you are creating your client (can you post some code).
Following salient points are taken into account while consuming the service
Adding a service reference
Creating an instance of the client
Calling the web methods of the instance

Related

Need help in C# to delete obj in a list

I have an employee management system which I'm trying to build in c# console application whereas im able to add a new employee.
but I'm not sure on how can I delete a employee from the list.
I have to put together both method then it works.
it seem like i'm unable to call the obj (emp) from my removeEmployee method
Main class
using System;
namespace HRM
{
class Program
{
static void Main(string[] args)
{
manageEmp emp = new manageEmp();
emp.addEmployee();
emp.removeEmployee();
}
}
}
Employee Class
using System;
using System.Collections.Generic;
namespace HRM
{
public class Employee
{
private String empID;
private String empFirstName;
private String empLastName;
private String empDep;
private String empDOB;
private String empAddress;
private int PostalCode;
private double empSal;
public Employee()
{
}
public Employee(String aempID, string aempFirstName, string aempLasttName, string aempDep, String aEmpDOB, string aempAddress, int aPostalCode, double aempSal)
{
this.EmpID = aempID;
this.EmpFirstName = aempFirstName;
this.EmpLastName = aempLasttName;
this.EmpDep = aempDep;
this.EmpDOB = aEmpDOB;
this.EmpAddress = aempAddress;
this.PostalCode1 = aPostalCode;
this.EmpSal = aempSal;
}
public string EmpID { get => empID; set => empID = value; }
public string EmpFirstName { get => empFirstName; set => empFirstName = value; }
public string EmpLastName { get => empLastName; set => empLastName = value; }
public string EmpDep { get => empDep; set => empDep = value; }
public string EmpDOB { get => empDOB; set => empDOB = value; }
public string EmpAddress { get => empAddress; set => empAddress = value; }
public int PostalCode1 { get => PostalCode; set => PostalCode = value; }
public double EmpSal { get => empSal; set => empSal = value; }
public List<Employee> El { get => el; set => el = value; }
public override string ToString()
{
return "Employment ID : " + empID + "\n"
+ "FirstName : " + EmpFirstName + "\n"
+ "LastName : " + EmpLastName + "\n"
+ "Department : " + EmpDep + "\n"
+ "Date of Birth: " + EmpDOB + "\n"
+ "Address : " + EmpAddress + "\n"
+ "PostalCode : " + PostalCode1 + "\n"
+ "empSal : " + EmpSal + "\n";
}
}
}
manageEmp class
using System;
using System.Collections.Generic;
namespace HRM
{
public class manageEmp
{
private List<Employee> el = new List<Employee>();
public List<Employee> El { get => el; set => el = value; }
public void addEmployee()
{
Console.WriteLine("===================================" + "\n");
Console.WriteLine("Add an Employee");
Console.WriteLine("===================================" + "\n");
Console.WriteLine("");
Console.WriteLine("Please enter your Employment ID");
String eID = Console.ReadLine();
Console.WriteLine("Please enter your First Name");
String eFirstName = Console.ReadLine();
Console.WriteLine("Please enter your Last Name");
String eLasttName = Console.ReadLine();
Console.WriteLine("Please entter your department");
String eDep = Console.ReadLine();
Console.WriteLine("Please enter your Date of Birth");
String eDOB = Console.ReadLine();
Console.WriteLine("Please entter your Address");
String eAddress = Console.ReadLine();
Console.WriteLine("Please enter your Postal Code");
int ePostalCode = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter your Salary");
double eSal = Convert.ToDouble(Console.ReadLine());
Employee emp = new Employee(eID, eFirstName, eLasttName, eDep, eDOB, eAddress, ePostalCode, eSal);
emp.El.Add(emp);
}
public void viewEmployee()
{
Employee nemp = new Employee();
nemp.El.ForEach(Console.WriteLine);
}
public void removeEmployee()
{
Console.WriteLine("Please enter a employee Id to be deleted");
String delemp = Console.ReadLine();
for (int i = 0; i < El.Count; i++)
{
emp = El[i];
if (delemp.Equals(eID))
{
el.Remove(emp);
}
Console.WriteLine(delemp + " Has been deleted sucessfully");
el.ForEach(Console.WriteLine);
}
}
}
}
Your problem is that your employee list is inside the employee class -- so each of the employees has its own list of employees -- and that list only contains that single employee.
In the function RemoveEmployee you are creating a new manageEmp object. As the word 'new' implies, this is a different, newly created manageEmp with its own, newly created List<Employee> which doesn't contain any items.
Further, you have declared the function as public void removeEmployee(string eID) so you can't call it with the line emp.removeEmployee().

Reading Generic Value from List of Generic Objects

I am trying to loop through a list of generic objects call Condition<T> to read the generic field Value. I followed this question to be able to store the List<Condition<T>>. The issue I am running into now is that I can't use the Value field in my loop. What do I need to change in order to use the Value field?
Main
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal))
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual))
foreach (ConditionBase c in Conditions)
{
if (c.GetType() == typeof(string))
{
// c.Value throws an error
url += c.Field + " " + c.ConditionOperator + " '" + c.Value + "' and ";
}
else if (c.GetType() == typeof(DateTime))
{
// c.Value throws an error
url += c.Field + " " + c.ConditionOperator + " " + Helpers.FormatDate(c.Value) + " and ";
}
}
Condition Base
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
}
Condition
public class Condition<T> : ConditionBase
{
private Field _Field;
private T _Value;
private ConditionOperator _ConditionOperator;
public Condition(Field field, T value, ConditionOperator condition)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
}
public Field Field
{
get
{
return this._Field;
}
set
{
if (this._Field != value)
{
this._Field = value;
}
}
}
public T Value
{
get
{
return this._Value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(this._Value, value))
{
this._Value = value;
}
}
}
public ConditionOperator ConditionOperator
{
get
{
return this._ConditionOperator;
}
set
{
if (this._ConditionOperator != value)
{
this._ConditionOperator = value;
}
}
}
}
Enums
public enum Field{
Field1,
Field2
}
public enum ConditionOperator{
Equal,
NotEqual,
GreaterThan,
LessThan
}
Solution
This solution is based on the comments by #orhtej2 & the answer by #Igor.
Main - Test
static void Main(string[] args)
{
var x1 = new Condition<int>(new Field(), 123, ConditionOperator.Equal);
var x2 = new Condition<string>(new Field(), "test", ConditionOperator.Equal);
var x3 = new Condition<DateTime>(new Field(), new DateTime(2018,5,5), ConditionOperator.Equal);
var qqq = new List<ConditionBase>();
qqq.Add(x1);
qqq.Add(x2);
qqq.Add(x3);
foreach (ConditionBase c in qqq)
{
Console.WriteLine(c.GetValue());
}
Console.ReadLine();
}
Condition Base
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
string GetValue();
}
Condition
public class Condition<T> : ConditionBase
{
private Field _Field;
private T _Value;
private ConditionOperator _ConditionOperator;
public Condition(Field field, T value, ConditionOperator condition)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
}
public Field Field
{
get
{
return this._Field;
}
set
{
if (this._Field != value)
{
this._Field = value;
}
}
}
public T Value
{
get
{
return this._Value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(this._Value, value))
{
this._Value = value;
}
}
}
public ConditionOperator ConditionOperator
{
get
{
return this._ConditionOperator;
}
set
{
if (this._ConditionOperator != value)
{
this._ConditionOperator = value;
}
}
}
public string GetValue()
{
if (Value is string)
{
return "'" + Value.ToString() + "'";
}
else if (Value is DateTime)
{
return Helpers.FormatDate(Convert.ToDateTime(Value));
}
else
{
return Value.ToString();
}
}
}
Enums
public enum Field{
Field1,
Field2
}
public enum ConditionOperator{
Equal,
NotEqual,
GreaterThan,
LessThan
}
You have syntax errors in the code like the lacking public scope of your enums and ConditionOperator.Equal (not ConditionOperator.Equals) but that asside here is the fix.
Conditions should be of type List<ConditionBase>
Use OfType on the List to retrieve and cast the resulting type to Condition<string>. I assume that this was your intention with your added check c.GetType() == typeof(string)
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual));
foreach (var c in Conditions.OfType<Condition<string>>())
{
url += c.Field + " " + c.ConditionOperator + " '" + c.Value + "' and ";
}
If you want a generic property that you can access on all instances regardless of the generic type constraint then you would need to extend the base interface accordingly.
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
object FieldValue { get; }
}
public class Condition<T> : ConditionBase
{
/* I only included the added code in this type */
public object FieldValue
{
get { return (object) this.Value; }
}
}
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual));
foreach (var c in Conditions)
{
url += c.Field + " " + c.ConditionOperator + " '" + c.FieldValue + "' and ";
}
It seems you want to output your value to a string based on the changes in your question. Add a string formatter to your type.
/* I only included the added code in this type */
public class Condition<T> : ConditionBase
{
private Func<T, string> _formatValue;
public Condition(Field field, T value, ConditionOperator condition, Func<T, string> formatValue)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
this._formatValue = formatValue;
}
public override string ToString()
{
return this._formatValue(this.Value);
}
}
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal, (val)=> val.ToString()));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual, (val)=> val));
foreach (var c in Conditions)
{
url += c.Field + " " + c.ConditionOperator + " '" + c.ToString() + "' and ";
}

Creating an object in the main method. Printing array values in the object

I'm fairly new to C# and I have created a small program with 2 classes ( 1 being the class containing the main method).
Instructor class:
namespace Exercise4
{
class Account
{
public long accountNo { set; get; }
public double balance { set; get; }
public string [] payees { set; get; }
public long [] payeesAccount { set; get; }
public Account()
{
this.accountNo = 0L;
this.balance = 0.0;
}
public Account(long accountNo,double balance)
{
this.accountNo = accountNo;
this.balance = balance;
}
public Account(long accountNo, double balance, string [] payees, long [] payeesAccount)
{
this.accountNo = accountNo;
this.balance = balance;
this.payees = payees;
this.payeesAccount = payeesAccount;
}
public int DebitAmount(double amount)
{
if ((this.balance - amount) <= this.balance)
return 1;
else
return 0;
}
public int TransferMoney(long payeeAccountNo, double amount)
{
if (payeesAccount.Contains(payeeAccountNo))
return DebitAmount(amount);
else
return -1;
}
public int TransferMoeny(string nickName,double amount)
{
if (payees.Contains(nickName))
return DebitAmount(amount);
else
return -1;
}
public string ToString()
{
string output = "";
output += "\nAccount Number: " + this.accountNo;
output += "\nBalance: " + this.balance;
output += "\nPayee: " + this.payees;
output += "\nPayee Account: " + this.payeesAccount;
return output;
}
}
}
Main method class:
namespace Exercise4
{
class Program
{
static void Main(string[] args)
{
string [] payee = new [] {"Oli"};
long[] payeesAccount = new[] {1000L};
Account reg = new Account(1000,100.00,payee,payeesAccount);
Console.WriteLine(reg.ToString());
}
}
}
I'm trying to print the value(Payee: Oli, Payee Account: 1000 )of the arrays instead of:
Account Number: 1000
Balance: 100
Payee: System.String[]
Payee Account: System.Int64[]
Any thoughts?
Thanks
You can use string.Join for such purposes
Try to define your method ToString() like this:
public override string ToString()
{
string output = "";
output += "\nAccount Number: " + this.accountNo;
output += "\nBalance: " + this.balance;
output += "\nPayee: " + string.Join(",", this.payees);
output += "\nPayee Account: " + string.Join(",", this.payeesAccount);
return output;
}
If you override the default method ToString() correctly then you can use it like this:
Console.WriteLine(reg);
Without the need to call it esplicitly.
And your overriden method should look like this, with string builder to create dynamic string properly:
public override string ToString()
{
var output = new StringBuilder();
output.Append("\nAccount Number: " + this.accountNo);
output.Append("\nBalance: " + this.balance);
output.Append("\nPayee: " + string.Join(", ", this.payees));
output.Append("\nPayee Account: " + string.Join(", ", this.payeesAccount));
return output.ToString();
}
And even better with C# 6.0+ using string interpolation:
public override string ToString()
{
var output = new StringBuilder();
output.Append($"Account Number: {accountNo}\n");
output.Append($"Balance: {balance}\n");
output.Append($"Payee: {string.Join(", ", payees)}\n");
output.Append($"Payee Account: {string.Join(", ", payeesAccount)}\n");
return output.ToString();
}
But I can advice you to review your class and decide if you realy need to have string[] instead of just string, as I can see you have only one payee and their account.

How to multiply by sales tax

I need to take the sales tax that is entered in CollectHeader()
and calculate and produce an output called totalPrice to show the productPrice * salesTax
Multiple ways i have tried i was unsucessful
Here is what i have
namespace ConsoleApplication1
{
class CustomerOrder
{
string company;
string productName1;
int productAmount1;
decimal productPrice1;
string productName2;
int productAmount2;
decimal productPrice2;
string productName3;
int productAmount3;
decimal productPrice3;
string companyName;
string companyAddress;
int salesTax;
public string ProductName1
{
get
{
return productName1;
}
set
{
productName1 = value;
}
}
public string ProductName2
{
get
{
return productName2;
}
set
{
productName2 = value;
}
}
public string ProductName3
{
get
{
return productName3;
}
set
{
productName3 = value;
}
}
public int ProductAmount1
{
get
{
return productAmount1;
}
set
{
productAmount1 = value;
}
}
public int ProductAmount2
{
get
{
return productAmount2;
}
set
{
productAmount2 = value;
}
}
public int ProductAmount3
{
get
{
return productAmount3;
}
set
{
productAmount3 = value;
}
}
public decimal ProductPrice1
{
get
{
return productPrice1;
}
set
{
productPrice1 = value;
}
}
public decimal ProductPrice2
{
get
{
return productPrice2;
}
set
{
productPrice2 = value;
}
}
public decimal ProductPrice3
{
get
{
return productPrice3;
}
set
{
productPrice3 = value;
}
}
public string CompanyName
{
get
{
return companyName;
}
set
{
companyName = value;
}
}
public string CompanyAddress
{
get
{
return companyAddress;
}
set
{
companyAddress = value;
}
}
public int SalesTax
{
get
{
return salesTax;
}
set
{
salesTax = value;
}
}
public CustomerOrder()
{
}
public void CollectHeader()
{
string inputValue;
Console.WriteLine("What name of the company {0}?", companyName);
inputValue = Console.ReadLine();
companyName = inputValue;
Console.WriteLine("What is the address?", companyAddress);
inputValue = Console.ReadLine();
companyAddress = inputValue;
Console.WriteLine("What is the sales tax?", salesTax);
inputValue = Console.ReadLine();
salesTax = Int32.Parse(inputValue);
}
public void PrintHeader()
{
Console.WriteLine("This is the {0} Customer Order Storage program.", companyName);
Console.WriteLine("Address: {0}", companyAddress);
Console.WriteLine("Sales Tax: {0}", salesTax);
}
public static void PrintEntryHeader()
{
Console.WriteLine("Please enter the following details about the order.\n");
}
public static void PrintSummaryHeader()
{
Console.WriteLine("Order entry is now complete.\nThe following orders have been stored");
}
public void PrintSummary()
{
Console.WriteLine(this.ToString());
Console.ReadKey();
}
public void CollectAllInput_Counter()
{
int productNumber = 1;
while (productNumber <= 3)
{
CollectItemSwitch(productNumber);
productNumber++;
}
}
public void CollectAllInput_For()
{
for (int productNumber = 1; productNumber <= 3; productNumber++)
{
CollectItemSwitch(productNumber);
}
}
public void CollectItem(int productNumber)
{
string productName;
int productAmount;
decimal productPrice;
string inputValue;
Console.WriteLine("What name of the product ordered {0}?", productNumber);
inputValue = Console.ReadLine();
productName = inputValue;
Console.WriteLine("What is the inventory quantity of drink {0}?", productNumber);
inputValue = Console.ReadLine();
productAmount = Int32.Parse(inputValue);
Console.WriteLine("What is the price of the product named {0}?", productNumber);
inputValue = Console.ReadLine();
productPrice = Decimal.Parse(inputValue);
if (productNumber > 0 && productNumber < 4)
{
if (productNumber == 1)
{
this.productName1 = productName;
this.productAmount1 = productAmount;
this.productPrice1 = productPrice;
}
if (productNumber == 2)
{
this.productName2 = productName;
this.productAmount2 = productAmount;
this.productPrice2 = productPrice;
}
if (productNumber == 3)
{
this.productName3 = productName;
this.productAmount3 = productAmount;
this.productPrice3 = productPrice;
}
}
}
public void CollectItemSwitch(int productNumber)
{
if (productNumber > 0 && productNumber < 4)
{
string productName;
int productAmount;
decimal productPrice;
string inputValue;
Console.WriteLine("What is the name of the product {0}\n", productNumber);
inputValue = Console.ReadLine();
productName = inputValue;
Console.WriteLine("What is the amount of product {0}\n", productNumber);
inputValue = Console.ReadLine();
productAmount = Int32.Parse(inputValue);
if (Int32.TryParse(inputValue, out productAmount) == false)
{
Console.WriteLine("[{0}] is not a valid number. Quantity is set to 0.", inputValue);
productAmount = 0;
}
Console.WriteLine("What is the price of product {0}", productNumber);
inputValue = Console.ReadLine();
productPrice = Decimal.Parse(inputValue);
if (!Decimal.TryParse(inputValue, out productPrice) == false)
{
Console.WriteLine("[{0}] is not a valid price. Price is set to 0.00.", inputValue);
}
switch (productNumber)
{
case 1:
this.productName1 = productName;
this.productAmount1 = productAmount;
this.productPrice1 = productPrice;
break;
case 2:
this.productName2 = productName;
this.productAmount2 = productAmount;
this.productPrice2 = productPrice;
break;
case 3:
this.productName3 = productName;
this.productAmount3 = productAmount;
this.productPrice3 = productPrice;
break;
}
}
else
{
throw new Exception(String.Format("The order number [{0}] is not valid", productNumber));
}
}
public override string ToString()
{
string outputString = company + "\n";
outputString += "Product 1: " + productName1 + ", Amount: " + productAmount1 + ", Price" + productPrice1 + "\n";
outputString += "Product 2: " + productName2 + ", Amount: " + productAmount2 + ", Price" + productPrice2 + "\n";
outputString += "Product 3: " + productName3 + ", Amount: " + productAmount3 + ", Price" + productPrice3;
return outputString;
}
}
}
public void CollectHeader()
{
string inputValue;
Console.WriteLine("What name of the company {0}?", companyName);
inputValue = Console.ReadLine();
companyName = inputValue;
Console.WriteLine("What is the address?", companyAddress);
inputValue = Console.ReadLine();
companyAddress = inputValue;
Console.WriteLine("What is the sales tax?", salesTax);
inputValue = Console.ReadLine();
float salesTax = float.Parse(inputValue);
//Assuming that salesTax is in the form of 1 + decimal percentage. For example, for a 5% tax, salesTax would be 1.05.
float totalPrice = productPrice1*salesTax + productPrice2*salesTax + productPrice3*salesTax;
Console.WriteLine("The total cost is " + totalPrice.ToString("c2") + ". Thank you for shopping at StackOverFlowmart.");
}

Reading data in from file

Here is link if you want to download application:
Simple banking app
Text file with data to read
I am trying to create a simple banking application that reads in data from a text file. So far i have managed to read in all the customers which there are 20 of them. However when reading in the accounts and transactions stuff it only reads in 20 but there is alot more in the text file.
Here is what i have so far. I think it has something to do with the nested for loop in the getNextCustomer method.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace e_SOFT_Banking
{
public partial class Form1 : Form
{
public static ArrayList bankDetails = new ArrayList();
public static ArrayList accDetails = new ArrayList();
public static ArrayList tranDetails = new ArrayList();
string inputDataFile = #"C:\e-SOFT_v1.txt";
const int numCustItems = 14;
const int numAccItems = 7;
const int numTransItems = 5;
public Form1()
{
InitializeComponent();
setUpBank();
}
private void btnShowData_Click_1(object sender, EventArgs e)
{
showListsOfCust();
}
private void setUpBank()
{
readData();
}
private void showListsOfCust()
{
listBox1.Items.Clear();
foreach (Customer c in bankDetails)
listBox1.Items.Add(c.getCustomerNumber() + " " + c.getCustomerTitle() + " " + c.getFirstName()
+ " " + c.getInitials() + " " + c.getSurname() + " " + c.getDateOfBirth()
+ " " + c.getHouseNameNumber() + " " + c.getStreetName() + " " + c.getArea()
+ " " + c.getCityTown() + " " + c.getCounty() + " " + c.getPostcode()
+ " " + c.getPassword() + " " + c.getNumberAccounts());
foreach (Account a in accDetails)
listBox1.Items.Add(a.getAccSort() + " " + a.getAccNumber() + " " + a.getAccNick() + " " + a.getAccDate()
+ " " + a.getAccCurBal() + " " + a.getAccOverDraft() + " " + a.getAccNumTrans());
foreach (Transaction t in tranDetails)
listBox1.Items.Add(t.getDate() + " " + t.getType() + " " + t.getDescription() + " " + t.getAmount()
+ " " + t.getBalAfter());
}
private void readData()
{
StreamReader readerIn = null;
Transaction curTrans;
Account curAcc;
Customer curCust;
bool anyMoreData;
string[] customerData = new string[numCustItems];
string[] accountData = new string[numAccItems];
string[] transactionData = new string[numTransItems];
if (readOK(inputDataFile, ref readerIn))
{
anyMoreData = getNextCustomer(readerIn, customerData, accountData, transactionData);
while (anyMoreData == true)
{
curCust = new Customer(customerData[0], customerData[1], customerData[2], customerData[3], customerData[4],
customerData[5], customerData[6], customerData[7], customerData[8], customerData[9],
customerData[10], customerData[11], customerData[12], customerData[13]);
curAcc = new Account(accountData[0], accountData[1], accountData[2], accountData[3], accountData[4],
accountData[5], accountData[6]);
curTrans = new Transaction(transactionData[0], transactionData[1], transactionData[2], transactionData[3],
transactionData[4]);
bankDetails.Add(curCust);
accDetails.Add(curAcc);
tranDetails.Add(curTrans);
anyMoreData = getNextCustomer(readerIn, customerData, accountData, transactionData);
}
if (readerIn != null)
readerIn.Close();
}
}
private bool getNextCustomer(StreamReader inNext, string[] nextCustomerData, string[] nextAccountData, string[] nextTransactionData)
{
string nextLine;
int numCItems = nextCustomerData.Count();
int numAItems = nextAccountData.Count();
int numTItems = nextTransactionData.Count();
for (int i = 0; i < numCItems; i++)
{
nextLine = inNext.ReadLine();
if (nextLine != null)
{
nextCustomerData[i] = nextLine;
if (i == 13)
{
int cItems = Convert.ToInt32(nextCustomerData[13]);
for (int q = 0; q < cItems; q++)
{
for (int a = 0; a < numAItems; a++)
{
nextLine = inNext.ReadLine();
nextAccountData[a] = nextLine;
if (a == 6)
{
int aItems = Convert.ToInt32(nextAccountData[6]);
for (int w = 0; w < aItems; w++)
{
for (int t = 0; t < numTItems; t++)
{
nextLine = inNext.ReadLine();
nextTransactionData[t] = nextLine;
}
}
}
}
}
}
}
else
return false;
}
return true;
}
private bool readOK(string readFile, ref StreamReader readerIn)
{
try
{
readerIn = new StreamReader(readFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when reading data in)" + " - File could not be found.\n" + notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when reading data in)" + "- Operation failed.\n" + e.Message);
return false;
}
}
}
}
I also have three classes one for customers, one for accounts and one for transactions, which follow in that order.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace e_SOFT_Banking
{
class Customer
{
private string customerNumber;
private string customerTitle;
private string firstName;
private string initials; //not required - defaults to null
private string surname;
private string dateOfBirth;
private string houseNameNumber;
private string streetName;
private string area; //not required - defaults to null
private string cityTown;
private string county;
private string postcode;
private string password;
private int numberAccounts;
public Customer(string theCustomerNumber, string theCustomerTitle, string theFirstName, string theInitials, string theSurname, string theDateOfBirth, string theHouseNameNumber, string theStreetName, string theArea, string theCityTown, string theCounty, string thePostcode, string thePassword, string theNumberAccounts)
{
customerNumber = theCustomerNumber;
customerTitle = theCustomerTitle;
firstName = theFirstName;
initials = theInitials;
surname = theSurname;
dateOfBirth = theDateOfBirth;
houseNameNumber = theHouseNameNumber;
streetName = theStreetName;
area = theArea;
cityTown = theCityTown;
county = theCounty;
postcode = thePostcode;
password = thePassword;
setNumberAccounts(theNumberAccounts);
}
public string getCustomerNumber()
{
return customerNumber;
}
public string getCustomerTitle()
{
return customerTitle;
}
public string getFirstName()
{
return firstName;
}
public string getInitials()
{
return initials;
}
public string getSurname()
{
return surname;
}
public string getDateOfBirth()
{
return dateOfBirth;
}
public string getHouseNameNumber()
{
return houseNameNumber;
}
public string getStreetName()
{
return streetName;
}
public string getArea()
{
return area;
}
public string getCityTown()
{
return cityTown;
}
public string getCounty()
{
return county;
}
public string getPostcode()
{
return postcode;
}
public string getPassword()
{
return password;
}
public int getNumberAccounts()
{
return numberAccounts;
}
public void setCustomerNumber(string inCustomerNumber)
{
customerNumber = inCustomerNumber;
}
public void setCustomerTitle(string inCustomerTitle)
{
customerTitle = inCustomerTitle;
}
public void setFirstName(string inFirstName)
{
firstName = inFirstName;
}
public void setInitials(string inInitials)
{
initials = inInitials;
}
public void setSurname(string inSurname)
{
surname = inSurname;
}
public void setDateOfBirth(string inDateOfBirth)
{
dateOfBirth = inDateOfBirth;
}
public void setHouseNameNumber(string inHouseNameNumber)
{
houseNameNumber = inHouseNameNumber;
}
public void setStreetName(string inStreetName)
{
streetName = inStreetName;
}
public void setArea(string inArea)
{
area = inArea;
}
public void setCityTown(string inCityTown)
{
cityTown = inCityTown;
}
public void setCounty(string inCounty)
{
county = inCounty;
}
public void setPostcode(string inPostcode)
{
postcode = inPostcode;
}
public void setPassword(string inPassword)
{
password = inPassword;
}
public void setNumberAccounts(string inNumberAccounts)
{
try
{
numberAccounts = Convert.ToInt32(inNumberAccounts);
}
catch (FormatException invalidInput)
{
System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
}
}
}
}
Accounts:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace e_SOFT_Banking
{
class Account
{
private string accSort;
private Int64 accNumber;
private string accNick;
private string accDate; //not required - defaults to null
private double accCurBal;
private double accOverDraft;
private int accNumTrans;
public Account(string theAccSort, string theAccNumber, string theAccNick,
string theAccDate, string theAccCurBal, string theAccOverDraft,
string theAccNumTrans)
{
accSort = theAccSort;
setAccNumber(theAccNumber);
accNick = theAccNick;
accDate = theAccDate;
setAccCurBal(theAccCurBal);
setAccOverDraft(theAccOverDraft);
setAccNumTrans(theAccNumTrans);
}
public string getAccSort()
{
return accSort;
}
public long getAccNumber()
{
return accNumber;
}
public string getAccNick()
{
return accNick;
}
public string getAccDate()
{
return accDate;
}
public double getAccCurBal()
{
return accCurBal;
}
public double getAccOverDraft()
{
return accOverDraft;
}
public int getAccNumTrans()
{
return accNumTrans;
}
public void setAccSort(string inAccSort)
{
accSort = inAccSort;
}
public void setAccNumber(string inAccNumber)
{
try
{
accNumber = Convert.ToInt64(inAccNumber);
}
catch (FormatException invalidInput)
{
System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
}
}
public void setAccNick(string inAccNick)
{
accNick = inAccNick;
}
public void setAccDate(string inAccDate)
{
accDate = inAccDate;
}
public void setAccCurBal(string inAccCurBal)
{
try
{
accCurBal = Convert.ToDouble(inAccCurBal);
}
catch (FormatException invalidInput)
{
System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
}
}
public void setAccOverDraft(string inAccOverDraft)
{
try
{
accOverDraft = Convert.ToDouble(inAccOverDraft);
}
catch (FormatException invalidInput)
{
System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
}
}
public void setAccNumTrans(string inAccNumTrans)
{
try
{
accNumTrans = Convert.ToInt32(inAccNumTrans);
}
catch (FormatException invalidInput)
{
System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
}
}
}
}
Transactions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace e_SOFT_Banking
{
class Transaction
{
private string date;
private string type;
private string description;
private double amount; //not required - defaults to null
private double balAfter;
public Transaction(string theDate, string theType, string theDescription,
string theAmount, string theBalAfter)
{
date = theDate;
type = theType;
description = theDescription;
setAmount(theAmount);
setBalAfter(theBalAfter);
}
public string getDate()
{
return date;
}
public string getType()
{
return type;
}
public string getDescription()
{
return description;
}
public double getAmount()
{
return amount;
}
public double getBalAfter()
{
return balAfter;
}
public void setDate(string inDate)
{
date = inDate;
}
public void setType(string inType)
{
type = inType;
}
public void setDescription(string inDescription)
{
description = inDescription;
}
public void setAmount(string inAmount)
{
try
{
amount = Convert.ToDouble(inAmount);
}
catch (FormatException invalidInput)
{
System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
}
}
public void setBalAfter(string inBalAfter)
{
try
{
balAfter = Convert.ToDouble(inBalAfter);
}
catch (FormatException invalidInput)
{
System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
}
}
}
}
Any help greatly appreciated.
Your problem start with the following
string[] customerData = new string[numCustItems];
string[] accountData = new string[numAccItems];
string[] transactionData = new string[numTransItems];
With this structure and the call
anyMoreData = getNextCustomer(readerIn, customerData, accountData, transactionData);
you will get only one accountData and one transactionData for one customer.
Please redesign your code, so that your data objects know how to read theirselve from the datastream.

Categories