/*****************************************************************************/
/*                                                                           */
/*  Copyright Notice: IBM Personal Communication/3270 Version 5.8            */
/*                    (C) COPYRIGHT IBM CORP. 2004 - PROGRAM PROPERTY        */
/*                    OF IBM ALL RIGHTS RESERVED                             */
/*                                                                           */
/* Changes:                                                                  */
/*                                                                           */
/*                                                                           */
/*****************************************************************************/
// This file contains simple examples which illustrate the usage of emulator class
// libraries in a .NET language.The samples can be run by compiling and executing this program.  
//The program will prompt for a sample number and will run the
// corresponding "SampleX()" function.  All input and output
// is command-line (console).


using System;
using System.Collections;
//Reference ECL types to use
using AutConnMgrTypeLibrary;
using AutConnListTypeLibrary;
using AutOIATypeLibrary;
using AutPSTypeLibrary;
using AutSessTypeLibrary;
using AutWinMetricsTypeLibrary;
using AutXferTypeLibrary;
using AutScreenDescTypeLibrary;
using AutScreenRecoTypeLibrary;

//The namespace is IBM ECL sample
namespace  IBMECLSamples
{
	public class ECLSamplesTester 
	{
		[STAThread]//This attribute is needed as all the PCOMM objects are single threaded apaprtment 
			//objects. If this attribute is not used, the RCW will throw execeptions.
		public static void Main(string[] args)
		{
			
			Console.WriteLine("IBM PCOMM ECL Samples");
			while (true)
			{
				Console.Write("Enter the sample number:");
				UInt32 Choice;
				try 
				{
					Choice = UInt32.Parse(Console.ReadLine());
				}
				catch(Exception )
				{
					Console.WriteLine("Please enter an valid sample number.");
					continue;
				}
				switch(Choice)
				{
					case 0:
						return ;
					case 1:
						ECLSamplesAutConnList.Sample1();  
						break;
					case 2:
						ECLSamplesAutConnList.Sample2();
						break;
					case 3:  
						ECLSamplesAutConnList.Sample3();
						break;
					case 4: 
						ECLSamplesAutConnList.Sample4();   
						break;
					case 5:
						ECLSamplesAutConnMgr.Sample5();
						break;
					case 6:
						ECLSamplesAutConnMgr.Sample6();
						break;
					case 7:
						ECLSamplesAutConnMgr.Sample7();
						break;
					case 8:
						ECLSamplesAutConnMgr.Sample8();
						break;
					case 9:
						ECLSamplesAutSess.Sample9();
						break;
					case 10:
						ECLSamplesAutWinMetrics.Sample10();
						break;
					case 11:
						ECLSamplesAutWinMetrics.Sample11();		
						break;
					case 12:
						ECLSamplesAutWinMetrics.Sample12();		
						break;
					case 13:
						ECLSamplesAutWinMetrics.Sample13();		
						break;
					case 14:
						//	ECLSamplesAutFieldList.Sample14();
						break;
					case 15: 
						ECLSamplesAutPS.Sample15();
						break;
					case 16:
						ECLSamplesAutPS.Sample16();
						break;
					case 17:
						ECLSamplesAutPS.Sample17();
						break;
					case 18:
						ECLSamplesAutFieldList.Sample18();
						break;
				}


			}
		}
	}

