Quantcast
Channel: SCN : Document List - Scripting Languages
Viewing all 100 articles
Browse latest View live

How to Create an SAP Server Program with Freestyle BASIC Script Language (FBSL)

$
0
0

Hello community,

 

nearly a half year I develop the COM Connector (CCo), look here.

Since over a month I develop for Freestyle BASIC Script Language (FBSL) an ABAP interface called FbslX, look here.

 

And now I switch my perspective a little bit. Now I use FBSL as "normal" script language with SAP NetWeaver RFC library to connect an SAP system. Here I use also CCo.

 

FBSL is the first BASIC like script language which I know, with which it is possbile to create SAP server programs. Here my example code:


//-Begin----------------------------------------------------------------

 

  //-Directives---------------------------------------------------------
    #AppType Console
    #Option Strict
   
  //-Includes-----------------------------------------------------------
    #Include <Windows.inc>
    #Include <sapnwrfc.inc>

 

  //-ABAPCall-----------------------------------------------------------
    Function ABAPCall(%rfcHandle, %funcHandle, %errorInfo)
      ? "ABAPCall"
      Return 0
    End Function

 

  //-Main---------------------------------------------------------------
    Sub Main()

 

      //-Variables------------------------------------------------------
        Dim %SAP, %hRfc, %hDesc, %rc, %hCon

 

      SAP = CreateObject("COMNWRFC")
      If SAP Then
        CallMethod(SAP, ".About")
        hDesc = GetValue("%d", SAP, ".RfcCreateFunctionDesc(%s)", _
          "ABAPCall")
        If hDesc Then
       
          rc = GetValue("%d", SAP, ".RfcInstallServerFunction(%s, %d, %d)", _
            "", hDesc, AdressOf ABAPCall)

          If rc = RFC_OK Then
         
            hCon = GetValue("%d", SAP, ".RfcRegisterServer(%s)", _
              "program_id=FBSLSERVER, gwhost=ABAP, gwserv=sapgw00")
            If hCon Then
           
              While rc = RFC_OK Or rc = RFC_RETRY
             
                rc = GetValue("%d", SAP, ".RfcListenAndDispatch(%d, %d)", _
                  hCon, 1)
                 
                Select Case rc
                  Case 0
                    OutputDebugString("RFC_OK")
                  Case 14
                    OutputDebugString("RFC_RETRY")
                End Select 
               
                Sleep(256)
             
              Wend
           
            End If
         
          End If
       
          CallMethod(SAP, ".RfcDestroyFunctionDesc(%d)", hDesc)
        End If
        ReleaseObject(SAP)
      End If
  
    End Sub

 

//-End------------------------------------------------------------------

 

You can call this script from ABAP via the following example code:


"-Begin-----------------------------------------------------------------

  Program ZTEST.

    Call Function 'ABAPCall' Destination 'FBSLSERVER'.

 

"-End-------------------------------------------------------------------

 

You must customize the FBSLSERVER with the TAC SM59 and that's all.

 

In my opinion offers this possibility absolut new horizons. So it is possible to use FBSL scripts as SAP server programs without any other steps, like e.g. compiling etc., or big IDEs or script environments. FBSL is extrem compact and powerful.  You can change the script easily via an simple editor and use it from SAP application server via an ABAP program. I have been searching a long time for this kind of solution.

 

Hope toinspireotherprogrammers.

 

Cheers

Stefan


How to use Freestyle BASIC Script Language (FBSL) with SAP GUI Scripting

$
0
0

Hello community,

 

Freestyle BASIC Script Language (FBSL) is a true multitalent. It is possible to use it inside ABAP, to build client and server applications and to use it with SAP GUI Scripting, as the example here shows. It is only a simple logon, but it shows how to use FBSL in this case.


//-Begin----------------------------------------------------------------

 

  //-Directives---------------------------------------------------------
    #AppType Console
    #Option Strict

 

  //-Includes-----------------------------------------------------------
    #Include <Windows.inc>
 
  //-Main---------------------------------------------------------------
    Sub Main()

 

      //-Variables------------------------------------------------------
        Dim %SAPROTWrapper, %SapGuiAuto, %application, %connection
        Dim %session

 

      SAPROTWrapper = CreateObject("SapROTWr.SapROTWrapper", "")
      If Not SAPROTWrapper Then
        ExitProgram
      End If

 

      SapGuiAuto = GetValue("%o", SAPROTWrapper, ".GetROTEntry(%s)", _
        "SAPGUI")
      If Not SapGuiAuto Then
        ExitProgram
      End If

 

      application = GetValue("%o", SapGuiAuto, ".GetScriptingEngine")
      If Not application Then
        ExitProgram
      End If

 

      connection = GetValue("%o", application, ".Children(%d)", 0)
      If Not connection Then
        ExitProgram
      End If

 

      session = GetValue("%o", connection, ".Children(%d)", 0)
      If Not session Then
        ExitProgram
      End If

 

      PutValue(session, ".findById(%s).text = %s", _
        "wnd[0]/usr/txtRSYST-MANDT", "001")
      PutValue(session, ".findById(%s).text = %s", _
        "wnd[0]/usr/txtRSYST-BNAME", "BCUSER")
      PutValue(session, ".findById(%s).text = %s", _
        "wnd[0]/usr/pwdRSYST-BCODE", "minisap")
      PutValue(session, ".findById(%s).text = %s", _
        "wnd[0]/usr/txtRSYST-LANGU", "EN")
      CallMethod(session, ".findById(%s).sendVKey %d", _
        "wnd[0]", 0)

 

      ReleaseObject(SAPROTWrapper)

 

    End Sub

 

//-End------------------------------------------------------------------

 

FBSL can compile scripts to executable. On this way you can deliver your SAP GUI script to any target computer on Windows platform, without any dependencies.

 

Good Scripting.

 

Cheers

Stefan

Freestyle BASIC Script Language (FBSL) in the Context of the SAP Application Server

$
0
0

Hello community,

 

here an architecture map to visualize the possibilities of FBSL in the context of the SAP application server.

 

FBSL_SAPAPPSERV.jpg

 

As you can see there are different ways to connect FBSL with the SAP application server. Via SAP GUI Scripting - example see here - via SAP NetWeaver RFC Library - example see here - and via FBSLX and ABAP - example see here. This is a wide range and as far as I can say is FBSL a phantastic platform for this kind of realizations. So it is easy possible to integrate process flows ot the application server with the presentation server and vis-a-vis.

 

Cheers

Stefan

 

 

P.S.  To use FBSL with SAP NetWeaver RFC Library I developed a special COM Connector, you find it here.

How to Use Python Inside ABAP

$
0
0

Hello community,

 

in the last time I presented a way to integrate BASIC-style script language inside ABAP here. To demonstrate that the these procedures work with other scripting languages too, I take the same methods and use it with Python language. Also I will show that it is possible to use the same ways with more volumminous environments. So I contain a complete Python environment inside ABAP and unpack it at the runtime of my ABAP program and in the context of the ABAP program I create a Python script an use it inside ABAP.

 

Steps

  1. Downloading of Python 2.7.5 from http://www.python.org/.
  2. Installation of Python in the standard default directory C:\Python27.
  3. Copying of python27.dll from c:\Windows\system32 into C:\Python27.
  4. Creating of a multi part RAR archive with a part size of max. 8,000,000 bytes. So I get three RAR archives.
  5. Creating of three ABAP function modules with BinFile2ABAP which contains these RAR archives.
  6. Creating of three function groups and upload of the function modules inside this groups.
    Hint: It is not possible to store more than 65,535 literals in one function group. So it is necessary to create for each function module its own function group.
  7. Upload of zScripXDll function module from here. It contains ScriptX ActiveX library which builds the bridge between ABAP and the scripting language.

 

