0% found this document useful (0 votes)
5 views

Filesbalance

The document defines classes and methods for serializing and deserializing record data to and from JSON files. It includes classes for representing records, methods for reading/writing files, and event handlers for interacting with the user interface.

Uploaded by

Slime UNICORN
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Filesbalance

The document defines classes and methods for serializing and deserializing record data to and from JSON files. It includes classes for representing records, methods for reading/writing files, and event handlers for interacting with the user interface.

Uploaded by

Slime UNICORN
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

namespace FileExample_01

{
[Serializable]
public class RecordSerializable
{
public int Account { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Balance { get; set; }

// default constructor sets members to default values


public RecordSerializable()
: this(0, string.Empty, string.Empty, 0M) { }

// overloaded constructor sets members to parameter values


public RecordSerializable(int account, string firstName,
string lastName, decimal balance)
{
Account = account;
FirstName = firstName;
LastName = lastName;
Balance = balance;
}
}
}

namespace FileExample_01
{
public class Record
{
public int Account { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Balance { get; set; }

// parameterless constructor sets members to default values


public Record() : this(0, string.Empty, string.Empty, 0M) { }

// overloaded constructor sets members to parameter values


public Record(int account, string firstName,
string lastName, decimal balance)
{
Account = account;
FirstName = firstName;
LastName = lastName;
Balance = balance;
}
}
}

namespace FileExample_01
{
public partial class MainForm : Form
{
//
//openbtn_Click: Handles the click event of the "Open" button.It opens a
file dialog for the user to select a file.If a file is selected, it reads the
contents of the file and enables the "Next Record" button.
//savebtn_Click: Handles the click event of the "Save" button.It opens a
file dialog for the user to specify the file to save the data.If a valid file name
is provided, it enables the "Enter" button to start entering data.
//enterbtn_Click: Handles the click event of the "Enter" button.It
retrieves the values from text boxes, validates them, creates a Record object, and
writes the record to the file.
//exitbtn_Click: Handles the click event of the "Exit" button.It closes the
file writer and exits the application.
//The nextbtn_Click event handler is responsible for displaying the next
record from the file when the "Next Record" button is clicked.
// object for deserializing RecordSerializable in binary format
private FileStream input; // stream for reading from a file
private StreamWriter fileWriter; // writes data to text file
protected int TextBoxCount { get; set; } = 4; // number of TextBoxes

// enumeration constants specify TextBox indices


public enum TextBoxIndices { Account, First, Last, Balance }
public MainForm()
{
InitializeComponent();
}

private void openbtn_Click(object sender, EventArgs e)


{
string account = accounttx.Text;
string fname = fnametx.Text;
string lname = lnametx.Text;
string balance = balancetx.Text;

// Variables for storing user's file selection and dialog result


DialogResult result; // Will hold the result (e.g., OK or Cancel) from
the file dialog
string fileName; // Will store the chosen file's name

// Create and show the file dialog with proper resource management
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
// Display the dialog and capture the user's choice
result = fileChooser.ShowDialog(); // Show the Open File dialog
fileName = fileChooser.FileName; // Get the chosen file's name

// If the user clicked "OK" in the dialog:


if (result == DialogResult.OK)
{
// Prepare for loading new data
ClearTextBoxes(); // Clear any existing text boxes

// Check for valid file selection


if (string.IsNullOrEmpty(fileName)) // If no file was specified
{
MessageBox.Show("Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error); // Show error message
}
else // File is valid, proceed with opening
{
// Create a stream for reading the file
input = new FileStream(fileName, FileMode.Open,
FileAccess.Read); // Open the file for reading

// Adjust button states for file handling


openbtn.Enabled = false; // Disable the Open File button
(presumably to avoid multiple openings)
nextbtn.Enabled = true; // Enable the Next Record button
(presumably for processing file content)
}
}
}

// clear all TextBoxes


public void ClearTextBoxes()
{
// iterate through every Control on form
foreach (Control guiControl in Controls)
{
// if Control is TextBox, clear it
if (guiControl is TextBox textBox)
{
textBox.Clear();
}
}
}

// set text box values to string-array values


public void SetTextBoxValues(string[] values)
{
// determine whether string array has correct length
if (values.Length != TextBoxCount)
{
// throw exception if not correct length
throw new ArgumentException($"There must be {TextBoxCount} strings
in the array", nameof(values));
}

// set array values to TextBox values


accounttx.Text = values[(int)TextBoxIndices.Account];
fnametx.Text = values[(int)TextBoxIndices.First];
lnametx.Text = values[(int)TextBoxIndices.Last];
balancetx.Text = values[(int)TextBoxIndices.Balance];
}
// return TextBox values as string array
public string[] GetTextBoxValues()
{
return new string[] {
this.accounttx.Text, this.fnametx.Text,
this.lnametx.Text, this.balancetx.Text};
}
private void nextbtn_Click(object sender, EventArgs e)
{
try
{
// Deserialize the object using JSON serialization
using (StreamReader fileReader = new StreamReader(input))
{
string json = fileReader.ReadToEnd();
RecordSerializable record =
JsonSerializer.Deserialize<RecordSerializable>(json);
// store RecordSerializable values in temporary string array
var values = new string[] {
record.Account.ToString(),
record.FirstName,
record.LastName,
record.Balance.ToString()
};

// copy string-array values to TextBox values


SetTextBoxValues(values);
}
}
catch (JsonException)
{
input?.Close(); // close FileStream
openbtn.Enabled = true; // enable Open File button
nextbtn.Enabled = false; // disable Next Record button

ClearTextBoxes();

// notify user if there are issues with JSON formatting


MessageBox.Show("Error reading JSON data from file", string.Empty,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (EndOfStreamException)
{
input?.Close(); // close FileStream
openbtn.Enabled = true; // enable Open File button
nextbtn.Enabled = false; // disable Next Record button

ClearTextBoxes();

// notify user if no more records are found in the file


MessageBox.Show("No more records in file", string.Empty,
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

private void savebtn_Click(object sender, EventArgs e)


{
// create and show dialog box enabling user to save file
DialogResult result; // result of SaveFileDialog
string fileName; // name of file containing data

using (var fileChooser = new SaveFileDialog())


{
fileChooser.CheckFileExists = false; // let user create file
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName; // name of file to save data
this.filenamelb.Text = fileName;
}

// ensure that user clicked "OK"


if (result == DialogResult.OK)
{
// show error if user specified invalid file
if (string.IsNullOrEmpty(fileName))
{
MessageBox.Show("Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
// save file via FileStream if user specified valid file
try
{
// open file with write access
var output = new FileStream(fileName,
FileMode.OpenOrCreate, FileAccess.Write);

// sets file to where data is written


fileWriter = new StreamWriter(output);

// disable Save button and enable Enter button


this.savebtn.Enabled = false;
this.enterbtn.Enabled = true;
}
catch (IOException)
{
// notify user if file does not exist
MessageBox.Show("Error opening file", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

private void enterbtn_Click(object sender, EventArgs e)


{
// store TextBox values string array
string[] values = GetTextBoxValues();

// determine whether TextBox account field is empty


if (!string.IsNullOrEmpty(values[(int)TextBoxIndices.Account]))
{
// store TextBox values in Record and output it
try
{
// get account-number value from TextBox
//int accountNumber =
// int.Parse(values[(int)TextBoxIndices.Account]);
int accountNumber =
int.Parse(this.accounttx.Text);
// determine whether accountNumber is valid
if (accountNumber > 0)
{
// Record containing TextBox values to output
//var record = new Record(accountNumber,
//values[(int)TextBoxIndices.First],
//values[(int)TextBoxIndices.Last],
//decimal.Parse(values[(int)TextBoxIndices.Balance]));
var record = new Record(accountNumber,
this.fnametx.Text,
this.lnametx.Text,
decimal.Parse(this.balancetx.Text));
// write Record to file, fields separated by commas
fileWriter.WriteLine(
$"{record.Account},{record.FirstName}," +
$"{record.LastName},{record.Balance}");
}
else
{
// notify user if invalid account number
MessageBox.Show("Invalid Account Number", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (IOException)
{
MessageBox.Show("Error Writing to File", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (FormatException)
{
MessageBox.Show("Invalid Format", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

ClearTextBoxes(); // clear TextBox values

private void exitbtn_Click(object sender, EventArgs e)


{
try
{
fileWriter?.Close(); // close StreamWriter and underlying file
}
catch (IOException)
{
MessageBox.Show("Cannot close file", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Application.Exit();
}
}
}

You might also like