	public class ECLSamplesAutConnList
	{
		static public void Sample1()
		{
			//This sample will return the number of instances of the emulator running
			AutConnList EmulatorConnectionList = new AutConnList();
			EmulatorConnectionList.Refresh();
			int Count = EmulatorConnectionList.Count;
			Console.WriteLine("The number of Emulator connections is:" + Count);
			EmulatorConnectionList = null;

		}
		static public void Sample2()
		{
			//This sample will reutrn the connection information for all the instances of the emulator running 
			AutConnList EmulatorConnectionList = new AutConnList();
			EmulatorConnectionList.Refresh();
			//The index for the collection starts from one. Hence, foreach or GetEnumerator does not
			// work and you will have a exception
			for ( int i = 1; i <= EmulatorConnectionList.Count ; i++)
			{
				//Get a reference to the session connection information
				IAutConnInfo SessionInfo = (IAutConnInfo)EmulatorConnectionList[i];
				Console.WriteLine("Session Letter: " + SessionInfo.Name);
				Console.WriteLine("\tSession Type: " + SessionInfo.ConnType);
				Console.WriteLine("\tCode Page   : " + SessionInfo.CodePage);
				Console.WriteLine("\tStarted     : " + (SessionInfo.Started ? "Session window not started" : "Session window  started")); 
				Console.WriteLine("\tCommStarted : " + (SessionInfo.CommStarted ? "Session trying to connect/connected to host" : "Session not connected to the host."));
				Console.WriteLine("\tAPIEnabled  : "  + (SessionInfo.APIEnabled ? "API Enabled" : "API not enabled"));
				Console.WriteLine("\tReady       : "  + (SessionInfo.Ready    ? "Session ready" :"Session not ready" ));
			}
			EmulatorConnectionList = null;
		}
		static public void Sample3()
		{
			//Check if a session with the letter 'A' is running
			AutConnList EmulatorConnectionList = new AutConnList();
			EmulatorConnectionList.Refresh();
			Object SessionInfo = EmulatorConnectionList.FindConnectionByName("A");
			if(SessionInfo == null)
				Console.WriteLine("Session A not started");
			else 
			{
				//Use the Session Object as needed
				Console.WriteLine("Session " +((IAutConnInfo)SessionInfo).Name + " started");
			}
			EmulatorConnectionList = null;
		}

		static public void Sample4()
		{
			//Start/Stop communicating with session
			AutConnList EmulatorConnectionList = new AutConnList();
			IAutConnInfo SessionInfo = (IAutConnInfo)EmulatorConnectionList.FindConnectionByName("A");
			if(SessionInfo == null)
				Console.WriteLine("Session A not started");
			else 
			{
				//If connection is not there establish it
				if(!SessionInfo.CommStarted)
					SessionInfo.StartCommunication();
				else
					//Session is connected and try disconnecting it.
					SessionInfo.StopCommunication();
			}
		
		}
	}
	class ECLSamplesAutConnMgr 
	{
		//Start a emulator session 
		static public void Sample5()
		{
			//This sample assumes that the WS file host.ws exists in the 
			//user data directory.
			string WorkStationProfile = "PROFILE=host.ws";
			string SessLetterName            = "CONNNAME=";
			char SessionLetter;
			AutConnMgr ConnMgr = new AutConnMgr();
			//Find the first free session letter and request to start that session letter
			((IAutConnList)ConnMgr.autECLConnList).Refresh();
			for(SessionLetter = 'A';SessionLetter <= 'Z';SessionLetter++)
			{
				Object Session = ((IAutConnList)ConnMgr.autECLConnList).FindConnectionByName(SessionLetter.ToString());
				if(Session==null)
					break;
			}
			string SessionString = WorkStationProfile + " " + SessLetterName + SessionLetter;   
			try 
			{
				ConnMgr.StartConnection(SessionString);
			}
			catch(System.Exception E)
			{ 
				Console.WriteLine("Could not start the session" + E.Message);
				return ;
			}
			//No exeception occured. Wait for the session to start up.
			int Seconds = 0;//10 seconds
			while (Seconds <= 10)//If the session did not start in 10 seconds get out.
			{
				((IAutConnList)ConnMgr.autECLConnList).Refresh();
				Object Session = ((IAutConnList)ConnMgr.autECLConnList).FindConnectionByName(SessionLetter.ToString());
				if( Session != null )//Session started properly
				{
					Session = null;
					break;
				}
				System.Threading.Thread.Sleep(1000);
				Seconds++;
			}
			ConnMgr = null;
		}
	