With these preparations you build the possibility to use Python inside ABAP.

 

ABAP Test Program


"-Begin-----------------------------------------------------------------
  Program ZSCRIPTX.

 

    "-Constants---------------------------------------------------------
      Constants CrLf(2) Type c Value %_CR_LF.
      Constants SW_SHOWNORMAL Type i Value 1.

 

    "-Variables---------------------------------------------------------
      Data oScriptX Type OLE2_OBJECT.
      Data Buffer Type String Value ''.
      Data WorkDir Type String Value ''.
      Data FileName Type String Value ''.
      Data rc Type i Value 0.
      Data hFileMap Type i Value 0.
      Data RetCode Type String Value ''.

 

    "-Macros------------------------------------------------------------
      Define _.
        Concatenate Buffer &1 CrLf Into Buffer.
      End-Of-Definition.

 

      Define Flush.
        Call Function 'AC_SYSTEM_FLUSH' Exceptions Others = 1.
      End-Of-Definition.

 

    "-Main--------------------------------------------------------------
      Create Object oScriptX 'ScriptX'.

      If sy-subrc <> 0 Or  oScriptX-Handle = 0 Or oScriptX-Type <> 'OLE2'.
        Call Function 'ZSCRIPTXDLL'.
        Create Object oScriptX 'ScriptX'.
      EndIf.

 

      If sy-subrc = 0 And oScriptX-Handle > 0 And oScriptX-Type = 'OLE2'.

        Call Method Of oScriptX 'About'.
        Flush.

 

        "-Create multi part archive files-------------------------------
          Call Function 'ZPYTHON27PART1RAR'.
          Call Function 'ZPYTHON27PART2RAR'.
          Call Function 'ZPYTHON27PART3RAR'.

 

        "-Unpack archive------------------------------------------------
          Call Method Of oScriptX 'Unrar' Exporting
            #1 = 'Python27.part1.rar'.
          Flush.

 

        "-Delete multi part archive files-------------------------------
          Call Method Of oScriptX 'DeleteFile' Exporting
            #1 = 'Python27.part1.rar'.
          Call Method Of oScriptX 'DeleteFile' Exporting
            #1 = 'Python27.part2.rar'.
          Call Method Of oScriptX 'DeleteFile' Exporting
            #1 = 'Python27.part3.rar'.
          Flush.

 

        Call Method Of oScriptX 'FileMapCreate' = hFileMap
          Exporting #1 = 'SAP001' #2 = 64.

        Flush.

 

        If hFileMap <> 0.

 

"-Python Script begin---------------------------------------------------

 

  "-External libraries--------------------------------------------------
_ 'import ctypes'.
_ 'import sys'.

 

  "-Constants-----------------------------------------------------------
_ 'FILE_MAP_ALL_ACCESS = 30'.

 

  "-Main----------------------------------------------------------------
_ 'print "Python version ", sys.version'.
_ 'print "Hello World from Python"'.
_ 'var_inp = raw_input("Enter something: ")'.
_ 'print "You entered: ", var_inp'.

 

  "-Transfer the input to the memory map file---------------------------
_ 'hMMF = ctypes.windll.kernel32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, \'.
_ '  0, "SAP001")'.
_ 'if hMMF <> 0:'.
_ '  buffer = ctypes.windll.kernel32.MapViewOfFile(hMMF, \'.
_ '    FILE_MAP_ALL_ACCESS, 0, 0, 0)'.
_ '  if buffer <> 0:'.
_ '    ctypes.cdll.msvcrt.strcpy(buffer, var_inp)'.
_ '    rc = ctypes.windll.kernel32.UnmapViewOfFile(buffer)'.
_ '  rc = ctypes.windll.kernel32.CloseHandle(hMMF)'.

 

_ 'raw_input("Press any key...")'.

 

"-Python Script end-----------------------------------------------------

 

          "-Get SAP GUIs work directory---------------------------------
            Call Method cl_gui_frontend_services=>get_sapgui_workdir
              Changing SAPWORKDIR = WorkDir Exceptions Others = 1.

 

          "-Create Python script file-----------------------------------
            Concatenate WorkDir '\Python27\Test.py' Into FileName.
            Call Method Of oScriptX 'WriteFile' Exporting #1 = FileName
              #2 = Buffer.
            Flush.

 

          "-Execute Python script---------------------------------------
            Call Method Of oScriptX 'Shell' = rc Exporting
              #1 = 'Python27\python.exe' #2 = 'Python27\Test.py'
              #3 = SW_SHOWNORMAL #4 = 1.
            Flush.

 

          "-Read the input from the memory map file---------------------
            Call Method Of oScriptX 'FileMapRead' = RetCode
              Exporting #1 = 'SAP001' #2 = 64.
            Flush.

 

          "-Destroy memory map file-------------------------------------
            Call Method Of oScriptX 'FileMapClose' = rc
              Exporting #1 = hFileMap.
            Flush.

 

          "-Delete Python environment-----------------------------------
            Call Method Of oScriptX 'DeleteDirectory' Exporting
              #1 = 'Python27'.
            Flush.

 

          "-Write the content of the memory map file--------------------
            Write: / RetCode.

 

        EndIf.

 

        Free Object oScriptX.

      EndIf.

 

"-End-------------------------------------------------------------------

 

zPython.jpg

 

Benefits

  1. Zero install, only copy.
  2. No admin rights necessary.
  3. All activities are in the user space only.
  4. These methods works perfect in protected and restricted environments.
  5. ABAP function modules contains all you need.
  6. No admin activities necessary. All you need you get with a simple call of an ABAP function module.

 

Good scripting.

 

Cheers

Stefan

New GuiListControl Class Iniside SAP GUI Scripting API

$
0
0

Hello community,

 

I compared the SAP GUI Scripting API version 7300.24.249 from the SAP GUI for Windows PL4 with the version 7300.26.249 from the PL6 and I found a new class called GuiListControl.

 

$CLSID_SAPFEWSELib_GuiListControl = GUID$("{CC75EA97-3DB1-4BDF-9791-89D09B1800A0}")

$IID_SAPFEWSELib_ISapListControlTarget = GUID$("{6E824989-726A-45EE-9FF0-52DC1A41D8D4}")

 

And here the methods:

 

' Interface Name  : ISapListControlTarget

' Class Name      : GuiListControl

' ClassID         : $CLSID_SAPFEWSELib_GuiListControl

