How to multiply by sales tax - c#

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.");
}

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().

How to add items to a list without over writing and to display the same in C#?

I have developed code for an Employee class with employee number, name, doj, designation and salary. I want to add these data's of an employee to a list. But when I am trying to do this, the details of the previous employee's are over written by the later and also it displays the details two times. And also I want to view all the employee's details starts with a particular character. How can I do that? here is my code.
MY CODE::
class Program
{
static void Main(string[] args)
{
int option;
List<Employee> employee = new List<Employee>();
Employee emp = new Employee();
do
{
Console.WriteLine("Main menu : 1.Add Employee 2.View All employees 3.View by Name");
option = Convert.ToInt32(Console.ReadLine());
switch (option)
{
case 1:
{
string dat;
DateTime date;
Console.WriteLine("enter the Employee number, name, doj, designation");
emp.EmployeeNumber = Convert.ToInt32(Console.ReadLine());
emp.Name = Console.ReadLine();
dat = Console.ReadLine();
if (DateTime.TryParse(dat, out date))
{
emp.DOJ = date;
}
else
{
Console.WriteLine("please provide the valid date format");
}
emp.Designation = Console.ReadLine();
long Salary = emp.calculateSalary();
Console.WriteLine("Salary : {0}", Salary);
employee.Add(emp);
break;
}
case 2:
{
foreach (var k in employee)
{
Console.WriteLine("Employee Id: {0}", k.EmployeeNumber);
Console.WriteLine("Name: {0}", k.Name);
Console.WriteLine("DOJ: {0}", k.DOJ);
Console.WriteLine("designation: {0}", k.Designation);
Console.WriteLine("salary: {0}", k.calculateSalary());
}
break;
}
case 3:
{
Console.WriteLine("enter the char");
string str = Console.ReadLine();
foreach (Employee i in employee)
{
if (i.Name.StartsWith(str))
{
Console.WriteLine(" Name: {0} \n Id:: {1} \n DOJ: {2} \n desig: {3} \n Salary: {4}", emp.Name, emp.EmployeeNumber, emp.DOJ, emp.Designation, emp.calculateSalary());
}
}
break;
}
}
} while (option != 4);
Console.ReadLine();
}
}
}
class Employee
{
int employeenumber;
string name;
DateTime doj;
string designation;
DateTime tod;
int Exp;
long salary;
public int EmployeeNumber
{
get { return employeenumber; }
set { employeenumber = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public DateTime DOJ
{
get { return doj; }
set { doj = value; }
}
public string Designation
{
get { return designation; }
set { designation = value; }
}
List<Employee> employee = new List<Employee>();
public long calculateSalary()
{
tod = DateTime.Today;
if (DOJ <= tod)
{
int y1 = DOJ.Year;
int y2 = tod.Year;
Exp = y2 - y1;
Console.WriteLine("exp: {0}", Exp);
salary = 200000;
if ((Exp >= 0) && (Exp < 1))
{
salary = 200000;
}
for (int i = 1; i <= Exp; i++)
{
salary = salary + 50000;
}
}
return salary;
}
}
This should work for you. First, in option one you should have been creating a new employee every time, instead of once outside of the loop and second in option 3 you were not referencing the employee from the loop, but the one(same) employee that you created before the do while loop, which would give you the same person every time.
List<Employee> employee = new List<Employee>();
do
{
Console.WriteLine("Main menu : 1.Add Employee 2.View All employees 3.View by Name");
option = Convert.ToInt32(Console.ReadLine());
switch (option)
{
case 1:
{
Employee emp = new Employee();
String date;
Console.WriteLine("enter the Employee number, name, doj, designation");
emp.EmployeeNumber = Convert.ToInt32(Console.ReadLine());
emp.Name = Console.ReadLine();
date = Console.ReadLine();
DateTime doj = new DateTime();
if (DateTime.TryParse(date, out doj))
{
emp.DOJ = doj;
}
else
{
Console.WriteLine("please provide the valid date format");
}
emp.Designation = Console.ReadLine();
//long Salary = emp.calculateSalary();
//Console.WriteLine("Salary : {0}", Salary);
employee.Add(emp);
break;
}
case 2:
{
foreach (var k in employee)
{
Console.WriteLine("Employee Id: {0}", k.EmployeeNumber);
Console.WriteLine("Name: {0}", k.Name);
Console.WriteLine("DOJ: {0}", k.DOJ);
Console.WriteLine("designation: {0}", k.Designation);
//Console.WriteLine("salary: {0}", k.calculateSalary());
}
break;
}
case 3:
{
Console.WriteLine("enter the char");
string str = Console.ReadLine();
foreach (Employee emp in employee)
{
if (emp.Name.StartsWith(str))
{
Console.WriteLine(" Name: {0} \n Id:: {1} \n DOJ: {2} \n desig: {3}", emp.Name, emp.EmployeeNumber, emp.DOJ, emp.Designation);
}
}
break;
}
}
} while (option != 4);

C# - Difficulty with method involving array

I am creating a program that intakes info for the number of visits on separate days to a centre. I am using an array to keep track of that info, but I also need to create a method that calls up the day with the least number of visits and then displays it in an output.
class ScienceCentreVisitation
{
private string centreName;
private string city;
private decimal ticketPrice;
private string[] visitDate;
private int[] adultVisitors;
private decimal[] totalRevenue;
//constructors
public ScienceCentreVisitation()
{
}
public ScienceCentreVisitation(string cent)
{
centreName = cent;
}
public ScienceCentreVisitation(string cent, string cit, decimal price, string[] date, int[] visit, decimal[] rev)
{
visitDate = new string[date.Length];
adultVisitors = new int[visit.Length];
totalRevenue = new decimal[rev.Length];
Array.Copy(date, 0, visitDate, 0, date.Length);
Array.Copy(visit, 0, adultVisitors, 0, adultVisitors.Length);
Array.Copy(rev, 0, totalRevenue, 0, rev.Length);
centreName = cent;
city = cit;
ticketPrice = price;
}
//properties
public string CentreName
{
get
{
return centreName;
}
set
{
centreName = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public decimal TicketPrice
{
get
{
return ticketPrice;
}
set
{
ticketPrice = value;
}
}
public string[] VisitDate
{
get
{
return visitDate;
}
set
{
visitDate = value;
}
}
public int[] AdultVisitors
{
get
{
return adultVisitors;
}
set
{
adultVisitors = value;
}
}
public decimal[] TotalRevenue
{
get
{
return totalRevenue;
}
set
{
totalRevenue = value;
}
}
//methods
public decimal CalculateTotalRevenue()
{
decimal totalRev;
int cntOfValidEntries;
int total = 0;
foreach (int c in adultVisitors)
total += c;
cntOfValidEntries = TestForZeros();
totalRev = (decimal)total / cntOfValidEntries;
return totalRev;
}
public int TestForZeros()
{
int numberOfTrueVisits = 0;
foreach (int cnt in adultVisitors)
if (cnt != 0)
numberOfTrueVisits++;
return numberOfTrueVisits;
}
public int GetIndexOfLeastVisited()
{
int minVisIndex = 0;
for (int i = 1; i < adultVisitors.Length; i++)
if (adultVisitors[i] < adultVisitors[minVisIndex])
minVisIndex = i;
return minVisIndex;
}
public int GetLeastVisited()
{
return adultVisitors[GetIndexOfLeastVisited()];
}
public string GetDateWithLeastVisited()
{
return visitDate[GetIndexOfLeastVisited()];
}
public int GetIndexOfMostRevenue()
{
int maxRevIndex = 0;
for (int i = 1; i < totalRevenue.Length; i++)
if (totalRevenue[i] > totalRevenue[maxRevIndex])
maxRevIndex = i;
return maxRevIndex;
}
public decimal GetMostRevenue()
{
return totalRevenue[GetIndexOfMostRevenue()];
}
public string GetDateWithMostRevenue()
{
return visitDate[GetIndexOfMostRevenue()];
}
public override string ToString()
{
return "Name of Centre: " + centreName +
"\nCity: " + city +
"\n Price of ticket: " + ticketPrice +
"\nDate of Least One-Day Adult Visitors:\t\t" + GetDateWithLeastVisited() +
"\nNumber of Least One-Day Adult Visitors:\t\t" + GetLeastVisited() +
"\nDate of Most Total Revenue Collected:\t\t" + GetDateWithMostRevenue() +
"\nHighest Total Revenue Collected:\t\t" + GetMostRevenue();
}
}
Other class:
class ScienceCentreApp
{
static void Main(string[] args)
{
string centreName;
string city;
decimal ticketPrice = 0;
int visitorCnt;
string[] dArray = new String[5];
int[] adultVisitors = new int[5];
decimal[] totalRevenue = new decimal[5];
char enterMoreData = 'Y';
ScienceCentreVisitation scv;
do
{
visitorCnt = GetData(out centreName, out city, out ticketPrice, dArray, adultVisitors, totalRevenue);
scv = new ScienceCentreVisitation(centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
Console.Clear();
Console.WriteLine(scv);
Console.Write("\n\n\n\nDo you want to enter more data - " +
"(Enter y or n)? ");
if (char.TryParse(Console.ReadLine(), out enterMoreData) == false)
Console.WriteLine("Invalid data entered - " +
"No recorded for your respones");
} while (enterMoreData == 'y' || enterMoreData == 'y');
Console.ReadKey();
}
public static int GetData(out string centreName, out string city, out decimal ticketPrice, string[] dArray, int[] adultVisitors, decimal[] totalRevenue)
{
int i,
loopCnt;
Console.Clear();
Console.Write("Name of Centre: ");
centreName = Console.ReadLine();
Console.Write("City: ");
city = Console.ReadLine();
Console.Write("Ticket Price: ");
string inValue = Console.ReadLine();
ticketPrice = Convert.ToDecimal(inValue);
Console.Write("How many records for {0}? ", centreName);
string inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out loopCnt) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for number of records");
for (i = 0; i < loopCnt; i++)
{
Console.Write("\nDate (mm/dd/yyyy): ");
dArray[i] = Console.ReadLine();
if (dArray[i] == "")
{
Console.WriteLine("No date entered - " +
"Unknown recorded for visits");
dArray[i] = "Unknown";
}
Console.Write("Number of One-Day Adult Visitors: ");
inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out adultVisitors[i]) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for adults visited");
}
return i;
}
}
I had it working before I made some changes to my program, but now it keeps coming up blank when I run it. Any idea why?
Without having the complete code it's difficult to debug this for you.
But here's a suggestion that came up when I was reading the start of your question:
It seems like the basic gist would be to use a Dictionary<DateTime, int> which would store the number of visits for each day.
Then you can use a simple LINQ query to get the smallest value:
dictionary.OrderBy(kvp => kvp.Value).First()
Of course, you can use a complex class in place of the int and store more data (location, price of admission for that day, adult visits, etc.).
class CenterVisitations
{
internal int Visitations { get; set; }
internal decimal TicketPrice { get; set; }
internal string Location { get; set; }
//add other stuff here, possibly create another class
//to store TicketPrice, Location and other static center data
//and create a reference to that here, instead of the above
//TicketPrice and Location...
}
Then you can define your dictionary like so:
Dictionary<DateTime, CenterVisitations>
And query it almost the same was as last time:
dictionary.Order(kvp => kvp.Value.Visitations).First();
Sorting and selecting would work the same way. Additionally you could add a .Where query to set a range of dates which you want to check:
dictionary.Where(kvp => kvp.Key < DateTime.Today && kvp.Key > DateTime.Today.AddDays(-7)) will only look for the last weeks worth of data.
It also seems you're keeping your data in separate arrays, which means querying it is that much harder. Finally, consider converting dates into DateTime objects rather than strings.

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

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

Sorting array in ascending order error

My code below works fine but what I want to do is to display the summary in ascending order according to its OrderNum. I tried to put Array.Sort(order[x].OrderNum) but error cannot convert from int to System.Array. Any suggestions on how I can sort this? Thank you very much!
using System;
class ShippedOrder
{
public static void Main()
{
Order[] order = new Order[5];
int x, y;
double grandTotal = 0;
bool goodNum;
for (x = 0; x < order.Length; ++x)
{
order[x] = new Order();
Console.Write("Enter order number: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("Sorry, the order number " + order[x].OrderNum + " is a duplicate. " + "\nPlease re-enter: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y > x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
}
Console.Write("Enter customer name: ");
order[x].Customer = Console.ReadLine();
Console.Write("Enter Quantity: ");
order[x].Quantity = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\nSummary:\n");
for (x = 0; x < order.Length; ++x)
{
Array.Sort(order[x].OrderNum); //This line is where the error is located
Console.WriteLine(order[x].ToString());
grandTotal += order[x].Total;
}
Console.WriteLine("\nTotal for all orders is Php" + grandTotal.ToString("0.00"));
Console.Read();
}
public class Order
{
public int orderNum;
public string cusName;
public int quantity;
public double total;
public const double ItemPrice = 19.95;
public Order() { }
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
public int OrderNum
{
get { return orderNum; }
set { orderNum = value; }
}
public string Customer
{
get { return cusName; }
set { cusName = value; }
}
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
total = quantity * ItemPrice + 4;
}
}
public double Total
{
get
{
return total;
}
}
public override string ToString()
{
return ("ShippedOrder " + OrderNum + " " + Customer + " " + Quantity +
" #Php" + ItemPrice.ToString("0.00") + " each. " + "Shipping is Php4.00\n" + " The total is Php" + Total.ToString("0.00"));
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (OrderNum == temp.OrderNum)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return OrderNum;
}
}
}
Just use Linq:
order = order.OrderBy(x => x.OrderNum).ToArray();
While looking this link, found that Array.Sort will not take integer as parameter.
You have to pass all the data as Array object.
Try the following:
order.Sort( delegate (Order o1, Order o2) {
return o1.OrderNum.CompareTo(o2.OrderNum);
});

Categories