		//Delegate for sample 6
		public static void CallOnStart(Object ConnHandle,bool bStarted)
		{
        
			AutConnList ConnList = new AutConnList();
			Object Session = ConnList.FindConnectionByHandle((int)ConnHandle);
			Console.WriteLine("Session Letter Started :" + ((AutConnListTypeLibrary.IAutConnInfo)Session).Name);
			System.Windows.Forms.Application.Exit();
	      
		}
		//Start a session as the same as Sample 5.However, detect session startup via events.
		static public void Sample6()
		{
			AutConnMgr ConnMgr = new AutConnMgr();
			ConnMgr.NotifyStartEvent += new  IStartEvent_NotifyStartEventEventHandler(CallOnStart);
			ConnMgr.RegisterStartEvent();	
			//This sample assumes that the WS file host.ws exists in the 
			//user data directory.
			string WorkStationProfile = "PROFILE=host.ws";
			string SessLetterName            = "CONNNAME=";
			char SessionLetter;
			//Find the first free session letter and request to start that session letter
			((IAutConnList)ConnMgr.autECLConnList).Refresh();
			for(SessionLetter = 'A';SessionLetter <= 'Z';SessionLetter++)
			{
				Object Session = ((IAutConnList)ConnMgr.autECLConnList).FindConnectionByName(SessionLetter.ToString());
				if(Session==null)
					break;
			}
			string SessionString = WorkStationProfile + " " + SessLetterName + SessionLetter;   
			try 
			{
				ConnMgr.StartConnection(SessionString);
			}
			catch(System.Exception E)
			{ 
				Console.WriteLine("Could not start the session " + E.Message);
				ConnMgr.UnregisterStartEvent();
				return ;
			}
			//Start request issued.Go in the message loop and wait for the startup event to signal session startup
			System.Windows.Forms.Application.Run();
			//We are out of the loop we took over.Session has started. Go ahead with other 
			//activities
			ConnMgr.UnregisterStartEvent();
		}
		//Stop all running PCOMM Sessions....
		static public void Sample7()
		{
			AutConnMgr ConnMgr = new AutConnMgr();
			//Find the first free session letter and request to stop that session letter and so on
			((IAutConnList)ConnMgr.autECLConnList).Refresh();
			for(char SessionLetter = 'A';SessionLetter <= 'Z';SessionLetter++)
			{
				Object Session = ((IAutConnList)ConnMgr.autECLConnList).FindConnectionByName(SessionLetter.ToString());
				if(Session!=null)
					ConnMgr.StopConnection(SessionLetter.ToString(),"saveprofile=no");
			}
		}
		//This sample will start a session based on the input session letter and 
		//profile name
		static public void Sample8()
		{
			string ProfileName,SessionLetter;
			Console.Write("Enter a profile name:");
			ProfileName   = Console.ReadLine();
          
			Console.Write("Enter a Session Letter to start the profile:"); 
			SessionLetter = Console.ReadLine();
			AutConnMgr ConnMgr = new AutConnMgr();
			string SessionString = "PROFILE="+ProfileName+" " +"CONNNAME=" + SessionLetter;

			try 
			{
				ConnMgr.StartConnection(SessionString);
			}
			catch(System.Exception E)
			{ 
				Console.WriteLine("Could not start the session " + E.Message);
			}
			return ;       
		}
	}
	//AutSess represents a session . It also is a placeholder for all the objects that
	// represent various facets of a session like: PS,OIA,PrinterSettings,FileXfer,WinMetrics etc
	//Typically you latch on to a running session or a session started by your code and
	//manipulate the session with the AutSess objects. AutSess2 is the new autsession object
	// which contains the new printer settings and page settings objects.If you do not wish to use
	// those objects, you can safely you AutSess object.
	class ECLSamplesAutSess 
	{
		static public void Sample9()
		{
			//This sample assumes you started the session A with Sample 8
			//Check if Session A exists...  If it exists get the session Object;
			AutConnMgr ConnMgr = new AutConnMgr();
			((IAutConnList)ConnMgr.autECLConnList).Refresh();
			Object Sess = ((IAutConnList)ConnMgr.autECLConnList).FindConnectionByName("A");
			if(Sess==null)
			{
				Console.WriteLine("Session A does not exist. This sample assumes Session A has started.");
				return;
			}
			AutSess2 Session = new AutSess2();
			Session.SetConnectionByName("A");
			//Connect to the host
			if(!Session.CommStarted)
				Session.StartCommunication();
			//Wait for the input to be ready
			((IAutOIA)(Session.autECLOIA)).WaitForInputReady("100");
		}
	}
	//This object represents the emulator window.This object is useful to hide/show the sessions.
	//Screen scraping frontends  which prefer to hide the emulator to avoid clutter and 
	//user interference should use this class.
	class ECLSamplesAutWinMetrics
	{ // Show the current window status of all active sessions
		static public void Sample10()
		{
			AutConnList EmulatorConnectionList = new AutConnList();
			EmulatorConnectionList.Refresh();
			//The index for the collection starts from one. Hence, foreach or GetEnumerator does not
			// work and you will have a exception
			for ( int i = 1; i <= EmulatorConnectionList.Count ; i++)
			{
				string SessWinState ;
				//Get a reference to the session  information
				IAutConnInfo SessInfo = (IAutConnInfo)EmulatorConnectionList[i];
				AutWinMetrics SessionWinmetrics = new AutWinMetrics();
				SessionWinmetrics.SetConnectionByHandle(SessInfo.Handle);
				Console.WriteLine("Session Letter: " + SessInfo.Name);
				if(SessInfo.CommStarted)
				{
					Console.WriteLine("Session Window Title:" + SessionWinmetrics.WindowTitle);
					Console.WriteLine("Session Window is " + (SessionWinmetrics.Visible  ? "visisble" : "hidden"));
					Console.WriteLine("Session Window co-ordinates are(LEFT,TOP): " + SessionWinmetrics.XPos + " " + SessionWinmetrics.YPos);
					Console.WriteLine("Session Window width and height are: " + SessionWinmetrics.Width + " " +SessionWinmetrics.Height);
					Console.WriteLine("Session window has the focus:" +   ( SessionWinmetrics.Active ? "True":"False"));
		       			
					if(SessionWinmetrics.Maximized)				
						SessWinState = "Maximized";
					else if(SessionWinmetrics.Minimized)
						SessWinState = "Minimized";
					else SessWinState = "Restored";
			
					Console.WriteLine("Session window's current state is:" +   SessWinState);
				}
				else Console.WriteLine("Connection not ready.");
			}

		}
		public static void Sample11()
		{
			//Change the title of the Session  
			//Check if Session A exists...  If it exists get the session Object;
			Console.Write("Enter the session letter to change the title:");
			string SessionLetter = Console.ReadLine();
			Console.Write("Enter the title to change:");
			string SessionWindowTitle = Console.ReadLine();
			AutConnMgr ConnMgr = new AutConnMgr();
			((IAutConnList)ConnMgr.autECLConnList).Refresh();
			Object Sess = ((IAutConnList)ConnMgr.autECLConnList).FindConnectionByName(SessionLetter);
			if(Sess==null)
			{
				Console.WriteLine("Session " + SessionLetter + " does not exist.");
				return;
			}
			AutWinMetrics SessionWinmetrics = new AutWinMetrics();
			SessionWinmetrics.SetConnectionByName(SessionLetter);
			SessionWinmetrics.WindowTitle = SessionWindowTitle;
		}
		public static void Sample12()
		{
			//Change the Window state of an session
			int SessionState = 0;
			Console.Write("Enter the session letter to change the Window State:");
			string SessionLetter = Console.ReadLine();
			while(!(SessionState >=1 && SessionState <=3))
			{
				Console.Write("Enter the State to change(1/2/3) (1)MAXIMIZED (2)MINIMIZED (3)RESTORED:");
				string Input = Console.ReadLine();
				try 
				{
					SessionState = System.Convert.ToInt32(Input);
				}
				catch(System.FormatException  )
				{
					SessionState = 0;
				}
			}
			AutConnMgr ConnMgr = new AutConnMgr();
			((IAutConnList)ConnMgr.autECLConnList).Refresh();
			Object Sess = ((IAutConnList)ConnMgr.autECLConnList).FindConnectionByName(SessionLetter);
			if(Sess==null)
			{
				Console.WriteLine("Session " + SessionLetter + " does not exist.");
				return;
			}
			AutWinMetrics SessionWinmetrics = new AutWinMetrics();
			SessionWinmetrics.SetConnectionByName(SessionLetter);
			if(SessionState == 1)
				SessionWinmetrics.Maximized = true;
			else if(SessionState == 2)
				SessionWinmetrics.Minimized = true;
			else SessionWinmetrics.Restored = true;
			return;
		}
		public static void Sample13()
		{
			//Hide or Show(make visible) an session
			int SessionState = 0;
			Console.Write("Enter the session letter to Hide or display the session:");
			string SessionLetter = Console.ReadLine();
			while(!(SessionState >=1 && SessionState <=2))
			{
				Console.Write("Enter the State to change(1/2) (1)HIDE (2)DISPLAY(Make a hidden Session Visible):");
				string Input = Console.ReadLine();
				try 
				{
					SessionState = System.Convert.ToInt32(Input);
				}
				catch(System.FormatException E )
				{
					SessionState = 0;
				}
			}
			AutConnMgr ConnMgr = new AutConnMgr();
			((IAutConnList)ConnMgr.autECLConnList).Refresh();
			Object Sess = ((IAutConnList)ConnMgr.autECLConnList).FindConnectionByName(SessionLetter);
			if(Sess==null)
			{
				Console.WriteLine("Session " + SessionLetter + " does not exist.");
				return;
			}
			AutWinMetrics SessionWinmetrics = new AutWinMetrics();
			SessionWinmetrics.SetConnectionByName(SessionLetter);
			if(SessionState == 1)
			{
				if(SessionWinmetrics.Visible)
					SessionWinmetrics.Visible = false;
				else Console.WriteLine("Session " + SessionLetter + " is already hidden.");
			}
			else
			{
				if(!SessionWinmetrics.Visible)
					SessionWinmetrics.Visible = false;
				else Console.WriteLine("Session " + SessionLetter + " is already Visible.");
			}
		}   

	}
	//This class represents the Presesntation space of a session. You can control majority 
	//of the PS functions using theis class
	class ECLSamplesAutPS 
	{
		public static void Sample15()
		{
			//This sample starts a session and waits for the session to be connected and once the session is connected
			// it navigates from the the inital logon screen to the first application screen and it logs out.
			//This sample assumes that there is a logon screen with the string USERID in it.
			//Run the Sample 5 which starts an session with the name host.ws . //For simplicity assume that session A was started.
			ECLSamplesAutConnMgr.Sample5();
			AutPS PresSpace = new AutPS();
			PresSpace.SetConnectionByName("A");
			PresSpace.WaitForString("USERID",0,0,10000,true,false);
			//This assumes that cursor is located in the input field next to user ID
			//One also could use standard cursor movement API's to navigate to the needed field 
			PresSpace.SendKeys("scottq[tab]",PresSpace.CursorPosRow,PresSpace.CursorPosCol);//Send the user ID scottq
			PresSpace.SendKeys("a7heris[enter]",PresSpace.CursorPosRow,PresSpace.CursorPosCol);
			//This takes us to our first screen.
			//In a robust screen scraping program there has to be logic to handle logon errors.
			PresSpace.SendKeys("logoff[enter]",PresSpace.CursorPosRow,PresSpace.CursorPosCol);
			//Close the session.
			ECLSamplesAutConnMgr.Sample7();
		  
		}
		static int PsUpdateCount ;
		public static void CallOnPSUpdate()
		{
			AutPS PresSpace = new AutPS();
			PresSpace.SetConnectionByName("A"); 
			string Pres = PresSpace.GetText(1,1,1920);
			Console.WriteLine(Pres);
			if(++PsUpdateCount == 20)
			{
				PsUpdateCount = 0;
				PresSpace.UnregisterPSEvent();
				System.Windows.Forms.Application.Exit();
			}
		}
		
