jkmills78
10/17/2017 - 8:38 PM

SAP Connection Class

Class to handle SAP connections

using SapROTWr;
using System;
using SAPFEWSELib;

namespace MyApp.Services.SAP
{
    public enum SAPServer
    {
        Quality,
        Production
    }

    public static class SAPConnection
    {
        private const string Quality = "Quality Server";
        private const string Production = "Production Server";

        public static CSapROTWrapper SAPROTWrapper { get; set; }
        public static object SAPGuiRot { get; set; }
        public static GuiConnection GUIConnection { get; set; }
        public static GuiSession GUISession { get; set; }
        public static GuiApplication GUIApp { get; set; }
        public static GuiFrameWindow GUIFrameWindow { get; set; }

        static SAPConnection()
        {
            SAPROTWrapper = new CSapROTWrapper();
            SAPGuiRot = SAPROTWrapper.GetROTEntry("SAPGUI");
        }

        public static void Connect(SAPServer connection)
        {
            CreateGUIApp();
            switch(connection)
            {
                case SAPServer.Quality:
                    CreateGUIConnection(Quality);
                    break;
                case SAPServer.Production:
                    CreateGUIConnection(Production);
                    break;
            }

            GUISession = GUIConnection?.Children.ElementAt(0) as GuiSession;
            GUIFrameWindow = GUISession.FindById("wnd[0]") as GuiFrameWindow;
        }

        private static void CreateGUIApp()
        {
            if (SAPGuiRot == null)
            {
                GUIApp = (GuiApplication)Activator.CreateInstance(Type.GetTypeFromProgID("SapGui.ScriptingCtrl.1"));
            }
            else
            {
                GUIApp =
                    SAPGuiRot.GetType()
                        .InvokeMember("GetScriptingEngine", System.Reflection.BindingFlags.InvokeMethod, null,
                            SAPGuiRot, null) as GuiApplication;
            }
        }

        private static void CreateGUIConnection(string connectionName)
        {
            if (GUIApp?.Connections.Count == 0)
            {
                GUIConnection = GUIApp.OpenConnection(connectionName);
            }
            else
            {
                GUIConnection = GUIApp?.Children.ElementAt(0) as GuiConnection;
            }
        }
    }
}