I need help in appeding the string to path. The problem here is that the path that i have declare cannot be call, instead it just give normal string value. here is my code.
public static string inputhistory1 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\" + Process.GetCurrentProcess().ProcessName + DateTime.Now.ToString("yyyyMMdd")+".chf";
public static string inputhistory2 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-1).ToString("yyyyMM") + ".chf";
public static string inputhistory3 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-2).ToString("yyyyMM") + ".chf";
public static string inputhistory4 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-3).ToString("yyyyMM") + ".chf";
public static bool checkfile(string filename)
{
bool same = false;
for (i = 1; i <= 4; i++)
{
string filechf = "inputhistory" + i;
filechf = filechf;
try
{
foreach (string line in System.IO.File.ReadAllLines(filechf))
{
if (line.Contains(filename))
{
same = true;
break;
}
else
{
same = false;
}
}
}
catch (Exception)
{
// Ignore if file does not exist.
}
if (same == true)
{
break;
}
}
}
Just to show off the expressiveness of LINQ, and the power of leveraging the tools available:
List<string> inputHistories = new List<string>
{
inputhistory1, inputhistory2, inputhistory3, inputhistory4
};
public static bool checkfile(string filename)
{
return inputHistories.Any(filename =>
File.ReadLines(filename).Any(line => line.Contains(filename)));
}
That is because you assign variable filechf with string "inputhistory" + i.
Use an array or list to store input history value.
public static string inputhistory1 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\" + Process.GetCurrentProcess().ProcessName + DateTime.Now.ToString("yyyyMMdd")+".chf";
public static string inputhistory2 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-1).ToString("yyyyMM") + ".chf";
public static string inputhistory3 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-2).ToString("yyyyMM") + ".chf";
public static string inputhistory4 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-3).ToString("yyyyMM") + ".chf";
List<string> inputHistories = new List<string>();
inputHistories.Add(inputhistory1);
inputHistories.Add(inputhistory2);
inputHistories.Add(inputhistory3);
inputHistories.Add(inputhistory4);
Then you could access its value by index:
public static bool checkfile(string filename)
{
bool same = false;
//try
//{
for (i = 0; i < inputHistories.Count; i++)
{
string filechf = inputHistories[i];
try
{
foreach (string line in System.IO.File.ReadAllLines(filechf))
{
if (line.Contains(filename))
{
same = true;
break;
}
else
{
same = false;
}
}
}
catch (Exception)
{
//ignore if file does not exist
}
if (same == true)
{
break;
}
}
There are kinds of solutions may meet your requirements
you can store the variables in a dictionary:
var dictionary = new Dictionary<string,string>();
dictionary.Add("inputhistory1", inputhistory1);
dictionary.Add("inputhistory2", inputhistory2);
dictionary.Add("inputhistory3", inputhistory3);
dictionary.Add("inputhistory4", inputhistory4);
//use as below
Console.WriteLine(dictionary["inputhistory1"]);
or you can use reflection, for more information MSDN:
public class TestClass
{
public static string inputhistory1 = "value1";
public static string inputhistory2 = "value2";
public static string inputhistory3 = "value3";
public static string inputhistory4 = "value4";
}
var obj = new TestClass();
var field = typeof (TestClass).GetField("inputhistory1");
//use as below
Console.WriteLine(field.GetValue(obj));
even you can use switch/case to return your variable value
Related
I have seen examples (and official ones) for IEnumerator on lists and arrays or dicts, but I have a different problem. I have classes with properties, how may I implement the IEnumerable and IEnumerator in that case?
My properties classes are:
public class standardMessage
{
public messageProperties message { get; set; }
public messageFlag flag { get; set; }
}
public class messageProperties
{
public string messageSubject { get; set; }
public string messageBody { get; set; }
}
public class messageFlag
{
public Boolean flagImportant { get; set; }
public Boolean flagPersonal { get; set; }
}
And this is the Program:
public class Program
{
static void Main(string[] args)
{
standardMessage myMessage = new standardMessage();
myMessage.message = new messageProperties
{
messageSubject = "Greetings",
messageBody = "Happy Weekend"
};
myMessage.flag = new messageFlag
{
flagImportant = false,
flagPersonal = true
};
//how do I iterate through all properties, without knowing how many are there, instead of writing this worm line of code?
Console.WriteLine(myMessage.message.messageSubject.ToString() + "\r\n" + myMessage.message.messageBody.ToString() + "\r\n" + myMessage.flag.flagImportant.ToString() + "\r\n" + myMessage.flag.flagPersonal.ToString());
Console.ReadLine();
}
}
If you want a production-grade way of printing your objects as a formatted string, you need to go and override ToString in all your classes to return whatever format you want.
However, if you just want to print the things on screen for debugging or logging purposes, why not JSON?
public static string ToJson(object #object) =>
System.Text.Json.JsonSerializer.Serialize(#object, new JsonSerializerOptions{WriteIndented = true});
Console.WriteLine(ToJson(myMessage));
Prints
{
"message": {
"messageSubject": "Greetings",
"messageBody": "Happy Weekend"
},
"flag": {
"flagImportant": false,
"flagPersonal": true
}
}
Quick and dirty, but quick and working.
I made a very primitive object to json converter. I wouldn't use this in production and it's about 30% slower than Newtonsoft but it get's the job done.
private static string PrintObject(object obj, int depth = 1)
{
var type = obj.GetType();
if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String))
return "\"" + obj.ToString() + "\"";
var props = type.GetProperties();
string ret = "";
for (var i = 0; i < props.Length; i++)
{
var val = props[i].GetValue(obj);
ret += new string('\t', depth) + "\"" + props[i].Name + "\":" + PrintObject(val, depth + 1);
if (i != props.Length - 1)
ret += "," + Environment.NewLine;
}
return ("{" + Environment.NewLine + ret + Environment.NewLine + new string('\t', depth - 1) + "}").Replace("\t", " ");
}
Gives the result
{
"message":{
"messageSubject":"Greetings",
"messageBody":"Happy Weekend"
},
"flag":{
"flagImportant":"False",
"flagPersonal":"True"
}
}
This question already has answers here:
How to get the list of properties of a class?
(11 answers)
Closed 8 years ago.
I have a class
class ABC
{
Public int one = 10;
Public String two = "123";
public override string ToString()
{
}
}
My question i want to get fields information/values in String of Class "ABC" when ever i will create an object of that class. For example:
Public Class Test
{
public static void Main()
{
ABC a = new ABC();
a.ToString();
}
}
Now here I create an object a of class "ABC", then i want to override method of ToString() to get all fields values of class ABC in a string.
As solution this worked for me :
**Here is an other solution if we use static fields and fieldsInfo:**
class ReflectionTest
{
public static int Height = 2;
public static int Width = 10;
public static int Weight = 12;
public static string Name = "Got It";
public override string ToString()
{
string result = string.Empty;
Type type = typeof(ReflectionTest);
FieldInfo[] fields = type.GetFields();
foreach (var field in fields)
{
string name = field.Name;
object temp = field.GetValue(null);
result += "Name:" + name + ":" + temp.ToString() + System.Environment.NewLine;
}
return result;
}
}
public override string ToString()
{
Dictionary<string, string> fieldValues = new Dictionary<string, string>();
var fields = this.GetType().GetFields();
foreach (var field in fields)
{
fieldValues[field.Name] = field.GetValue(this).ToString();
}
return string.Join(", ", fieldValues.Select(x => string.Format("{0}: {1}", x.Key, x.Value)));
}
You could either use a property to retrieve the string, or override ToString(), both are shown:
public class ABC
{
private Int32 _one = 10;
public Int32 One { get { return _one; } }
private String _two = "123";
public String Two { get { return _two; } }
protected override ToString()
{
return _two;
}
}
not sure if this is what you mean;
public override ToString()
{
return string.Format("one: {1}{0}two: {2}", Environment.NewLine(), one, two);
}
So, here it is:
public class ABC
{
public int one;
public string two;
public int three;
public override string ToString()
{
string names = String.Empty;
System.Reflection.FieldInfo[] infos = this.GetType().GetFields();
foreach (System.Reflection.MemberInfo inf in infos)
{
if (names == String.Empty)
{
names = inf.Name;
}
else
{
names += ';' + inf.Name;
}
}
return names;
}
}
Enjoy!
This should do it:
public override string ToString() {
string s = "";
foreach(FieldInfo f in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)) {
s += f.Name + "=" + f.GetValue(this).ToString() + "\r\n";
}
return s;
}
BindingFlags.Public reflects only public members. If you want private member too, use also the BindingFlags.Private flag.
You may use the this.GetType().GetFields() at object initialization, to call it only once.
This works for framework 2 also.
Change it to your needs.
Instead of using Reflection, you can use any of the following two approaches:
1: Here you can serialize your class object to a JSON object which would be more readable:
public override string ToString()
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ABC));
string str;
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, this);
stream.Position = 0;
using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
{
str = streamReader.ReadToEnd();
}
}
return str;
}
2: Here you can serialize your class object to XML which can be utilize some where else:
public override string ToString()
{
XmlSerializer s = new XmlSerializer(typeof(ABC));
StringBuilder sb = new StringBuilder();
var xtw = XmlTextWriter.Create(sb);
s.Serialize
(xtw, this);
return sb.ToString();
}
Finally Get solution to my problem :)
using System;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
MyClass mC= new MyClass();
string result = mC.ToString();
}
}
class MyClass
{
string someValue = "One";
int someValue1 = -1;
bool someValue2 = false;
float someValue3 = 2.2f;
public string SomeValue
{
get{ return this.someValue;}
}
public int SomeValue1
{
get { return this.someValue1; }
}
public bool SomeValue2
{
get { return this.someValue2; }
}
public float SomeValue3
{
get { return this.someValue3; }
}
public override string ToString()
{
string result = string.Empty;
Type type = this.GetType();
PropertyInfo [] pInfo = type.GetProperties();
for (int i = 0; i <= pInfo.Length-1; i++)
{
Type internalType = this.GetType();
PropertyInfo pInfoObject = internalType.GetProperty(pInfo[i].Name);
object value = pInfoObject.GetValue(this,null);
result += pInfo[i].Name + " : " + value.ToString() + System.Environment.NewLine;
}
return result;
}
}
Here is an other solution if we use static fields and fieldsInfo:
class ReflectionTest
{
public static int Height = 2;
public static int Width = 10;
public static int Weight = 12;
public static string Name = "Got It";
public override string ToString()
{
string result = string.Empty;
Type type = typeof(ReflectionTest);
FieldInfo[] fields = type.GetFields();
foreach (var field in fields)
{
string name = field.Name;
object temp = field.GetValue(null);
result += "Name:" + name + ":" + temp.ToString() + System.Environment.NewLine;
}
return result;
}
}
I am getting a List of below class.
public class SmsResponse
{
public string AliasName { get; set; }
public string CellPhoneNumber { get; set; }
public int Response { get; set; }
}
I am passing this list to a function to check if the response field has response other than 0 , if it have than it is a error for which i have to prepare a status string by this method PrepareStatusString();.
bool isSuccess = EvaluateSmsResponse(responseList); //list of smsresponse class
private bool EvaluateSmsResponse(List<SmsResponse> smsResponseList)
{
bool isSent = smsResponseList.Exists(response => response.Response != 0);
if (!isSent)
PrepareStatusString(smsResponseList);
return isSent;
}
private void PrepareStatusString(List<SmsResponse> responseList)
{
bool isfirst = true;
foreach (var item in responseList)
{
if (item.Response != 0)
{
if(isfirst)
StatusDescription += item.AliasName + "|" + item.CellPhoneNumber + "|" + item.Response.ToString();
else
StatusDescription += "," + item.AliasName + "|" + item.CellPhoneNumber + "|" + item.Response.ToString();
isfirst = false;
}
}
}
The code is working as desired, but can it be optimized/improved in any way. I am feeling there is a scope improvement but not able to figure out ??
If you're using .NET 4 or newer, you can override SmsResponse.ToString() and then use String.Join<T>(String, IEnumerable<T>) to concatenate the responses.
So your SmsResponse class may look something like this:
public class SmsResponse
{
public string AliasName { get; set; }
public string CellPhoneNumber { get; set; }
public int Response { get; set; }
public override string ToString()
{
return AliasName + "|" + CellPhoneNumber + "|" +
Response.ToString();
}
}
And PrepareStatusString would be:
private void PrepareStatusString(List<SmsResponse> responseList)
{
StatusDescription = string.Join(",", responseList.Where(i => i.Response != 0));
}
StringBuilder will be more efficient at appending strings within the foreach loop (depending on num of iterations)
private void PrepareStatusString(List<SmsResponse> responseList)
{
bool isfirst = true;
StringBulder sb = new StringBuilder();
foreach (var item in responseList)
{
if (item.Response != 0)
{
if(isfirst)
sb.AppendFormat("{0}|{1}|{2}", item.AliasName, item.CellPhoneNumber,item.Response.ToString());
else
sb.AppendFormat(",{0}|{1}|{2}", item.AliasName, item.CellPhoneNumber, item.Response.ToString());
isfirst = false;
}
}
StatusDescription = sb.ToString();
}
I don't know about optimization, but it could be rewritten more expressively as follows:
private void PrepareStatusString(List<SmsResponse> responseList)
{
StatusDescription = responseList
.Where(x => x.Response != 0)
.Select(x => x.AliasName
+ "|" + x.CellPhoneNumber
+ "|" + x.Response.ToString())
.Aggregate((x, y) => x + "," + y);
}
Note that StringBuilder will only offer a noticeable performance benefit if you expect more than a couple hundred objects there.
Use string.Join like so
List<string> elements = new List<string>();
foreach (var item in responseList)
{
if (item.Response != 0)
{
elements.add(item.AliasName + "|" + item.CellPhoneNumber + "|" + item.Response.ToString());
}
}
string result = string.Join(",", elements.ToArray());
I have a requirement, in it I have to do the following things:
Generate code dynamically
Write the code into an existing .cs file
I have to add the code just before the last two braces of the class file.
For e.g. the class file is :
namespace Stackoverflow
{
public class AskQuestion
{
public void Ask()
{
}
//Add the generated code here.
}
}
I tried following code :
Created a class FindBraceLocation
namespace DBInfo.Class
{
public class FindBraceLocation
{
private int _bracePositionInLine;
private int _noOfBraceFound;
private int _lineNoIndex;
private readonly string[] _fs;
public int LineNoIndex
{
get { return _lineNoIndex; }
set { _lineNoIndex = value; }
}
public int BracePositionInLine
{
get { return _bracePositionInLine; }
set { _bracePositionInLine = value; }
}
public int NoOfBraceFound
{
get { return _noOfBraceFound; }
set { _noOfBraceFound = value; }
}
public FindBraceLocation(string[] allLines)
{
_bracePositionInLine = -1;
_noOfBraceFound = 0;
_lineNoIndex = 0;
_fs = allLines;
}
public void SearchFileStringIndex()
{
int noOfLines = _fs.Length;
string line;
int lineCounter;
int pos2 = -1;
for (lineCounter = noOfLines - 1; lineCounter >= 0; lineCounter--)
{
line = _fs[lineCounter];
if (line.Trim().Length == 0)
{
continue;
}
pos2 = FindIndexOfBrace(line);
if (pos2 != -1)
break;
}
_lineNoIndex = lineCounter;
_bracePositionInLine = pos2;
}
public int FindIndexOfBrace(string line)
{
//int braceNo = _noOfBraceFound;
for (int counter = line.Length - 1; counter >= 0; counter--)
{
if (line[counter] == '}' && (++_noOfBraceFound == 2))
{
return counter;
}
}
return -1;
}
}
}
And used the following method to write it into a file :
protected void WriteToExistingGeneratedFile(string strInfo, string strPath)
{
string[] allLines = File.ReadAllLines(strPath);
FindBraceLocation fp = new FindBraceLocation(allLines);
fp.SearchFileStringIndex();
string lineForInsertion = allLines[fp.LineNoIndex];
string tempLine = lineForInsertion.Substring(0, fp.BracePositionInLine) + "\n" + strInfo + "\n" + lineForInsertion.Substring(fp.BracePositionInLine);
allLines[fp.LineNoIndex] = tempLine;
File.WriteAllLines(strPath, allLines);
}
Instead of modifying the existing file, dynamically generate a second file and use the partial keyword to add new members to the class.
Static file:
namespace Stackoverflow
{
public partial class AskQuestion
{
public void Ask()
{
}
}
}
Generated file:
namespace Stackoverflow
{
partial class AskQuestion
{
// Dynamically generated methods and properties
}
}
If you use a stream reader you can use the normal string functions on it. Something like this would work:
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.cs");
string myString = myFile.ReadToEnd();
// This will error if there are not at least 2 parentheses.
string UpToLastParan = myString.Text.Substring(0, myString.LastIndexOf("}"));
int SecondToLast = UpToLastParan.LastIndexOf("}");
string UpToSecondToLastParan = myString.Substring(0, SecondToLast);
string CorrectedString = UpToSecondToLastParan + "Your Code Here" + myString.Substring(SecondToLast, myString.Length - SecondToLast);
// Write back to 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.