		public static void Sample16()
		{
			//This sample  shows how to use PS events.  This sample shows first 20 updates via the delegate
			//Have a class which derives from AutPS and adds the handler.
			AutPS PresSpace = new AutPS();
			//			PSUpdateCount = 0;
			PresSpace.NotifyPSEvent +=  new IPSEvent_NotifyPSEventEventHandler(CallOnPSUpdate);
			
			ECLSamplesAutConnMgr.Sample5();
			//For simplicity assume session A
			PresSpace.SetConnectionByName("A"); 
			PresSpace.RegisterPSEvent(true);
			//Wait on the Run Method
			System.Windows.Forms.Application.Run();
			ECLSamplesAutConnMgr.Sample7();
		}
		public static void Sample17()
		{
			AutPS PresSpace = new AutPS();
			//Search for a given text in the PS
			ECLSamplesAutConnMgr.Sample5();
			//For simplicity assume session A
			PresSpace.SetConnectionByName("A");
			Console.Write("Enter text to search on the PS of session A :");
			string SearchText = Console.ReadLine();
			Object Row = 1  ,Col = 1;

			if(PresSpace.SearchText(SearchText,AutPSTypeLibrary.PsDir.pcNoDirection, ref Row,ref Col))
				Console.WriteLine("String found in the presentation space at ROW:" + Row + " and COL:" + Col);
			else
				Console.WriteLine("String not found in the presentation space.");
			ECLSamplesAutConnMgr.Sample7();
		}  
	}
	//This class represents the fields of Plane....
	class ECLSamplesAutFieldList 
	{
		public static void Sample18()
		{
			// Print information about all the fields in the presentation space.
			AutPS PresSpace = new AutPS();
			ECLSamplesAutConnMgr.Sample5();
			//For simplicity assume session A
			PresSpace.SetConnectionByName("A");		
			((IAutFieldList)(PresSpace.autECLFieldList)).Refresh();
			Console.WriteLine("Number of Fields in the PS are:" + ((IAutFieldList)(PresSpace.autECLFieldList)).Count);
			
			for(int i = 1; i <= ((IAutFieldList)(PresSpace.autECLFieldList)).Count;i++)
			{
				IAutFieldInfo PresField = (IAutFieldInfo)((IAutFieldList)(PresSpace.autECLFieldList))[i];
				Console.WriteLine("Field Text: " + PresField.GetText());
				Console.WriteLine("Field Pos(Start Row,Start Col,End Row,End Col: " + PresField.StartRow + " " + PresField.StartCol + " " + PresField.EndRow + " " + PresField.EndCol);
				Console.WriteLine("Field Length:  " + PresField.Length);
				Console.WriteLine("Field Protected Attribute :"  + (PresField.Protected?"True":"False"));
				Console.WriteLine("Field Modified Attribute:" + (PresField.Modified ?"True":"False"));
				Console.WriteLine("Field Display Attribute:" + (PresField.Display  ?"True":"False"));
				Console.WriteLine("Field High intensity Attribute:" + (PresField.HighIntensity  ?"True":"False"));
				Console.WriteLine("Field PenDetectable Attribute:" + (PresField.PenDetectable ? "True":"False"));
			}
			ECLSamplesAutConnMgr.Sample7();
		}
	}
	

}