Interface IDBind ISapListControlTarget

    Member Call SetFocus <32024> ()

    Member Call Visualize <32039> (In On As Integer<0>, Opt In InnerObject As Variant<1>) As Integer

    Member Call DumpState <31194> (In InnerObject As WString<0>) As IDispatch

    Member Call ShowContextMenu <32068> ()

    Member Call FindById <32029> (In Id As WString<0>, Opt In Raise As Variant<1>) As IDispatch

    Member Call FindByName <32026> (In Name As WString<0>, In Type As WString<1>) As IDispatch

    Member Call FindByNameEx <32034> (In Name As WString<0>, In Type As Long<1>) As IDispatch

    Member Call FindAllByName <32035> (In Name As WString<0>, In Type As WString<1>) As IDispatch

    Member Call FindAllByNameEx <32036> (In Name As WString<0>, In Type As Long<1>) As IDispatch

    Member Call SelectContextMenuItem <34100> (In FunctionCode As WString<0>)

    Member Call SelectContextMenuItemByText <34101> (In Text As WString<0>)

    Member Call SelectContextMenuItemByPosition <34102> (In PositionDesc As WString<0>)

    Member Call SetSelectionID <1> (In i As Long<0>)

    Member Call GetSelectionID <2> () As Long

    Member Call GetSelectionText <3> () As WString

    Member Call GetTextFromID <4> (In idVal As Long<0>) As WString

    Member Call SetInputControlText <5> (In ISapListControlTarget As WString<0>) As Integer

    Member Call GetInputControlText <6> () As WString

    Member Get Name <32001> () As WString

    Member Get Type <32015> () As WString

    Member Get TypeAsNumber <32032> () As Long

    Member Get ContainerType <32033> () As Integer

    Member Get Id <32025> () As WString

    Member Get Parent <32038> () As IDispatch

    Member Get Text <32000> () As WString

    Member Let Text <32000> ()

    Member Get Left <32003> () As Long

    Member Get Top <32004> () As Long

    Member Get Width <32005> () As Long

    Member Get Height <32006> () As Long

    Member Get ScreenLeft <32046> () As Long

    Member Get ScreenTop <32047> () As Long

    Member Get Tooltip <32008> () As WString

    Member Get Changeable <32009> () As Integer

    Member Get Modified <32030> () As Integer

    Member Get IconName <32037> () As WString

    Member Get AccTooltip <32042> () As WString

    Member Get AccLabelCollection <32043> () As IDispatch

    Member Get AccText <32044> () As WString

    Member Get AccTextOnRequest <32045> () As WString

    Member Get ParentFrame <32050> () As IDispatch

    Member Get IsSymbolFont <32061> () As Integer

    Member Get DefaultTooltip <32069> () As WString

    Member Get Children <32019> () As IDispatch

    Member Get SubType <33700> () As WString

    Member Get CurrentContextMenu <33701> () As IDispatch

    Member Get Handle <33702> () As Long

    Member Get AccDescription <33703> () As WString

    Member Get OcxEvents <33705> () As IDispatch

    Member Get DragDropSupported <33706> () As Integer

End Interface

 

It contains a lot of new methods for the SAP list control. Cool...

 

Cheers

Stefan

How to Register Any COM Library On-The-Fly Without Admin Rights

$
0
0

Hello community,

 

last week I introduced here the possibility how to register a COM library on-the-fly without admin rights with ABAP.

 

It is also possible to use the same method inside any COM-enabled scripting language.

 

Here an example how to use it with VBScript:


'-Begin-----------------------------------------------------------------

 

  '-Directives----------------------------------------------------------
    Option Explicit

 

  '-Variables-----------------------------------------------------------
    Dim Reg, DX, res, rc
 
  '-Main----------------------------------------------------------------
    Set Reg = CreateObject("RegisterX")
    If IsObject(Reg) Then
     
      Reg.About

 

      If Reg.DLLRegisterServer("", _
        "{89565275-A714-4a43-912E-978B935EDCCC}", _
        "", "D:\Programme\RegisterX\DynWrapX.dll", _
        "DynamicWrapperX", "", "", "") = 1 Then

 

        Set DX = CreateObject("DynamicWrapperX")

 

        If IsObject(DX) Then

 

          DX.Register "kernel32", "Beep", "i=uu"
          DX.Beep 800, 1000

 

          DX.Register "user32.dll", "MessageBoxW", "i=hwwu", "r=l"
          res = DX.MessageBoxW(0, "Hello, world!", "Test", 4)
         
          Set DX = Nothing
         
        End If

 

        rc = Reg.DLLUnregisterServer("", _
          "{89565275-A714-4a43-912E-978B935EDCCC}", "", _
          "DynamicWrapperX", "")

 

      End If
     
      Set Reg = Nothing

 

    End If

 

'-End-------------------------------------------------------------------

 

On the same way it is possible to use it with SAP GUI Scripting.

 

You can register RegisterX with the command rundll32 RegisterX,RegisterServer Path [/S], it is also possible without admin rights.

 

You find RegisterX here.

 

Cheers

Stefan

UPX Squeezed ActiveX Libraries in Scripting Language Context

$
0
0

Hello community,

 

I use the Universal Packer for eXecutables (UPX) to squeeze any libraries, also the ActiveX libraries of the SAP GUI for Windows, to connect an SAP system. Here a link to another post which discribes UPX in the context of SAP NetWeaver RFC libraries.

 

Intermission: In this context here a link to a question about the future of the ActiveX components.

 

I check the unicode and non-unicode ActiveX components, with the following result:

 

  1. Non-unicode
    wdobabi.ocx, wdtaocx.ocx, wdtfuncs.ocx, wdtlog.ocx and librfc32.dll uses in a normal case 13,840 k, but if there are packed with UPX it uses 3,947 k. You can save 71.5% space.
  2. Unicode
    wdobapiU.ocx, wdtaocxU.ocx, wdtfuncU.ocx, wdtlog.ocx, librfc32U.dll, libsapu16vc100.dll and the international components for unicode icudt34.dll, icuin34.dll and icuuc34.dll uses in a normal case 27,826 k, but if there are packed with UPX is uses 7,515 k. You can save 73% space.

 

In both cases all libraries works well and without any problems in any script language which are com-enabled. I think it is a benefit to squeeze the libraries, without any disadvantages.

 

Good squeezing.

 

Cheers

Stefan

How to Check the Existence of an Object Without Exception Messagebox

$
0
0

Hello community,

 

here a method how to check the existence of an object in SAP GUI Scripting. In a normal case, if an object not exists, you get an exception error in a messagebox and the SAP GUI script terminate immediately. With this method you can choose whether the SAP GUI script terminate or not. Here the source:


