Hi there,
I am calling following C# method to Query all the available sessions at the moment.
Code:
public static UInt32 QuerySessions(out string s)
{
Console.WriteLine("Query session entered");
StringBuilder Data = new StringBuilder(312);
Data.Append(' ', 312);
UInt32 rc = 0;
UInt32 f = HA_QUERY_SESSIONS;
UInt32 l = 312;
UInt32 r = EhllapiFunc.hllapi(out f, Data, out l, out rc);
Console.WriteLine("Query session Exit");
s = Data.ToString();
return r;
}
I am calling this from one timer after defined time.
Let say I have two running Rumba session open at the moment. I successfully get data from above API.
If I close existing Rumba Emulator window. the code inside timer hang on the the API call for infinite time .
I an wondering why it stops. What is the dependency with the existing sessions. Please suggest work around for the same.
#Rumba9.5#RumbaI observe following:
I require to check constantly which session is in focus. So I keep querying rumba API after every 500 milliseconds.
I also tried to increase timing to 2 seconds. Still I am not getting response everytime from QuerySession API.
Hi there,
I am calling following C# method to Query all the available sessions at the moment.
Code:
public static UInt32 QuerySessions(out string s)
{
Console.WriteLine("Query session entered");
StringBuilder Data = new StringBuilder(312);
Data.Append(' ', 312);
UInt32 rc = 0;
UInt32 f = HA_QUERY_SESSIONS;
UInt32 l = 312;
UInt32 r = EhllapiFunc.hllapi(out f, Data, out l, out rc);
Console.WriteLine("Query session Exit");
s = Data.ToString();
return r;
}
I am calling this from one timer after defined time.
Let say I have two running Rumba session open at the moment. I successfully get data from above API.
If I close existing Rumba Emulator window. the code inside timer hang on the the API call for infinite time .
I an wondering why it stops. What is the dependency with the existing sessions. Please suggest work around for the same.
#Rumba9.5#RumbaI have added while loop to wait until i get active session from QuerySession API.
Still I have to wait for the API to respond with code 0 ( Success code for QuerySession API) I need to get response every time.
Please refer following code.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EV.AE.RumbaAutomation;
using System.IO;
using WebSocket4Net;
using System.Runtime.InteropServices;
namespace Test_EHLLAPIWrapper
{
class Program
{
static List<string> sessionList = new List<string>();
static List<string> sessionCollectionList = new List<string>();
static ManualResetEvent _quitEvent = new ManualResetEvent(false);
static System.Timers.Timer timer;
static void Main(string[] args)
{
Console.CancelKeyPress = (sender, eArgs) =>
{
_quitEvent.Set();
eArgs.Cancel = true;
};
// kick off asynchronous stuff
//EHLLAPI.EhllapiWrapper1.SetSessParams("NOATTRB,NOEAB,NOXLATE,NEWRET,TWAIT,SRCHALL,SRCHFRWD,FPAUSE,AUTORESET,QUIET,WRITE_SUPER").ToString();
//string s = string.Empty;
//EHLLAPI.EhllapiWrapper1.QuerySessions(out s);
//string[] sessionCollection = s.Split(new string[] { "€\\a" }, StringSplitOptions.RemoveEmptyEntries);
////sessionList = new string[sessionCollection.Length];
//for (int i = 0; i < sessionCollection.Length; i )
//{
// //EHLLAPI.EhllapiWrapper1.Connect(sessionCollection
.Substring(0, 1));
// if (EHLLAPI.EhllapiWrapper1.StartHostNotification(sessionCollection.Substring(0, 1)) == 0)
// {
// sessionList.Add(sessionCollection.Substring(0, 1));
// }
//}
//Launch();
timer = new System.Timers.Timer();
timer.Elapsed = Timer_Elapsed;
timer.Enabled = true;
timer.Interval = 2000;
_quitEvent.WaitOne();
}
static ManualResetEvent queryHndl = new ManualResetEvent(false);
#region Win32
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private static string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
private static IntPtr GetActiveWindow()
{
return GetForegroundWindow();
}
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32")]
private static extern UInt32 GetWindowThreadProcessId(Int32 hWnd, out Int32 lpdwProcessId);
private static Int32 GetWindowProcessID(Int32 hwnd)
{
Int32 pid = 1;
GetWindowThreadProcessId(hwnd, out pid);
return pid;
}
#endregion Win32
private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer.Stop();
Console.WriteLine("Timer Elasped");
Int32 hwnd = (Int32)GetForegroundWindow();
string appProcessName = Process.GetProcessById(GetWindowProcessID(hwnd)).ProcessName;
string appExePath = Process.GetProcessById(GetWindowProcessID(hwnd)).MainModule.FileName;
Console.WriteLine("1");
if (appExePath.ToLower().Contains("wddsppag") || appExePath.ToLower().Contains("rumbapage"))
{
Console.WriteLine("1.1");
string sessions = string.Empty;
UInt32 r = 14;
//Task task = Task.Factory.StartNew(() =>
//{
// r = EHLLAPI.EhllapiWrapper1.QuerySessions(out sessions);
// queryHndl.Set();
// if (r == 0)
// {
// try
// {
// Console.WriteLine("1.2");
// string[] sessionCollection = sessions.Split(new string[] { "€\\a" }, StringSplitOptions.RemoveEmptyEntries);
// Console.WriteLine("2");
// for (int i = 0; i < sessionCollection.Length; i )
// {
// string sessionSortNm = sessionCollection.Substring(0, 1);
// sessionCollectionList.Add(sessionSortNm);
// if (!sessionList.Contains(sessionSortNm))
// {
// if (EHLLAPI.EhllapiWrapper1.StartHostNotification(sessionSortNm) == 0)
// {
// sessionList.Add(sessionSortNm);
// }
// }
// }
// Console.WriteLine("3");
// var extra = sessionList.Except(sessionCollectionList).ToArray();
// foreach (string strSession in extra)
// {
// sessionList.Remove(strSession);
// }
// }
// catch (Exception ex)
// {
// Console.WriteLine(ex.Message);
// }
// }
//});
//queryHndl.WaitOne(200);
int loopCounter = 0;
do
{
Console.WriteLine("loopCounter: " loopCounter);
Thread elementExtractor = new Thread(() =>
{
try
{
r = EHLLAPI.EhllapiWrapper1.QuerySessions(out sessions);
queryHndl.Set();
}
catch { }
finally
{
//Console.WriteLine("QuerySessions complated.");
}
});
//Console.WriteLine("Thread ApartmentState.STA.");
elementExtractor.SetApartmentState(ApartmentState.STA);
elementExtractor.Priority = ThreadPriority.Highest;
elementExtractor.Start();
//elementExtractor.Join();
queryHndl.WaitOne(200);
loopCounter = 1;
} while (r != 0 && loopCounter < 15);
string[] sessionCollection = sessions.Split(new string[] { "€\\a" }, StringSplitOptions.RemoveEmptyEntries);
//Console.WriteLine("2");
for (int i = 0; i < sessionCollection.Length; i )
{
string sessionSortNm = sessionCollection.Substring(0, 1);
sessionCollectionList.Add(sessionSortNm);
if (!sessionList.Contains(sessionSortNm))
{
if (EHLLAPI.EhllapiWrapper1.StartHostNotification(sessionSortNm) == 0)
{
sessionList.Add(sessionSortNm);
}
}
}
//Console.WriteLine("3");
var extra = sessionList.Except(sessionCollectionList).ToArray();
foreach (string strSession in extra)
{
sessionList.Remove(strSession);
}
Console.WriteLine("Sessions" sessions);
Console.WriteLine("Result" r);
Console.WriteLine("4");
foreach (string s in sessionList)
{
UInt32 result = EHLLAPI.EhllapiWrapper1.CheckHostUpdated(s);
int p;
EHLLAPI.EhllapiWrapper1.GetCursorPos(out p);
if (result == 21)
{
EHLLAPI.EhllapiWrapper1.Connect(s);
Console.WriteLine("Window switch to session is : {0} position is : {1} , result: {2}", s, p, result);
}
else if (result == 22)
{
Console.WriteLine("Active session is : {0} position is : {1} , result: {2}", s, p, result);
}
else if (result == 23)
{
Console.WriteLine("Active session is : {0} position is : {1} , result: {2}", s, p, result);
}
}
Console.WriteLine("5");
}
else
{
EHLLAPI.EhllapiWrapper1.ResetSystem();
sessionList.Clear();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Timer Started in Finally block.");
timer.Enabled = true;
timer.Start();
}
}
public static void Launch()
{
try
{
EHLLAPI.EhllapiWrapper1.SetSessParams("NOATTRB,NOEAB,NOXLATE,NEWRET,TWAIT,SRCHALL,SRCHFRWD,FPAUSE,AUTORESET,QUIET,WRITE_SUPER").ToString();
string s = string.Empty;
EHLLAPI.EhllapiWrapper1.QuerySessions(out s);
//EHLLAPI.EhllapiWrapper1.StartHostNotification(out s);
//EHLLAPI.EhllapiWrapper1.CheckHostUpdated(out s);
EHLLAPI.EhllapiWrapper1.StartKeyIntercept(out s);
string GetKeyVal = EHLLAPI.EhllapiWrapper1.GetKey(out s);
int CurPos = 0;
EHLLAPI.EhllapiWrapper1.GetCursorPos(out CurPos);
EHLLAPI.EhllapiWrapper1.SendKey(GetKeyVal);
EHLLAPI.EhllapiWrapper1.StopKeyIntercept(out s);
UInt32 sessionID = EHLLAPI.EhllapiWrapper1.Connect("B");
EHLLAPI.EhllapiWrapper1.GetCursorPos(out CurPos);
UInt32 FieldPosition = EHLLAPI.EhllapiWrapper1.FieldPosition((UInt32)CurPos);
UInt32 FieldLinght = EHLLAPI.EhllapiWrapper1.FieldLength(FieldPosition);
string FieldString = EHLLAPI.EhllapiWrapper1.CopyFieldString(FieldPosition);
string FieldAttributes = EHLLAPI.EhllapiWrapper1.CopyFieldAttribute(FieldPosition);
string CopiedPresentationSpace = EHLLAPI.EhllapiWrapper1.CopyPresentationSpace((UInt32)CurPos);
EHLLAPI.EhllapiWrapper1.ReadScreen((int)FieldPosition, 3000, out s);
//System.Diagnostics.Debugger.Launch();
//Process RumbaProcess = Process.Start(@"C:\\Users\\Gaurav_Teli\\Documents\\Mainframe Display.rsdm");
Thread.Sleep(300);
string sessionShortName = "A";
string EmulatorApiMethod = "hllapi";
//EhllapiWrapper EhllapiWrapper = new EhllapiWrapper(@"C:\\Program Files (x86)\\Micro Focus\\RUMBA\\System\\ehlapi32.Dll", EmulatorApiMethod);
EhllapiWrapper EhllapiWrapper = new EhllapiWrapper(@"C:\\Program Files (x86)\\Micro Focus\\RUMBA\\System\\ehlapi32.Dll", EmulatorApiMethod);
EhllapiWrapper?.Connect(sessionShortName);
int position = EhllapiWrapper.GetCursorPosition();
Int16 Row = EhllapiWrapper.GetRowCount(position);
Int16 Column = EhllapiWrapper.GetColumnCount(position);
//string fieldName = EhllapiWrapper.FindField(position);
//string fieldName = EhllapiWrapper.CallFunctionCode(34,Row,Column,"");
EhllapiWrapper.CopyStringToPS(Row, Column, "test");
Console.WriteLine("position: " position.ToString());
Console.ReadKey();
}
catch { }
}
//public void LaunchRecorder(ref int processID, ref int websocketPortNo)
//{
// try
// {
// int pID = processID;
// Process pbeRecorderProcess = null;
// //logger.DebugFormat("Searching existing process with process PID '{0}'", pID.ToString());
// if (pID > 0)
// pbeRecorderProcess = Process.GetProcesses().FirstOrDefault(x => x.Id == pID || x.ProcessName.ToLower() == procName.ToLower());
// if (pbeRecorderProcess == null)
// {
// pbeRecorderProcess = new Process();
// ProcessStartInfo prcStartInfo = new ProcessStartInfo();
// prcStartInfo.UseShellExecute = false;
// string recorderExePath = @"C:\\Users\\Gaurav_Teli\\Documents\\Visual Studio 2015\\Projects\\Test_EHLLAPIWrapper\\RumbaRecorder\\bin\\Debug\\RumbaRecorder.exe";
// FileInfo finfo = new FileInfo(recorderExePath);
// if (finfo.Exists)
// {
// prcStartInfo.WorkingDirectory = finfo.DirectoryName;
// prcStartInfo.FileName = finfo.FullName;
// prcStartInfo.Arguments = "rumba_backgroundrecorder";
// pbeRecorderProcess.StartInfo = prcStartInfo;
// pbeRecorderProcess.Start();
// pbeRecorderProcess.WaitForInputIdle();
// //logger.DebugFormat("Existing process with process PID '{0}' not nound. Started new process with process PID '{1}'", pID.ToString(), pbeRecorderProcess.Id.ToString());
// Thread.Sleep(5000);
// }
// else
// {
// //logger.Error("Background Recorder exe not found. Please refer config file to configure Background Recorder exe path.");
// }
// }
// //else
// //logger.DebugFormat("Process with process PID '{0}' found", pID.ToString());
// string portNo = string.Empty;
// string hostname = string.Empty;
// int maxAtmptGetPort = 10;
// while (string.IsNullOrEmpty(portNo) && maxAtmptGetPort > 0)
// {
// portNo = pbeRecorderProcess.GetUsedPortNumber(hostname);
// maxAtmptGetPort--;
// if (string.IsNullOrEmpty(portNo)) Thread.Sleep(1000);
// }
// WebSocket websocket = null;
// if (websocket == null)
// {
// websocket = new WebSocket($"ws://{hostname}:{portNo}/", "", null, null, "", "IDM:BGRecorder");
// websocket.MessageReceived -= Websocket_MessageReceived;
// websocket.MessageReceived = Websocket_MessageReceived; ;
// websocket.Closed -= Websocket_Closed;
// websocket.Closed = Websocket_Closed; ;
// websocket.Open();
// }
// maxAtmptGetPort = 10;
// while (websocket.State == WebSocketState.Connecting && maxAtmptGetPort > 0)
// {
// maxAtmptGetPort--;
// Thread.Sleep(1000);
// }
// processID = pbeRecorderProcess.Id;
// websocketPortNo = int.Parse(portNo);
// }
// catch (Exception ex)
// {
// }
//}
//private void Websocket_Closed(object sender, EventArgs e)
//{
//}
//private void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
//{
//}
}
public static class ProcessExtension
{
public static string userEnvironmentPath = string.Empty;
//public static string GetUsedPortNumber(this Process targetProcess, string hostname)
//{
// string batFileNm = "getnetstat.bat";
// ProcessStartInfo start = new ProcessStartInfo();
// if (!File.Exists(Path.Combine(userEnvironmentPath, batFileNm)))
// {
// using (StreamWriter streamWriter = File.CreateText(Path.Combine(userEnvironmentPath, batFileNm)))
// {
// streamWriter.Write("netstat -ano | findstr %1");
// }
// }
// start.FileName = Path.Combine(userEnvironmentPath, batFileNm); // Specify exe name.
// start.UseShellExecute = false;
// start.RedirectStandardOutput = true;
// start.CreateNoWindow = true;
// start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
// start.Arguments = targetProcess.Id.ToString();
// using (Process process = Process.Start(start))
// {
// using (StreamReader reader = process.StandardOutput)
// {
// string result = reader.ReadToEnd();
// string[] rows = Regex.Split(result, "\\r\\n");
// foreach (string row in rows)
// {
// //Split it into columns
// string[] tokens = Regex.Split(row, "\\\\s ");
// if (tokens.Length > 4 && (tokens[1].Equals("UDP") || tokens[1].Equals("TCP")))
// {
// string localAddress = Regex.Replace(tokens[2], @"\\[(.*?)\\]", hostname);
// string port_number = localAddress.Split(':')[1];
// return port_number;
// }
// }
// }
// }
// return "";
//}
}
}