// CppBinRead.cpp : main project file.

#include "stdafx.h"

using namespace System;
using namespace System::IO;

// The Customer class 
ref class Customer
{
	String^ name;
    long accNo;
    double balance;
public:
    // Constructors
    Customer() : name(nullptr), accNo(0), balance(0.0) {}
    Customer(String^ s, long l, double b) :
        name(s), accNo(l), balance(b) {}

    // Write object data to a BinaryWriter
    void Write(BinaryWriter^ bw)
    {
        bw->Write(name);
        bw->Write(accNo);
        bw->Write(balance);
    }

    // Read object data from a BinaryReader
    void Read(BinaryReader^ br)
    {
        name = br->ReadString();
        accNo = br->ReadInt32();
        balance = br->ReadDouble();
    }

    // Properties to retrieve the instance variables
    property String^ Name
	{
		String^ get() { return name; }
	}
	property long Account
	{
		long get() { return accNo; }
	}
	property double Balance
	{
		double get() { return balance; }
	}
};

int main()
{
    // Get the command line arguments
	array<String^>^args = Environment::GetCommandLineArgs();

	// Check for required arguments
	if (args->Length < 2)
	{
		Console::WriteLine(L"Usage: CppBinRead path");
		return -1;
	}

	// Save the path
	String^ path = gcnew String(args[1]);

	// Create or instantiate some customers objects
	Customer^ c1 = gcnew Customer(L"Mike Smith", 1234567, 600.0);
	Customer^ c2 = gcnew Customer(L"Billy Jones", 2345678, 7000.5);
	Customer^ c3 = gcnew Customer(L"Mark Davies", 3456789, 30000.0);

	try
	{
		// Create a FileStream
		Console::WriteLine("Creating a FileStream object");
		FileStream^ fstrm = gcnew FileStream(path, FileMode::Create,
                                       FileAccess::ReadWrite);
		// Create a BinaryWriter to use the FileStream
		Console::WriteLine("Creating a BinaryWriter...");
		BinaryWriter^ binw = gcnew BinaryWriter(fstrm);

		// Write the customters to the file
		Console::WriteLine("Write the customers to the file...");
		c1->Write(binw);
		c2->Write(binw);
		c3->Write(binw);

		// Create a BinaryReader that reads from the same FileStream
		Console::WriteLine("Creating a BinaryReader that reads from the same FileStream...");
		BinaryReader^ binr = gcnew BinaryReader(fstrm);

		// Move back to the beginning
		Console::WriteLine("Move back to the beginning");
		binr->BaseStream->Seek(0, SeekOrigin::Begin);

		// Create a new customer, and read details from the file
		Console::WriteLine("Creating new customer, and read details from the file:");
		Customer^ c4 = gcnew Customer();
		c4->Read(binr);
		Console::WriteLine(L"\nBalance for {0} (a/c {1}) is {2}", 
          c4->Name,  (Object^)(c4->Account), (Object^)(c4->Balance));
	}
	catch(System::Exception^ pe)
		{
			Console::WriteLine(pe->ToString());
		}

	return 0;
}







