Untitled
unknown
plain_text
8 months ago
3.8 kB
6
Indexable
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace SAPAutomation
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine($"[{DateTime.Now}] Connecting to SAP GUI...");
// Attach to the SAP GUI scripting engine
Type sapGuiType = Type.GetTypeFromProgID("SapGui.ScriptingCtrl.1");
if (sapGuiType == null)
{
throw new Exception("SAP GUI Scripting Control not found. Ensure it is registered and installed.");
}
dynamic sapGuiApp = Activator.CreateInstance(sapGuiType);
if (sapGuiApp == null)
{
throw new Exception("Failed to create an instance of SAP GUI scripting application.");
}
Console.WriteLine($"[{DateTime.Now}] Successfully connected to SAP GUI Scripting Control!");
// Open SAP connection
Console.WriteLine($"[{DateTime.Now}] OpenConnection called...");
dynamic sapConnection = sapGuiApp.OpenConnection("SRS");
if (sapConnection == null)
{
throw new Exception("Failed to open SAP connection. Ensure the system name is correct.");
}
Console.WriteLine($"[{DateTime.Now}] Connection established!");
// Wait for session readiness
Console.WriteLine($"[{DateTime.Now}] Checking for active sessions...");
int maxWaitTime = 15000; // Max wait time in milliseconds
int waitInterval = 1000; // Polling interval in milliseconds
int elapsedTime = 0;
while (sapConnection.Children.Count == 0 && elapsedTime < maxWaitTime)
{
Console.WriteLine($"[{DateTime.Now}] Waiting for the SAP session to be ready...");
Thread.Sleep(waitInterval);
elapsedTime += waitInterval;
}
if (sapConnection.Children.Count == 0)
{
throw new Exception("No active SAP session found after waiting.");
}
dynamic sapSession = sapConnection.Children(0); // First session in the connection
if (sapSession == null)
{
throw new Exception("No active SAP session found. Ensure the connection is valid.");
}
Console.WriteLine($"[{DateTime.Now}] Session ready!");
// Example: Maximize the SAP window
Console.WriteLine($"[{DateTime.Now}] Maximize SAP window...");
sapSession.FindById("wnd[0]").Maximize();
Thread.Sleep(2000); // Pause for 2 seconds
// Example: Perform login
Console.WriteLine($"[{DateTime.Now}] Performing login...");
sapSession.FindById("wnd[0]/usr/txtRSYST-BNAME").Text = "your_username";
sapSession.FindById("wnd[0]/usr/pwdRSYST-BCODE").Text = "your_password";
sapSession.FindById("wnd[0]/tbar[0]/btn[0]").Press();
Thread.Sleep(50000); // Pause for 3 seconds after login
Console.WriteLine($"[{DateTime.Now}] Login operation performed successfully.");
}
catch (COMException ex)
{
Console.WriteLine($"COM Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
Editor is loading...
Leave a Comment