'-Begin-----------------------------------------------------------------

 

  '-Directives----------------------------------------------------------
    Option Explicit
    On Error Resume Next

 

  '-Global Variables----------------------------------------------------
    Dim SapGuiAuto, application, connection, session, QuitFlag

 

  '-Class cCheck--------------------------------------------------------
    Class cCheck

 

      '-Instance Variables----------------------------------------------     
        Dim CmdField

 

      '-Method Exe------------------------------------------------------
        Public Sub Exe(ByVal Cmd)
          CmdField = Split(Cmd, """", -1, 1)
          session.findById(CmdField(1))
          ExecuteGlobal Cmd
        End Sub

 

      '-Method ErrCatch-------------------------------------------------
        Private Sub ErrCatch
          If Err.Number = 0 Then Exit Sub
          Select Case Err.Number
            Case 619
              If MsgBox("Run-time error " & Err.Number & _
                " occurred." & vbCrLf & Err.Description & vbCrLf & _
                "ID: " & CmdField(1) & vbCrLf & vbCrLf & "Abort?", _
                vbYesNo, "Error on " & Err.Source) = vbYes Then
                QuitFlag = True
              End If
            Case Else
              If MsgBox("Run-time error " & Err.Number & _
                " occurred." & vbCrLf & Err.Description & vbCrLf & _
                vbCrLf & "Abort?", vbYesNo, "Error on " & _
                Err.Source) = vbYes Then
                QuitFlag = True
              End If
          End Select
          Err.Clear
        End Sub

 

      '-Destructor------------------------------------------------------
        Private Sub Class_Terminate
          ErrCatch
        End Sub

 

    End Class

 

  '-Sub C---------------------------------------------------------------
    Sub C(ByVal Cmd)
      Dim Check
      If QuitFlag Then WScript.Quit()
      Set Check = New cCheck : Check.Exe Cmd : Set Check = Nothing
    End Sub

 

  '-Main----------------------------------------------------------------
    If Not IsObject(application) Then
      Set SapGuiAuto = GetObject("SAPGUI")
      Set application = SapGuiAuto.GetScriptingEngine
    End  If

 

    If Not IsObject(connection) Then
      Set connection = application.Children(0)
    End If

 

    If Not IsObject(session) Then
      Set session = connection.Children(0)
    End If

 

    If IsObject(WScript) Then
      WScript.ConnectObject session, "on"
      WScript.ConnectObject application, "on"
    End If

 

  C "session.findById(""wnd[0]/usr/txtRSYST-MANDT"").text = ""001"""
  '-The following object doesn't exists---------------------------------

  C "session.findById(""wnd[0]/usr/txtRSYST-MAND"").text = ""001"""
  C "session.findById(""wnd[0]/usr/txtRSYST-BNAME"").text = ""bcuser"""
  C "session.findById(""wnd[0]/usr/pwdRSYST-BCODE"").text = ""minisap"""
  C "session.findById(""wnd[0]/usr/txtRSYST-LANGU"").text = ""EN"""
  C "session.findById(""wnd[0]/tbar[0]/btn[0]"").press"

 

'-End-------------------------------------------------------------------

 

The sub procedure C sends the SAP GUI Scripting command as string parameter and delivers it to the method Exe of the Check class. This method call the method FindById and if it doesn't find, an exception is thrown. Now the class was destroyed and the destructor calls the method ErrCatch. This method opens a messagebox and sets a global flag. If the flag is set, with the positive answer of the messagebox, the script terminate immediately or runs again with a negative answer. In the example above I check the objects of the logon screen.

 

I think this method is a way to make SAP GUI Scripting more robust for the work in different SAP environments.

 

Cheers

Stefan


Bebo, a Control and Activity Pad with Script Support for SAP Sessions

$
0
0

Hello community,

 

a long time ago I introduced Bebo here. Now a little refresh and reminder, because I develop Bebo since three years and it is a very reliable and  stable product. Bebo is a small utility to watch, navigate and control all SAP sessions. With Bebo you see all sessions clearly arranged in a tree. Also you can direct execute a transaction or a script to the selected session. The available transaction codes and other possibilities are an easy and individual customizing in a preference file. With Bebo you can organize your favorite transaction codes, activities and scripts in a tree as you want - one time for all application servers. Bebo helps you in the jungle of sessions and connections - it is a point of view.

 

Bebo is freeware and you can find it here.

 

Suggestions and comments are welcome.

 

Cheers

Stefan

How to Build an HTA/HTML UI to Code and Execute ABAP Reports

$
0
0

Hello community,

 

a longer time ago I introduced CCo (COM Connector) here. Later I presented here the possibility how to program and run an ABAP Report with the scripting language VBScript and CCo. Here is now a development with the same possibility and additional an UI to code the ABAP report. It is a hypertext application.

 

<html>  <head>    <title>      Execute an ABAP Report    </title>    <hta:application applicationname="ABAPReport" id="ABAPReport"      singleinstance="yes" border="thick" borderStyle="sunken"       version="1.0" />    <script language="VBScript">      '-Directives------------------------------------------------------        Option Explicit      '-Constants-------------------------------------------------------        Const RFC_OK = 0      '-ABAPExec--------------------------------------------------------        Sub ABAPExec()          '-Variables---------------------------------------------------            Dim SAP, hRFC, rc, hFuncDesc, hFunc, ABAP, i, hRow, hTable            Dim RowCount, charBuffer, Result          document.Output.Result.value = ""          Set SAP = CreateObject("COMNWRFC")          If Not IsObject(SAP) Then            Exit Sub          End If          hRFC = SAP.RfcOpenConnection( _            "ASHOST=" & document.ConnParams.ASHost.value & ", "  & _            "SYSNR=" & document.ConnParams.SysNr.value & ", " & _            "CLIENT=" & document.ConnParams.Client.value & ", " & _            "USER=" & document.ConnParams.User.value)          If hRFC = 0 Then            Set SAP = Nothing            Exit Sub          End If          hFuncDesc = SAP.RfcGetFunctionDesc(hRFC, _            "RFC_ABAP_INSTALL_AND_RUN")          If hFuncDesc = 0 Then            rc = SAP.RfcCloseConnection(hRFC)            Set SAP = Nothing            Exit Sub          End If          hFunc = SAP.RfcCreateFunction(hFuncDesc)          If hFunc = 0 Then            rc = SAP.RfcCloseConnection(hRFC)            Set SAP = Nothing            Exit Sub          End If          '-Writes the report into the PROGRAM table--------------------            If SAP.RfcGetTable(hFunc, "PROGRAM", hTable) = RFC_OK Then              ABAP = Split(document.ABAP.Report.value, vbCrLf)              For i = 0 To UBound(ABAP) - 1                If Trim(ABAP(i)) <> "" Then                  hRow = SAP.RfcAppendNewRow(hTable)                  rc = SAP.RfcSetChars(hRow, "LINE", ABAP(i))                End If              Next            End If          If SAP.RfcInvoke(hRFC, hFunc) = RFC_OK Then            '-Gets the result from the WRITES table---------------------              If SAP.RfcGetTable(hFunc, "WRITES", hTable) = RFC_OK Then                rc = SAP.RfcGetRowCount(hTable, RowCount)                rc = SAP.RfcMoveToFirstRow(hTable)                For i = 1 To RowCount                  hRow = SAP.RfcGetCurrentRow(hTable)                  rc = SAP.RfcGetChars(hRow, "ZEILE", charBuffer, 256)                  Result = Result & Trim(charBuffer) & vbCrLf                  If i < RowCount Then                    rc = SAP.RfcMoveToNextRow(hTable)                  End If                Next                '-Shows the result in the output area-------------------                  document.Output.Result.value = Result              End If          End If          rc = SAP.RfcDestroyFunction(hFunc)          rc = SAP.RfcCloseConnection(hRFC)          Set SAP = Nothing        End Sub              '-onLoad----------------------------------------------------------        Sub Window_onLoad()          window.moveTo 25,25          window.resizeTo 680,710        End Sub      </script>  </head>  <body>    <h1>      Execute an ABAP Report    </h1>    <form action="ConnParams.htm" name="ConnParams">      <p>        ASHost:         <input name="ASHost" type="text" size="10" maxlength="10"          value="ABAP">         SysNr.:         <input name="SysNr" type="text" size="2" maxlength="2"          value="00">         Client:         <input name="Client" type="text" size="3" maxlength="3"          value="001">         User:         <input name="User" type="text" size="12" maxlength="12"          value="BCUSER">      </p>    </form>    <input type="button" value="Execute ABAP Report"      onClick='ABAPExec()'>        <form action="ABAP.htm" name="ABAP">      <p><textarea name="Report" cols="72" rows="18" wrap="hard">
"-Begin-----------------------------------------------------------------  Report zTest Line-Size 72.  Write: 'Hello World from'.  Write: sy-sysid.
"-End-------------------------------------------------------------------</textarea>      </p>    </form>    <form action="Output.htm" name="Output">      <p>        <textarea name="Result" cols="72" rows="9" wrap="soft" readonly>      </textarea>      </p>    </form>  </body> </html>

 

ABAP1.jpg

As you can see it is very easy to build an external editor for ABAP reports, with the possibilities of HTML and CCo.

 

Cheers

Stefan

How to use Windows PowerShell Script inside ABAP

$
0
0

Hello community,

 

Windows PowerShell is a mix of command-line shell and scripting language. You find more Information about PowerShell here and here.

 

With the free COM library ActiveXPosh.dll from SAPIEN you can also use PowerShell inside ABAP.

 

Here an example how to get all services and its state.

 

"-Begin-----------------------------------------------------------------
  Program zPSTest.

    "-TypePools---------------------------------------------------------
      Type-Pools OLE2 .

    "-Constants--------------------------------------------------------
      Constants OUTPUT_CONSOLE Type i Value 0.
      Constants OUTPUT_WINDOW Type i Value 1.
      Constants OUTPUT_BUFFER Type i Value 2.

    "-Variables---------------------------------------------------------
      Data PS Type OLE2_OBJECT.
      Data Result Type i Value 0.
      Data strResult Type String Value ''.
      Data tabResult Type Table Of String.

    "-Main--------------------------------------------------------------
      Create Object PS 'SAPIEN.ActiveXPoSH'.

      If sy-subrc = 0 And PS-Handle <> 0 And PS-Type = 'OLE2'.

        Call Method Of PS 'Init' = Result Exporting #1 = 0.

        If Result = 0.

          Call Method Of PS 'IsPowerShellInstalled' = Result.

          If Result <> 0.

            Set Property Of PS 'OutputMode' = OUTPUT_BUFFER.

            Call Method Of PS 'Execute' Exporting
              #1 = 'Get-WmiObject -class Win32_Service | Format-Table -property Name,State'.

            Call Method Of PS 'OutputString' = strResult.

            Split strResult At cl_abap_char_utilities=>cr_lf
              Into Table tabResult.

            Loop At tabResult Into strResult.
              Write: / strResult.
            EndLoop.

          EndIf.

        EndIf.

        Free Object PS.
      EndIf.

"-End-------------------------------------------------------------------

 

You can use with PowerShell all dotNET and Windows standard libraries. On this way you can extend your possibilities.

 

Cheers

Stefan

Control Visualizer

$
0
0

Hello community,

 

we all know the good old Scripting Wizard, which is not longer supported since Windows 7 and SAP GUI for Windows 7.20 PL?.

 

But SAP offers a Control Visualizer, maybe a replacment.

 

If you press the buttons  Ctrl  +  Shift  +  Z at the same time, it opens an additional window, called CMyControl Visualizer.

Hint: It is the Z key on keyboard with German keyboard layout.

 

Visualizer.jpg

You got the field name, the style, the content and some other technical stuff about the selected control.

I am not really sure if this is a replacment, but it seems a little bit.

 

Hint: It works not with any screen and it is not very stable.

 

Cheers

Stefan

Automation of SAP Netweaver portal

$
0
0

'Automating the SAP netweaver portal - The Everest of Automation!

'

'There are a few articles on the web discussing the automation of the SAP Portal - some even saying its a myth.

'

'Ok it is possible using VBA..(Excel). Could be adapted for vb script.

'

'This assumes you have some knowledge of HTML DOM and general automation.

'

'

'1. Get the URL of your portal. Sometimes the portal window does not display the address bar.

'This example will get the URL of a window with "Home - SAP NetWeaver Portal" (depending on your env).

'Open a portal and run this function.

 

 

Debug.Print oGetPortal.LocationURL

 

Function oGetPortal( _

Optional sWindowTitle AsString = "Home - SAP NetWeaver Portal" _

) AsObject

 

 

   Set objShellApp = CreateObject("Shell.Application")

   ForEach objWindow In objShellApp.Windows

  DoEvents

   If LCase(objWindow.LocationName) = LCase(sWindowTitle) Then

   Set oGetPortal = objWindow

   ExitFor

   EndIf

   Next

   Set objShellApp = Nothing

   Set objWindow = Nothing

EndFunction

 

 

'2 For automation you probably want to create a new instance of the IE portal rather than attach to

'an existing window. The Portal often runs on an intranet.

'In windows 7 the IE object automatically detaches from intranet pages - not very useful for automation.

'

'So the below code works around this issue & should work on earlier windows versions and non intranet pages

'it also opens up the portal in an IE window with an address bar and is easier to get access to the IE developer tools.

 

 

Debug.Print oGetLatestPortal.LocationURL

 

PrivateDeclareSub Sleep Lib"kernel32" (ByVal dwMilliseconds AsLong)

PrivateDeclareFunction GetForegroundWindow Lib"user32" () AsLong

Function oGetLatestPortal( _

  Optional sURL AsString = "http://myportalpath/portal#", _

  Optional sWindowTitle AsString = "Home - SAP NetWeaver Portal") AsObject

 

   Dim IE As InternetExplorer

   Set IE = New InternetExplorer

   ' only works for about 5 portal windows

 

  IE.Navigate sURL

   Dim hwnd AsLong

  hwnd = GetForegroundWindow() ' get latest IE window

   Set IE = Nothing  ' work around for windows 7 issue

 

  i = 0

   DoWhile i < 10And IE IsNothing

 

  i = i + 1

   Set objShellApp = CreateObject("Shell.Application")

   ForEach objWindow In objShellApp.Windows

  DoEvents

   If LCase(objWindow.LocationName) = LCase(sWindowTitle) Then

       If objWindow.hwnd = hwnd Then'active IE window if more than one with same title

                Set IE = objWindow

       EndIf

     EndIf

   Next

  DoEvents

  Sleep 100

   Loop

 

 

   If IE IsNothingThen

  MsgBox "nothing"

ExitFunction

  End If

 

   Set oGetLatestIE = IE

 

EndFunction

 

'3. Wait for IE page to load. You cannot do any automation until after

'the page is loaded. This function returns true if the page or frames top level is loaded (frames discussed later)

 

Debug.Print lWait(oGetLatestPortal)

 

Function lWait(LOIE AsObject) AsBoolean

  Dim t1 AsLong

  Dim t2 AsLong

  OnErrorResumeNext

  t1 = Timer

  t2 = t1 + 60

  Do

   If Timer > t2 Then lWait = False: ExitFunction

  If VarType(LOIE.Document) = vbString ThenExitDo

  Loop

  Do

   If Timer > t2 Then lWait = False: ExitFunction

  If LOIE.Busy = FalseThenExitDo

  Loop

  Do

   If Timer > t2 Then lWait = False: ExitFunction

  If VarType(LOIE.Document.readyState) = "C"ThenExitDo

  Loop

  Do

   If Timer > t2 Then lWait = False: ExitFunction

  If LOIE.Document.readyState = "complete"ThenExitDo

  Loop

  lWait = True

EndFunction

 

 

'4. Using developer tools in IE8+ (F12) with the window you just opened using the above code.

'Use the IE inspect tool (arrow) to click on the field or link/field/button you want to automate. This will

'expand the HTML DOM and show the HTML tag corresponding to the field. If you can see the tag you can automate

'it! But it can be tricky.

'

'5. Clicking on a link. Now that you have open a portal window you want to do something usually click on a link.

'Using the developer tools in IE. Find the link you want. If the link you want is inside a HTML form or frame

'tag see further on.

 

 

lWait IE

Set link = IE.Document.getElementById("MyLink_1_1") ' Can be a div or anchor

link.click

 

' Waiting for elements to appear.

'

' Even though you call lWait and IE is ready, the portal may be doing things. eg.

' displaying spinners (etc) Sometimes you must wait for the element to appear.

' Note elements can be forms, frames, links or fields or anything.

'

' safer way to get a element that will wait until it appears

Dim element AsObject

Dim t1 AsLong

Dim t2 AsLong

 

t1 = Timer

t2 = t1 + 10' secs

 

While element IsNothing

  DoEvents

   If Timer > t2 Then

  MsgBox "timeout"

   ExitDo

   EndIf

' note, IEdoc can be IE.Document, SubFrame.contentWindow.Document or SubForm.Document (discussed later)

 

   Set element = IEdoc.getElementById("elementid")

 

Wend

 

'If you still have problems try to get an element preceeding the element you want

'Use the VB debugger and also put sleeps in and use while loops as shown also you must get any

' forms or frames preceeding the element.

'

'

'

'6. Elements in Forms or Frames

'If you still can't get the element by elementbyid or by looping through getElementsByTagName,

'It could be because the field you want is in a form or frame.

'You should get a reference to any forms or frame preceeding the element first. Use F12 developer tools

'to find out if there are any precedding forms or frames.

 

 

'6 a.HTML frames

'Get an obj reference to a html frame

 

Dim subframe1 AsObject

' Assuming you have any preceeding Forms or Frames

Set subframe1 = IE.Document.getElementById("frameid") ' example

 

lWait subframe1.contentWindow

 

'Once you get a obj reference to a frame you must get the sub document

'before you can do any further searches

 

Dim myframedocument AsObject

Set myframedocument = subframe1.contentWindow.Document

 

Set subframe2 = myframedocument.getElementById("frameid2") ' example

 

'

'6b HTML forms

'

'A HTML Form is similar, again you must get any preceeding Forms or Frames

Dim subform AsObject

Set subform = IE.Document.getElementById("formid") ' example

 

Dim myformdocument AsObject

Set myformdocument = subform.Document

 

Set mylink = myformdocument.getElementById("mylink") ' example

 

 

'7.Dynamic Content. In the portal HTML elements id's can change depending on the context ie whether certain

'sections are data driven or due to different user's role, certain elements are displayed. In the previous

'example Link_1_1 might be a different menu option on one users login to another. So in these cases

'you need to write more generic code. 2 examples.

'

' using a tags attributes

For k1 = 0To IE.Document.links.Length - 1

   If IE.Document.links.Item(k1).getAttribute("title") = "Show Attachments"Then

 

 

IE.Document.links.Item(k1).Click

ExitFor

 

   EndIf

 

Next k1

 

 

' Loop through a table looking for a link's screen text

Set oTbl = IE.Document.getElementById("myNavigationTable")

Set oTBody = oTbl.getElementsByTagName("TBODY").Item(0)

Set oTRow = oTBody.getElementsByTagName("TR").Item(0)

Set oTds = oTRow.getElementsByTagName("TD")

 

ForEach oTd In oTds

  DoEvents

   If InStr(oTd.innertext, "Link Text") > 0Then

   Set link = oTd.getElementsByTagName("A").Item(0)

   ExitFor

   EndIf

 

Next oTd

link.Click

 

 

 

'8.If you hit a back button element on a page you might have to

're-establish VB objects in your code as sometimes they lose reference.

'

'9.Finally this is not a turn key solution - ideally a function could be written to find a control

'by searching the DOM tree handling all frames and forms and waits

'

'I hope this post helps

How an SAP GUI Script is Executed

$
0
0

Hello community,

 

there are several ways to execute an SAP GUI script:

 

  1. Via SAP GUI recorder, press Alt+F12, now choose the menu item Script Recording and Playback, load the script file and press Playback button.
  2. Via Drag'n'Drop with the script file to the session where the script should be executed.
  3. Via double click on the script file in the Windows Explorer.
  4. Via the command line in a console window with the command wscript.exe or cscript.exe and the name of the script file.

 

This are four ways but technically this are only two ways. One and two works technically equal, also as three and four.

 

One and two executes the script via MSScriptControl. This means that the SAP GUI for Windows instanciate the class MSScriptControl.ScriptControl from the msscript.ocx library and executes the SAP GUI Script as statement - I think.

 

To check it out I create the following test script:

 

'-Begin-----------------------------------------------------------------

 

  If Not IsObject(application) Then

    Set SapGuiAuto  = GetObject("SAPGUI")

    Set application = SapGuiAuto.GetScriptingEngine

  End If

 

  If Not IsObject(connection) Then

    Set connection = application.Children(0)

  End If

 

  If Not IsObject(session) Then

    Set session    = connection.Children(0)

  End If

 

  session.findById("wnd[0]/tbar[0]/okcd").text = "/nSE16"

  session.findById("wnd[0]/tbar[0]/btn[0]").press

 

  WScript.Sleep 500

  WScript.Echo "Test"

 

'-End-------------------------------------------------------------------

 

The reaction with one and two are

001.JPG

To see reaction in a simulated context of SAP GUI for Windows I create the following test script:

 

'-Begin-----------------------------------------------------------------

 

  '-Directives----------------------------------------------------------

    Option Explicit

 

  '-Variables-----------------------------------------------------------

    Dim ScrCtrl, Cmd

 

  '-Main----------------------------------------------------------------

    Set ScrCtrl = CreateObject("MSScriptControl.ScriptControl")

    If IsObject(ScrCtrl) Then

 

      ScrCtrl.AllowUI = vbTrue

      ScrCtrl.Language = "VBScript"

 

      Cmd = "WScript.Echo ""Hello World"""

      ScrCtrl.ExecuteStatement Cmd

 

    End If

 

'-End-------------------------------------------------------------------

 

The reaction is the same as one and two

 

002.JPG

This knowledge gives us now a good base to understand the behaviour of the different executions forms better. On the one hand via MSScriptControl, on the other hand via WScript.

 

Hint: If you work with WScript you must define the connection (application.Children(x)) and session (connection.Children(y)) with correct values - here x and y as example. The standard defines always 0 - which means connection 0 and session 0, the first connection and session in the pool of all open connections and sessions.

 

Cheers

Stefan

A Look Behind the Curtain - Lift the veil from saplogon.exe

$
0
0

Hello community,

 

the SAP logon program saplogon.exe is the centre of rotation of all communication between the SAP GUI for Windows and the SAP application server. The SAP logon is the one and only. If you want to know more details about the activities of the saplogon.exe process, you have the possiblity to use Microsofts Process Monitor from www.sysinternals.com. Set the filter to the process name saplogon.exe.

 

001.JPG

If you activate the capture, you can see a lot of details of activities of the following operation areas:

  1. Access to the file system.
  2. Access to the registry.
  3. Monitoring of the process and its threads, also DLL and device driver access.
  4. Network activities.

 

With this way it is e.g. very easy to detect the procedure of the execution of a SAP GUI Script via the playback function of the SAP GUI Scripting recorder - see also here.

002.JPG

If you want to know and to learn more about the activities of the saplogon.exe process, use the Process Monitor. It is very good to understand how a lot of things work.

 

Cheers

Stefan


How to Combine Windows PowerShell Script and SAP GUI Scripting

$
0
0

Hello community,

 

I presented here the possibility how to use Windows PowerShell Script inside ABAP. Also is it possible to use Windows PowerShell in combination with SAP GUI Scripting. You Need therefor the free COM library ActiveXPosh.dll from SAPIEN.

 

Here an example how to use a DLL call from the Windows API inside an SAP GUI script:


'-Begin-----------------------------------------------------------------
'-
'- Example how to use a DLL call via PowerShell with component
'- ActiveXPosh inside SAP GUI Scripting
'-
'-----------------------------------------------------------------------

 

 

  '-Directives----------------------------------------------------------
    Option Explicit

 

  '-Constants-----------------------------------------------------------
    Const OUTPUT_CONSOLE = 0
    Const OUTPUT_WINDOW = 1
    Const OUTPUT_BUFFER = 2

 

  '-Variables-----------------------------------------------------------
    Dim PSCode

 

  '-Sub Add-------------------------------------------------------------
    Sub Add(Code)
      PSCode = PSCode & Code & vbCrLf
    End Sub

 

  '-Sub Main------------------------------------------------------------
    Sub Main()

 

      '-Variables-------------------------------------------------------
        Dim SapGuiAuto, application, connection, session
        Dim PS

 

      If Not IsObject(application) Then
        Set SapGuiAuto = GetObject("SAPGUI")
        Set application = SapGuiAuto.GetScriptingEngine
      End If
 
      If Not IsObject(connection) Then
        Set connection = application.Children(0)
      End If

 

      If Not IsObject(session) Then
        Set session = connection.Children(0)
      End If

 

      If Not IsObject(PS) Then
        Set PS = CreateObject("SAPIEN.ActiveXPoSH")
        If PS.Init(vbFalse) <> 0 Then
          MsgBox "Can't instantiate PowerShell engine"
          Exit Sub
        End If
        If PS.IsPowerShellInstalled = vbFalse Then
          Msgbox "PowerShell is not installed"
          Exit Sub
        End If
      End If

 

      PS.OutputMode = OUTPUT_BUFFER

 

'-PowerShell Begin------------------------------------------------------
PSCode = ""

 

Add "$sig = @"""
Add "[DllImport(""User32.dll"")]"
Add "public static extern int MessageBoxA(int hWnd, String Text, String Caption, int Type);"
Add """@;"
Add "$DLL_User32 = Add-Type PBexpMsgBox -MemberDefinition $sig -PassThru"
Add "$DLL_User32::MessageBoxA(0, ""Hello World"", ""From WinAPI"", 0);"

 

PS.Execute(PSCode)
'-PowerShell End--------------------------------------------------------

 

      session.findById("wnd[0]/tbar[0]/okcd").text = "/nSE38"
      session.findById("wnd[0]/tbar[0]/btn[0]").press

 

    End Sub

 

  '-Main----------------------------------------------------------------
    Main()

 

'-End-------------------------------------------------------------------

 

Here an example how to use VB# (Visual Basic for dotNET) code inside SAP GUI Scripting:


'-Begin-----------------------------------------------------------------
'-
'- Example how to use a dotNET VB# code via PowerShell with component
'- ActiveXPosh inside SAP GUI Scripting
'-
'-----------------------------------------------------------------------

 

  '-Directives----------------------------------------------------------
    Option Explicit

 

  '-Constants-----------------------------------------------------------
    Const OUTPUT_CONSOLE = 0
    Const OUTPUT_WINDOW = 1
    Const OUTPUT_BUFFER = 2

 

  '-Variables-----------------------------------------------------------
    Dim PSCode

 

  '-Sub Add-------------------------------------------------------------
    Sub Add(Code)
      PSCode = PSCode & Code & vbCrLf
    End Sub

 

  '-Sub Main------------------------------------------------------------
    Sub Main()

 

      '-Variables-------------------------------------------------------
        Dim SapGuiAuto, application, connection, session
        Dim PS, str, outText

 

      If Not IsObject(application) Then
        Set SapGuiAuto = GetObject("SAPGUI")
        Set application = SapGuiAuto.GetScriptingEngine
      End If
 
      If Not IsObject(connection) Then
        Set connection = application.Children(0)
      End If

      If Not IsObject(session) Then
        Set session = connection.Children(0)
      End If

 

      If Not IsObject(PS) Then
        Set PS = CreateObject("SAPIEN.ActiveXPoSH")
        If PS.Init(vbFalse) <> 0 Then
          MsgBox "Can't instantiate PowerShell engine"
          Exit Sub
        End If
        If PS.IsPowerShellInstalled = vbFalse Then
          Msgbox "PowerShell is not installed"
          Exit Sub
        End If
      End If

 

      PS.OutputMode = OUTPUT_BUFFER

 

'-PowerShell Begin------------------------------------------------------
PSCode = ""

 

Add "$VBCode = @"""

 

'-VB# Begin-------------------------------------------------------------

Add "Option Strict On"

 

Add "Imports System"

Add "Imports Microsoft.VisualBasic"

 

Add "Namespace VBCode"

 

Add "  Public Class VB"

 

Add "    Public Shared Function Hello1() As String"
Add "      Return ""Hello World!"""
Add "    End Function"

 

Add "    Public Function Hello2(ByVal Name As String) As String"
Add "      Return ""Hello "" & Name & ""!"""
Add "    End Function"

 

Add "    Public Sub Hello3(ByVal Name As String)"
Add "      MsgBox(Name, MsgBoxStyle.OkOnly, ""Hello"")"
Add "    End Sub"

 

Add "  End Class"

 

Add "End Namespace"

'-VB# End---------------------------------------------------------------

 

Add """@;"

Add "Add-Type -TypeDefinition $VBCode -Language VisualBasic"
Add "$VB = new-Object VBCode.VB"

Add "[VBCode.VB]::Hello1()"
Add "$VB.Hello2(""Stefan"")"
Add "$VB.Hello3(""Stefan"")"

 

PS.Execute(PSCode)
'-PowerShell End--------------------------------------------------------

 

      For Each str In PS.Output
        outText = outText & str & vbCrLf
      Next
      MsgBox outText

 

      session.findById("wnd[0]/tbar[0]/okcd").text = "/nSE16"
      session.findById("wnd[0]/tbar[0]/btn[0]").press

    End Sub

 

  '-Main----------------------------------------------------------------
    Main()

 

'-End-------------------------------------------------------------------

 

Also you have the possibility to use all commands from PowerShell itself.

 

Expand your SAP GUI Scripts with the possibilities of PowerShell Script.

 

Cheers

Stefan

Tip: Write each table with SAP GUI Scripting to a CSV file

$
0
0

Hello community,
here is a SAP GUI Script to write each table in a file in CSV (Comma Separated Value) format. Use only one sub call

ReadTableInFile "SFLIGHT", "C:\\Dummy\\SFlight.csv"

in your SAP GUI script and you get the table SFLIGHT in the file C:\Dummy\SFlight.csv.
I think it is a good way, if you need to download data tables e.g. to analyze data constellations. So you can download a few data tables without any manual activities.

 

Here you find a description how you can manipulate very big data files and the aspect to connect them to a Microsoft Access database for a fast and flexible

analysis - it is in German language.

 

The following source code is full commented, so I hope it is easy to unterstand how it works.

Any comments are welcome.

 

Cheers
Stefan

'-Begin-----------------------------------------------------------------
'-
'- Author: Stefan Schnell
'- Page: www.stschnell.de
'- Date: 2012/03/31
'-
'-----------------------------------------------------------------------

  '-ReadTableInFile-----------------------------------------------------
    Sub ReadTableInFile(TableName, FileName)

      '-Reset the session-----------------------------------------------
        session.findById("wnd[0]/tbar[0]/okcd").text = "/n"
        session.findById("wnd[0]/tbar[0]/btn[0]").press

      '-Open TAC SE16---------------------------------------------------
        session.findById("wnd[0]/tbar[0]/okcd").text = "/nSE16"
        session.findById("wnd[0]/tbar[0]/btn[0]").press

      '-View table------------------------------------------------------
        session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").text = _
          TableName
        session.findById("wnd[0]/tbar[1]/btn[7]").press
        session.findById("wnd[0]/tbar[1]/btn[8]").press

      '-Set display to ALV Grid view------------------------------------   
        '-Open user specific parameters dialog--------------------------
        '-
        '- Attention: Here is a language specific code, customize it
        '-
        '---------------------------------------------------------------
          Set Menu = session.findById("wnd[0]/mbar")
          Set Einstellungen = Menu.FindByName("Einstellungen", "GuiMenu")
          Set BenutzerPar = Einstellungen.FindByName("Benutzerparameter...", _
            "GuiMenu")
          BenutzerPar.Select()

        '-Set the display-----------------------------------------------
          Set ALVGridView = session.findById("wnd[1]/usr/tabsG_TABSTRIP/" & _
            "tabp0400/ssubTOOLAREA:SAPLWB_CUSTOMIZING:0400/radRSEUMOD-TBALV_GRID")
          If ALVGridView.Selected = vbFalse Then
            ALVGridView.select()
          End If
          session.findById("wnd[1]/tbar[0]/btn[0]").press       
        Set BenutzerPar = Nothing
        Set Einstellungen = Nothing
        Set Menu = Nothing

      '-Get rows and columns--------------------------------------------
        Set table = session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell")
        Rows = table.RowCount() - 1
        Cols = table.ColumnCount() - 1

      '-Write the table to a CSV file-----------------------------------
        Set oFile = CreateObject("Scripting.FileSystemObject")
        If IsObject(oFile) Then
          Set SFlightFile = oFile.CreateTextFile(FileName, True)
          If IsObject(SFlightFile) Then

            '-Get the title of all columns in the first line------------
              Set Columns = table.ColumnOrder()
              For j = 0 To Cols
                If j = Cols Then
                  SFlightFile.Write(CStr(Columns(j)))
                Else
                  SFlightFile.Write(CStr(Columns(j)) & ";")
                End If
              Next
              SFlightFile.WriteLine("")
 

            For i = 0 To Rows
              For j = 0 To Cols
                If j = Cols Then
                  SFlightFile.Write(table.GetCellValue(i, _
                    CStr(Columns(j))))
                Else
                  SFlightFile.Write(table.GetCellValue(i, _
                    CStr(Columns(j))) & ";")
                End If
              Next

              '-Each 32 lines actualize the grid------------------------
                If i Mod 32 = 0 Then
                  table.SetCurrentCell i, CStr(Columns(0))
                  table.firstVisibleRow = i
                End If

              '-Carriage and return after a line------------------------
                If i <> Rows Then
                  SFlightFile.WriteLine("")
                End If

            Next
            SFlightFile.Close

          End If
        End If

        Set ALVGridView = Nothing
        Set Columns = Nothing
        Set table = Nothing
    End Sub

  '-Main----------------------------------------------------------------
    If Not IsObject(application) Then
      Set SapGuiAuto = GetObject("SAPGUI")
      Set application = SapGuiAuto.GetScriptingEngine
    End If

    If Not IsObject(connection) Then
      Set connection = application.Children(0)
    End If


    If Not IsObject(session) Then
      Set session = connection.Children(0)
    End If

    '-Read the table SFLIGHT in a file----------------------------------
      ReadTableInFile "SFLIGHT", "C:\\Dummy\\SFlight.csv"

'-End-------------------------------------------------------------------

New Scripting Option in SAP GUI for Windows 7.30 PL 8

$
0
0

Hello community,

 

there is a new SAP GUI scripting option in the SAP GUI logon 7.30 PL8, called "Show native MS Windows dialogs".

 

newopt.JPG

 

The help describes it as following:

"Since Microsoft Windows' native system dialogs (Save As, Open) cannot be recorded when a script is run, they are replaced automatically with a dynpro-based dialog. You can disable this procedure by selecting option, Show Native MS Windows dialogs. The system-defined dialogs will be displayed, but cannot be recorded by the script."

 

Cool new option.

 

Cheers

Stefan

How To Execute Any File With GuiXT

$
0
0

Hello community,

 

everbody knows GuiXT - the comfortable library to individualize the SAP screens. It is standard part of the SAP GUI for Windows and you can use it without any problems. You can find more information about GuiXT here.

 

GuiXT offers the possibility to use function calls from DLLs inside a GuiXT script, with the command Call. Here an GuiXT script example how to use the Windows API function ShellExecute. On this way you can execute any file you like.

 

Cheers

Stefan

 

//-Begin----------------------------------------------------------------  //-With InputAssistant------------------------------------------------    //-Flags------------------------------------------------------------      //-ShowWindow-----------------------------------------------------        Set V[SW_HIDE] "0"        Set V[SW_SHOWNORMAL] "1"        Set V[SW_NORMAL] "1"        Set V[SW_SHOWMINIMIZED] "2"        Set V[SW_SHOWMAXIMIZED] "3"        Set V[SW_MAXIMIZE] "3"        Set V[SW_SHOWNOACTIVATE] "4"        Set V[SW_SHOW] "5"        Set V[SW_MINIMIZE] "6"        Set V[SW_SHOWMINNOACTIVE] "7"        Set V[SW_SHOWNA] "8"        Set V[SW_RESTORE] "9"        Set V[SW_SHOWDEFAULT] "10"        Set V[SW_FORCEMINIMIZE] "11"        Set V[SW_MAX] "11"    //-ShellExecute-----------------------------------------------------      Set V[hWnd] "0"      Set V[Operation] "open"      Set V[File] "Test.vbs"      Set V[Parameters] ""      Set V[Directory] "C:\Dummy"      Set V[ShowCmd] V[SW_SHOWNORMAL]      Call "ShellExecuteA" dll="shell32.dll" In="&V[hWnd]" In="&V[Operation]" In="&V[File]" In="&V[Parameters]" In="&V[Directory]" In="&V[ShowCmd]" Out="rc"  //-Without InputAssistant---------------------------------------------    //-ShellExecute-----------------------------------------------------      Call "ShellExecuteA" dll="shell32.dll" In="0" In="open" In="Test.vbs" In="" In="C:\Dummy" In="1" Out="rc"

//-End------------------------------------------------------------------

Tip: How to Code a GuiXT Conformable Dynamic Link Library (DLL)

$
0
0


Hello community,

 

I show here an example how to call the Windows API function ShellExecute inside a GuiXT script. You can call a DLL function with the command Call, look here for the technical documentation. And now I show an example, how to code your own dynamic link library (DLL) with FreeBASIC to use it inside a GuiXT script.

 

As you can see, in the section "Calling a dll function" in the technical documentation from Synactive, the Call function from GuiXT needs only pointer to strings as input and output arguments. With this knowledge I implement a DLL in FreeBASIC with one export function expMsgBox. These export function has only string arguments, two input and one output. Inside the export function I call a simple MessagBox function with the input parameters. The result of the MessageBox function I convert to a string and put it to the output argument.


'-Begin-----------------------------------------------------------------
'-
'- FreeBasic Dynamic Link Library (DLL) for GuiXT
'- Compile it with -dll option.
'-
'- Author: Stefan Schnell
'-
'-----------------------------------------------------------------------

 

  '-Includes------------------------------------------------------------
    #Include Once "windows.bi"

 

  Extern "Windows-MS"

 

    '-Function expMsgBox------------------------------------------------
      Function expMsgBox Alias "expMsgBox" (ByVal inMsg As String, _
        ByVal inTitle As String, ByVal outRes As String) As Long Export

 

        '-Variables-----------------------------------------------------
          Dim resMsgBox As Long

 

        resMsgBox = MessageBox(NULL, inMsg, inTitle, MB_YESNOCANCEL)
        outRes = Str(resMsgBox)
        expMsgBox = resMsgBox

 

      End Function

 

  End Extern

 

'-End-------------------------------------------------------------------

 

 

I call this DLL function from GuiXT with the following script:


//-Begin----------------------------------------------------------------

 

  Call "expMsgBox" dll="FreeBasic.dll" In="Hello World" In="GuiXT" Out="res"
  Message "&[res]"

 

//-End------------------------------------------------------------------

 

 

It works perfect with GuiXT.

msgbox.JPG

 

result.JPG

 

With this possibility you can combine the power of GuiXT script with the power of FreeBASIC. GuiXT is standard part of the SAP GUI for Windows installation and FreeBASIC is a free/open source compiler.

 

Cheers

Stefan

Viewing all 100 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>