/*********************************************************

BugBank-workingSrc.js : copyright 2001, Essam Ahmed

This sample is from the book JScript.NET Programming (2001)
by Essam Ahmed

*********************************************************/

import System;
import System.Drawing;
import System.ComponentModel;
import System.Windows.Forms;
import System.Diagnostics;
import System.Data;
import System.Data.Common;
import System.Data.OleDb;
import System.Collections;
import System.Text;
import System.IO;

package Win32Form1Namespace {

	
	
	public class exNSF extends localEx {
		public function exNSF(s:String) {
			super(s);
		}
	}
	
	public class localEx extends Exception {
		public function localEx(s:String) {
			super(s);
		}
	}
    
    public class Win32Form1 extends System.Windows.Forms.Form {
		static function  Error(s:String) :void
		{
			throw new localEx(s);
		}
		
        private var isValidCust : Boolean ;
        private var isConnected : Boolean=true ;
        private var currentCustId : String ;
        private var label1 : System.Windows.Forms.Label;
        
        private var label2 : System.Windows.Forms.Label;
        
        private var dgCustInfo : System.Windows.Forms.DataGrid;
        
        private var label3 : System.Windows.Forms.Label;
        
        private var listAccounts : System.Windows.Forms.ListBox;
        
        private var label4 : System.Windows.Forms.Label;
        
        private var txtCustId : System.Windows.Forms.TextBox;
        
        private var groupBox1 : System.Windows.Forms.GroupBox;
        
        private var rdoDeposit : System.Windows.Forms.RadioButton;
        
        private var rdoWithdraw : System.Windows.Forms.RadioButton;
        
        private var txtAmount : System.Windows.Forms.TextBox;
        
        private var label5 : System.Windows.Forms.Label;
        
        private var btnCommit : System.Windows.Forms.Button;
        
        private var btnClear : System.Windows.Forms.Button;
        
        private var btnInquire : System.Windows.Forms.Button;
        
        private var label6 : System.Windows.Forms.Label;
        
        private var lblBalance : System.Windows.Forms.Label;
        
        private var components : System.ComponentModel.IContainer=null;
        
        var accounts : custAccounts;
        var bbDatabase : Database;
        static var generalTrace:TraceSwitch=new TraceSwitch("general","general sw");
        
        public function Win32Form1() {
			Trace.Listeners.Add(new TextWriterTraceListener(File.Create("output.txt")));
            isValidCust=false;
            this.InitializeComponent();
            
        }
         
        public static System.STAThreadAttribute() function Main() {
            System.Windows.Forms.Application.Run(new Win32Form1());
        }
        
        private function InitializeComponent() {
            this.rdoWithdraw = new System.Windows.Forms.RadioButton();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.btnClear = new System.Windows.Forms.Button();
            this.txtCustId = new System.Windows.Forms.TextBox();
            this.rdoDeposit = new System.Windows.Forms.RadioButton();
            this.btnCommit = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.label5 = new System.Windows.Forms.Label();
            this.listAccounts = new System.Windows.Forms.ListBox();
            this.btnInquire = new System.Windows.Forms.Button();
            this.label4 = new System.Windows.Forms.Label();
            this.txtAmount = new System.Windows.Forms.TextBox();
            this.dgCustInfo = new System.Windows.Forms.DataGrid();
            this.label6 = new System.Windows.Forms.Label();
            this.lblBalance = new System.Windows.Forms.Label();
            this.groupBox1.SuspendLayout();
            System.ComponentModel.ISupportInitialize(this.dgCustInfo).BeginInit();
            this.dgCustInfo.SuspendLayout();
            this.SuspendLayout();
            // 
            // rdoWithdraw
            // 
            this.rdoWithdraw.Location = new System.Drawing.Point(16, 64);
            this.rdoWithdraw.Name = "rdoWithdraw";
            this.rdoWithdraw.Size = new System.Drawing.Size(120, 24);
            this.rdoWithdraw.TabIndex = 1;
            this.rdoWithdraw.Text = "Withdraw";
            // 
            // label1
            // 
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", float(21.75), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, byte(0));
            this.label1.Location = new System.Drawing.Point(168, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(136, 40);
            this.label1.TabIndex = 0;
            this.label1.Text = "BugBank";
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(16, 32);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(120, 23);
            this.label2.TabIndex = 1;
            this.label2.Text = "Customer ID#:";
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(16, 104);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(120, 23);
            this.label3.TabIndex = 4;
            this.label3.Text = "Customer Info:";
            // 
            // btnClear
            // 
            this.btnClear.Location = new System.Drawing.Point(344, 384);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(88, 32);
            this.btnClear.TabIndex = 11;
            this.btnClear.Text = "Clear";
            // 
            // txtCustId
            // 
            this.txtCustId.Location = new System.Drawing.Point(16, 64);
            this.txtCustId.MaxLength = 5;
            this.txtCustId.Name = "txtCustId";
            this.txtCustId.TabIndex = 2;
            this.txtCustId.Text = "5556";
            // 
            // rdoDeposit
            // 
            this.rdoDeposit.Checked = true;
            this.rdoDeposit.Location = new System.Drawing.Point(16, 32);
            this.rdoDeposit.Name = "rdoDeposit";
            this.rdoDeposit.Size = new System.Drawing.Size(120, 24);
            this.rdoDeposit.TabIndex = 0;
            this.rdoDeposit.TabStop = true;
            this.rdoDeposit.Text = "Deposit";
            // 
            // btnCommit
            // 
            this.btnCommit.Location = new System.Drawing.Point(344, 336);
            this.btnCommit.Name = "btnCommit";
            this.btnCommit.Size = new System.Drawing.Size(88, 32);
            this.btnCommit.TabIndex = 10;
            this.btnCommit.Text = "Commit";
            this.btnCommit.add_Click(doCommit);
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.AddRange([this.rdoWithdraw, this.rdoDeposit]);
            this.groupBox1.Location = new System.Drawing.Point(24, 312);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(144, 100);
            this.groupBox1.TabIndex = 7;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Transaction";
            // 
            // label5
            // 
            this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", float(12), System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, byte(0));
            this.label5.Location = new System.Drawing.Point(232, 352);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(72, 24);
            this.label5.TabIndex = 9;
            this.label5.Text = "Amount";
            // 
            // listAccounts
            // 
            this.listAccounts.ColumnWidth = 3;
            this.listAccounts.HorizontalScrollbar = true;
            this.listAccounts.ItemHeight = 20;
            this.listAccounts.Location = new System.Drawing.Point(136, 240);
            this.listAccounts.MultiColumn = false;
            this.listAccounts.Name = "listAccounts";
            this.listAccounts.Size = new System.Drawing.Size(176, 64);
            this.listAccounts.TabIndex = 5;
            this.listAccounts.add_SelectedIndexChanged(handleAccountChanged);
            // 
            // btnInquire
            // 
            this.btnInquire.Font = new System.Drawing.Font("Microsoft Sans Serif", float(8.25), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, byte(0));
            this.btnInquire.Location = new System.Drawing.Point(128, 64);
            this.btnInquire.Name = "btnInquire";
            this.btnInquire.Size = new System.Drawing.Size(56, 23);
            this.btnInquire.TabIndex = 12;
            this.btnInquire.Text = "Inquire";
            this.btnInquire.add_Click(doInquire);
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(136, 216);
            this.label4.Name = "label4";
            this.label4.TabIndex = 6;
            this.label4.Text = "Accounts";
            // 
            // txtAmount
            // 
            this.txtAmount.Location = new System.Drawing.Point(176, 384);
            this.txtAmount.MaxLength = 7;
            this.txtAmount.Name = "txtAmount";
            this.txtAmount.Size = new System.Drawing.Size(120, 26);
            this.txtAmount.TabIndex = 8;
            this.txtAmount.Text = "0";
            this.txtAmount.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            // 
            // dgCustInfo
            // 
            this.dgCustInfo.DataMember = "";
            this.dgCustInfo.Location = new System.Drawing.Point(16, 128);
            this.dgCustInfo.Name = "dgCustInfo";
            this.dgCustInfo.Size = new System.Drawing.Size(416, 80);
            this.dgCustInfo.TabIndex = 3;
            // 
            // label6
            // 
            this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", float(12), System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, byte(0));
            this.label6.Location = new System.Drawing.Point(328, 248);
            this.label6.Name = "label6";
            this.label6.TabIndex = 13;
            this.label6.Text = "Balance:";
            // 
            // lblBalance
            // 
            this.lblBalance.Location = new System.Drawing.Point(328, 280);
            this.lblBalance.Name = "lblBalance";
            this.lblBalance.TabIndex = 14;
            this.lblBalance.Text = "0";
            this.lblBalance.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // Win32Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(8, 19);
            this.ClientSize = new System.Drawing.Size(464, 429);
            this.Controls.AddRange([this.lblBalance, this.label6, this.btnInquire, this.btnClear, this.btnCommit, this.label5, this.txtAmount, this.groupBox1, this.label4, this.listAccounts, this.label3, this.dgCustInfo, this.txtCustId, this.label2, this.label1]);
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", float(12), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, byte(0));
            this.Name = "Win32Form1";
            this.Text = "BugBank Sample App";
            this.StartPosition=FormStartPosition.CenterScreen;
            this.groupBox1.ResumeLayout(false);
            System.ComponentModel.ISupportInitialize(this.dgCustInfo).EndInit();
            this.dgCustInfo.ResumeLayout(false);
            this.ResumeLayout(false);
            this.add_Closing(handleFormClose);
            clearForm();
            bbDatabase = new Database();
        /*    
            try {
  	            bbDatabase = new Database();
  	        }
  	        catch (e:localEx)
  	        {
  				MessageBox.Show(e.Message);
  				Trace.WriteLine("Database not open - please check!");
  				isConnected=false;
  			}
  		*/	
        }

		private function handleFormClose(obj : Object, eArgs : System.ComponentModel.CancelEventArgs){
			Trace.WriteLineIf(generalTrace.TraceVerbose,"Exit");
			Trace.Close();
		}


		private function doCommit(obj : Object, eArgs : EventArgs){        
			try {
				Double.Parse(txtAmount.Text);
			}
			catch(e:FormatException)
			{
				MessageBox.Show("Please use only numbers for the Amount");
				return;
			}
			
			if (Double.Parse(txtAmount.Text) <= 0 ) {
				MessageBox.Show("Invalid Amount\n\nUse only non-zero, positive values");
				return
			}
			var transAmount=Double.Parse(txtAmount.Text);
			try {
				new transaction(bbDatabase).commit(rdoDeposit.Checked,transAmount,
						accounts.Item(listAccounts.SelectedItems[0].ToString()));
			}
			catch (e:exNSF)
			{
				Trace.WriteLineIf(generalTrace.TraceVerbose,"Attempt to "+(rdoDeposit.Checked ? "Deposit " : "Withdraw ")+transAmount.ToString()+" for "+listAccounts.SelectedItems[0].ToString()+" FAILED");
				MessageBox.Show(e.Message);
				return;
			}
			Trace.WriteLineIf(generalTrace.TraceVerbose,(rdoDeposit.Checked ? "Deposit" : "Withdraw")+" ["+listAccounts.SelectedItems[0].ToString()+"] " +transAmount.ToString());
			
			doInquire(obj,eArgs);
		}

		private function doInquire(obj : Object, eArgs : EventArgs){        
		
			Trace.Assert(txtCustId.Text!="1111", "Test assertion fired - you entered 1111 in the Customer ID field");
			if(!(isConnected)) {
				MessageBox.Show("The Bank System is not available");
				return;
			}
				
			var ds : DataSet;
			
			clearForm();		
			try {
				Int32.Parse(txtCustId.Text);
			}
			catch(e:FormatException)
			{
				MessageBox.Show("Please use only numbers for the Customer Numbers");
				return;
			}
			
			if (Int32.Parse(txtCustId.Text) < 1 ) {
				MessageBox.Show("Invalid Customer Number - please check");
				return;
			}
			currentCustId=txtCustId.Text;
			ds=bbDatabase.queryDS("select * from customers where customerid="+txtCustId.Text);
			if(ds.Tables[0].Rows.Count<1)
			{
				MessageBox.Show("Customer does not exist\n\nPlease check Customer Number");
				return;
			}
			isValidCust=true;
			var  dsv :DataView= new DataView(ds.Tables[0]);
			dgCustInfo.DataSource = dsv;
			var dsAccounts : DataSet;
			dsAccounts=bbDatabase.queryDS("SELECT Accounts.acctID, AccountTypes.atName FROM AccountTypes INNER JOIN Accounts ON AccountTypes.atId = Accounts.acctType where  acctCustId="+txtCustId.Text);
			
			var rr : DataRow;
			accounts = new custAccounts();
			
			for(rr in dsAccounts.Tables[0].Rows)
			{
				accounts.Add(new custAccount(rr[1].ToString(),long.Parse(rr[0].ToString())));
				listAccounts.Items.Add(accounts.Item(rr[1].ToString()).m_type );
			}
			listAccounts.SetSelected(0,true);
			Trace.WriteLineIf(generalTrace.TraceVerbose,"Inquire Account "+currentCustId);
			
		}
		
		private function handleAccountChanged(obj : Object, eArgs : EventArgs){        
			
			lblBalance.Text=accounts.Item(listAccounts.SelectedItems[0].ToString()).accountBalance.ToString();
			btnCommit.Enabled=isValidCust;

		}
		private function clearForm()
		{
			dgCustInfo.AllowNavigation=false;
			var ds2 : DataSet = new DataSet();
			ds2.Tables.Add("empty");
			var  dsv2 :DataView= new DataView(ds2.Tables[0]);
			dgCustInfo.DataSource = dsv2;
			listAccounts.Items.Clear();
			rdoDeposit.Checked=true;
			txtAmount.Text=0;
			lblBalance.Text=0;
			isValidCust=false;
			btnCommit.Enabled=false;
			currentCustId="0";
		}
		

    } // class
    
    
	class Database {


		private var m_cmd : OleDbCommand;
		private var m_ds : DataSet;		
		private var m_conn : OleDbConnection;
		private var m_connectionString : String;

		function Database()
		{
//			try {
				// fixed
				m_connectionString=new String("Provider=Microsoft.JET.OLEDB.4.0;data source=bugbank.mdb");
				//m_connectionString=new String("Provider=Microsoft.JET.OLEDB.4.0;" + 
				//		"data source=bugbank");
				m_conn = new OleDbConnection (m_connectionString);

				m_conn.Open();
				m_cmd = new OleDbCommand();
				m_cmd.Connection=m_conn;
//			}
//			catch (e:Exception)
//			{
//				throw new localEx(e.Message);
//				return;
//			}
			 
		}
    	
		public function set databaseLocation(loc : String) {
			Trace.Assert(loc.Length > 0, "Attempt to set a 0 length connection string");
			m_connectionString=loc;
		}
			
		public function get databaseLocation() : String {
			return m_connectionString;
		}
		public function queryDS(qs:String) : DataSet {
			Trace.Assert(qs.Length > 0, "passed empty parameter to queryDS");
			var lds : DataSet=new DataSet();
			var dataAdapter : OleDbDataAdapter;
			m_cmd.CommandText=qs;
			dataAdapter= new OleDbDataAdapter();
			dataAdapter.SelectCommand =m_cmd;
			dataAdapter.Fill(lds);
			return lds;
		}
		
		public function execCommand(qs:String) : DataSet {
			Trace.Assert(qs.Length > 0, "passed empty parameter to execCommand");
			m_cmd.CommandText=qs;
			m_cmd.ExecuteNonQuery();
			
		}
	}
	

	class transaction {
		private var m_db:Database;
		function transaction(curDb:Database){
			m_db=curDb;
		}
		
		function commit (isDep:Boolean,amnt:double,acct:custAccount)
		{
			var dt : DateTime;
			var txtDate : String;
			//amnt=(isDep ? amnt : -1*amnt);
			if(!isDep && acct.accountBalance-amnt < 0)
				throw new exNSF("Insufficient funds\n\nTransaction cancelled");
			amnt=(isDep ? amnt : -1*amnt);
			dt=DateTime.Now;
			txtDate=dt.ToString("g");
			var cmd="INSERT INTO Transactions ( TransactionDate, TransactionAmount, AccountID ) values(\"" + 
						txtDate + "\"," +  amnt.ToString() + 
						","+ acct.m_number.ToString()+")";
			m_db.execCommand(cmd);
		}
	}

	class custAccounts {
	
		private var ht : Hashtable;
		
		function custAccounts() {
			ht=new Hashtable();
		}
		
		public function Add(acct:custAccount)
		{
			ht.Add(acct.m_type,acct);
		}
		
		public function Item(acctName:String)
		{
			return ht.Item(acctName);
		}
	}

	// add into hashtable...
	class custAccount extends Object {
		
		private var m_bal : double;
		public var m_type : String;
		public var m_number : long;
		
		function custAccount() {
		
		}
		function custAccount(aType:String,aNumber:long) {
			m_bal=0;
			m_type=new String(aType);
			m_number=aNumber;
			calcBalance();
		}
		function get accountBalance() : double {
			return m_bal;
		}
		
		private function calcBalance() {
			var bbDatabase : Database = new Database();
			var ds : DataSet;
			var drow : DataRow;
			ds=bbDatabase.queryDS("SELECT Sum(Transactions.TransactionAmount) AS txSum FROM Transactions where accountId="+m_number.ToString());
			drow=ds.Tables[0].Rows[0];
			if(drow[0])
				m_bal=Double.Parse(drow[0].ToString());
		}
	}
			
			
			
	
}
try {
	Win32Form1Namespace.Win32Form1.Main();
}
catch (e:Win32Form1Namespace.localEx) {
	MessageBox.Show(e.Message);
}

/*
jsc /t:winexe /r:system /r:system.windows.forms.dll /r:system.drawing  /r:System.Data bb.js
*/



    
    

