以c#

时间:2016-04-21 15:55:14

标签: c# sap

我希望在c#中遍历所有SAP GuiComponents,但我正努力让所有孩子参加gui会议。

这是我到目前为止(最初将session.ActiveWindow.Children传递给节点):

 private void IterateFindIDByNAme(GuiComponentCollection nodes, string searchstring)
    {
        if (foundID == "")
        {
            foreach (GuiComponent node in (GuiComponentCollection)nodes)
            {
                var comp = node;
                if (comp.Name.Contains(searchstring))
                    foundID = comp.Id;
                else
                {
                    try
                    {
                        FindIDByNAme((GuiComponentCollection)node, searchstring);
                    }
                    catch { }
                }
            }
        }
    }

它能够获取session.ActiveWindow的所有子元素,但是在尝试将所有子元素转换为GuiComponentCollections时,它会摔倒。

如果我可以使用FindByName函数,这将是无关紧要的,但由于某种原因,它不能在我正在进行的SAP屏幕上工作(它确实对其他人有效,不知道为什么)。

该字段的ID为:

wnd[0]/usr/subBCA_SUB_HEADER:SAPLBANK_BDT_CTRL:0100/subSUBS_DETAIL:SAPLBUSS:0028/ssubGENSUB:SAPLBUSS:4038/subA01P02:SAPLBCA_DYN_CN_CNMANO:0002/ctxtBCA_DYN_CONTRACT_ORGENTRY-ORGUNIT

我正在尝试的功能是:

((GuiTextField)session.FindByName("BCA_DYN_CONTRACT_ORGENTRY-ORGUNIT", "GuiTextField")).Text = "Test";

findbyid运行正常,但不是findbyname吗?

我知道这是两个问题,但有点相关。

3 个答案:

答案 0 :(得分:1)

  

<强> ctxt BCA_DYN_CONTRACT_ORGENTRY-ORGUNIT

控件的类型是GuiCTextField而非 GuiTextField

session.FindByName("BCA_DYN_CONTRACT_ORGENTRY-ORGUNIT", "GuiCTextField")

示例代码:

        public DateTime? GetModificationDate(int employeeID)
        {
            var session = SapHelper.GetActiveSession();

            Console.WriteLine("Recherche de la measure [A5 ou A6] avec un motif 90...");
            var window = session.BeginTransaction("PA20", "Afficher données de base personnel");
            window.FindByName<GuiCTextField>("RP50G-PERNR").Text = employeeID.ToString();
            window.FindByName<GuiCTextField>("RP50G-CHOIC").Text = "Mesures  (0000)";
            window.FindByName<GuiCTextField>("RP50G-SUBTY").Text = null;
            window.FindByName<GuiButton>("btn[20]").Press(); // list view

            if (window.Text == "Afficher données de base personnel")
            {
                Console.WriteLine(">> " + window.FindByName<GuiStatusbar>("sbar").Text);
                return null;
            }

            /*  Index Type          Title             Tooltip             
                0     GuiTextField  Début             Date de début       
                1     GuiTextField  Fin               Date de fin         
                2     GuiCTextField Mes.              Catégorie de mesure 
                3     GuiTextField  Dés. cat. mesure  Dés. cat. mesure    
                4     GuiCTextField MotMe             Motif mesure        
                5     GuiTextField  Dés. motif mesure Dés. motif mesure   
                6     GuiCTextField Client            Statut propre client
                7     GuiCTextField Activité          Statut d'activité   
                8     GuiCTextField Paiement          Statut paiement part */
            var result = window.FindByName<GuiTableControl>("MP000000TC3000").AsEnumerable()
                .Select(x => new
                {
                    Start = x.GetText(0),
                    Category = x.GetCText(2),
                    CategoryText = x.GetText(3),
                    Reason = x.GetCText(4),
                    ReasonText = x.GetText(5),
                })
                .Where(x => (x.Category == "A5" || x.Category == "AG") && x.Reason == "90")
                .FirstOrDefault();
            if (result == null)
            {
                Console.WriteLine(">> aucune measure [A5 ou A6] avec un motif 90 trouvée");
                return null;
            }
            else
            {
                Console.WriteLine(">> {0}:[{1}]{2} [{3}]{4}",
                    result.Start, result.Category, result.Category, result.Reason, result.ReasonText);
                return DateTime.ParseExact(result.Start, "yyyy/MM/dd", CultureInfo.InvariantCulture);
            }
        }

Xy.Sap:

#region namespace Xy.Sap
namespace Xy.Sap
{
    using System.Reflection;
    using sapfewse;
    using saprotwr.net;
    using COMException = System.Runtime.InteropServices.COMException;

    public static class SapHelper
    {
        public static GuiSession GetActiveSession()
        {
            var rot = new CSapROTWrapper().GetROTEntry("SAPGUI");
            if (rot == null)
                throw SapException.NotOpened();

            var app = (GuiApplication)rot.GetType().InvokeMember("GetScriptingEngine", BindingFlags.InvokeMethod, null, rot, null);
            var connectedSession = app.Connections.Cast<GuiConnection>()
                .SelectMany(x => x.Children.Cast<GuiSession>())
                .Where(x => !string.IsNullOrEmpty(x.Info.User))
                .FirstOrDefault();

            if (connectedSession == null)
                throw SapException.NotOpened();

            return connectedSession;
        }
    }

    public class SapException : Exception
    {
        public SapException(string message) : base(message) { }

        public static SapException NotOpened()
        {
            return new SapException("Veuillez lancer le SAP et de connecter avec votre identité");
        }
    }

    public static class SapExtensions
    {
        #region GuiSession

        /// <summary>
        /// Shortcut for PA20 query
        /// </summary>
        /// <param name="session"></param>
        /// <param name="employeeID"></param>
        /// <param name="it">Infotype ID</param>
        /// <param name="sty">Subtype ID</param>
        /// <param name="asListView"></param>
        /// <returns></returns>
        public static GuiFrameWindow QueryPA20(this GuiSession session, int employeeID, string it, string sty = null, bool asListView = false)
        {
            var window = session.BeginTransaction("PA20", "Afficher données de base personnel");
            window.FindByName<GuiCTextField>("RP50G-PERNR").Text = employeeID.ToString();
            window.FindByName<GuiCTextField>("RP50G-CHOIC").Text = it;
            window.FindByName<GuiCTextField>("RP50G-SUBTY").Text = sty;
            window.FindByName<GuiButton>(asListView ? "btn[20]" : "btn[7]").Press();

            if (window.Text == "Afficher données de base personnel")
            {
                var exception = new InvalidOperationException(string.Format("Failed to access to personal information of {0}", employeeID));
                exception.Data["Employee ID"] = employeeID;
                exception.Data["Infotype"] = it;
                exception.Data["Subtype"] = sty;
                exception.Data["View"] = asListView ? "ListView[Mont]" : "RecordView[Glasses]";
                exception.Data["Status Message"] = window.FindByName<GuiStatusbar>("sbar").Text;

                throw exception;
            }

            return window;
        }

        /// <summary>
        /// Shortcut for PA30 query
        /// </summary>
        /// <param name="session"></param>
        /// <param name="employeeID"></param>
        /// <param name="it">Infotype ID</param>
        /// <param name="sty">Subtype ID</param>
        /// <param name="asListView"></param>
        /// <returns></returns>
        public static GuiFrameWindow QueryPA30(this GuiSession session, int employeeID, string it, string sty = null)
        {
            var window = session.BeginTransaction("PA30", "Gérer données de base HR");
            window.FindByName<GuiCTextField>("RP50G-PERNR").Text = employeeID.ToString();
            window.FindByName<GuiCTextField>("RP50G-CHOIC").Text = it;
            window.FindByName<GuiCTextField>("RP50G-SUBTY").Text = sty;
            window.FindByName<GuiButton>("btn[6]").Press();

            if (window.Text == "Gérer données de base HR")
            {
                var exception = new InvalidOperationException(string.Format("Failed to access to personal information of {0}", employeeID));
                exception.Data["Employee ID"] = employeeID;
                exception.Data["Infotype"] = it;
                exception.Data["Subtype"] = sty;
                exception.Data["Status Message"] = window.FindByName<GuiStatusbar>("sbar").Text;

                throw exception;
            }

            return window;
        }


        /// <summary>
        /// Start a new transaction and return the active window
        /// </summary>
        public static GuiFrameWindow BeginTransaction(this GuiSession session, string transactionID, string expectedTitle)
        {
            return session.BeginTransaction(transactionID,
                x => x.Text == expectedTitle,
                x =>
                {
                    var exception = new InvalidOperationException(string.Format("Failed to open transaction : {0}", transactionID));
                    exception.Data["Transaction ID"] = transactionID;
                    exception.Data["Expected Title"] = expectedTitle;
                    exception.Data["Current Title"] = x.Text;
                    exception.Data["Status Message"] = x.FindByName<GuiStatusbar>("sbar").Text;

                    return exception;
                });
        }
        public static GuiFrameWindow BeginTransaction(this GuiSession session, string transactionID, Predicate<GuiFrameWindow> validation, Func<GuiFrameWindow, string> errorFormatter)
        {
            return session.BeginTransactionImpl(transactionID, validation, x => new Exception(errorFormatter(x)));
        }
        public static GuiFrameWindow BeginTransaction(this GuiSession session, string transactionID, Predicate<GuiFrameWindow> validation, Func<GuiFrameWindow, Exception> errorBuilder)
        {
            return session.BeginTransactionImpl(transactionID, validation, errorBuilder);
        }
        private static GuiFrameWindow BeginTransactionImpl(this GuiSession session, string transactionID, Predicate<GuiFrameWindow> validation, Func<GuiFrameWindow, Exception> errorBuilder)
        {
            // force current transaction to end, preventing any blocking(eg: model dialog)
            session.EndTransaction();

            session.StartTransaction(transactionID);
            var window = session.ActiveWindow;
            if (!validation(window))
                throw errorBuilder(window);

            return window;
        }

        #endregion
        #region GuiFrameWindow

        public static TSapControl FindByName<TSapControl>(this GuiFrameWindow window, string name)
        {
            try
            {
                return (TSapControl)window.FindByName(name, typeof(TSapControl).Name);
            }
            catch (COMException e)
            {
                var writer = new StringWriter();
                writer.WriteLine("The control could not be found by name and type.");
                writer.WriteLine("Name : " + name);
                writer.WriteLine("Type : " + typeof(TSapControl).Name);

                throw new Exception(writer.ToString(), e);
            }
        }

        #endregion
        #region GuiTableControl

        /// <summary>Note: Do not iterate through this ienumerable more than once</summary>
        public static IEnumerable<GuiTableRow> AsEnumerable(this GuiTableControl table)
        {
            var container = table.Parent as dynamic;
            string name = table.Name, type = table.Type;
            int rowCount = table.VerticalScrollbar.Maximum;

            Func<GuiTableControl> getTable = () => container.FindByName(name, type) as GuiTableControl;

            for (int i = 0; i <= rowCount; i++)
            {
                getTable().VerticalScrollbar.Position = i;
                yield return getTable().Rows.Item(0) as GuiTableRow;
            }
        }

        public static TSapControl GetCell<TSapControl>(this GuiTableRow row, int column)
        {
            return (TSapControl)row.Item(column);
        }
        public static string GetCText(this GuiTableRow row, int column)
        {
            return row.GetCell<GuiCTextField>(column).Text;
        }
        public static string GetText(this GuiTableRow row, int column)
        {
            return row.GetCell<GuiTextField>(column).Text;
        }
        #endregion
    }
}
#endregion

编辑:下面评论中提到的LINQPad脚本的链接不再有效。我已重新上传here

此脚本可帮助您浏览SAP GUI:

  • 列出控件类型,名称,ID,内容
  • 列出属性和方法
  • 突出显示控件
  • 生成选择器:.FindByName<GuiTableControl>("MP000000TC3000")

答案 1 :(得分:0)

In case anyone wants to know how to get child elements of any gui component (this will simply write all ids to the console):

private void LoopAllElements(GuiComponentCollection nodes)
    {
        foreach (GuiComponent node in (GuiComponentCollection)nodes)
        {
            Console.WriteLine(node.Id);
                if (node.ContainerType)
                {
                    var children = ((node as dynamic).Children as GuiComponentCollection);
                    LoopAllElements(children);
                }
        }
    }

This will loop through all child elements of any GUIComponentCollection you pass to it such as

LoopAllElements(session.Children)

There is probably a better linq way of doing this but this should get you started.

Please also check out this gist created by Xiaoy312 https://gist.github.com/Xiaoy312/a1424bd34acae92554105b27b0c80971

this has a lot of useful functions to debug your current sap session which i have found extremely useful.

You can either view the code as it has a number of functions you can use such as improved findbyid and findbyname or run it in linqpad https://www.linqpad.net/Download.aspx which will allow you to interogate the current SAP session.

答案 2 :(得分:0)

如果我理解正确,我们必须手动启动SAP Logon以使生产线在下面工作:

var app = (GuiApplication)rot.GetType().InvokeMember("GetScriptingEngine", BindingFlags.InvokeMethod, null, rot, null);

我是对的吗?

如果是这样,也许有人可以解释为什么在这一行:

var SapGuiApp = new GuiApplication();
string development = "Development ERP System";
var connection = SapGuiApp.OpenConnection(development);

我得到例外:

  

“System.Runtime.InteropServices.COMException”类型的异常   发生在System.Dynamic.dll中但未在用户代码中处理   附加信息:加载类型库/ DLL时出错。 (例外   来自HRESULT:0x80029C4A(TYPE_E_CANTLOADLIBRARY))

我已经尝试将目标平台从任何CPU更改为x86和x64,并且没有成功解决此问题。

但是当我使用以下脚本运行SAPGUI时:

CSapROTWrapper sapROTWrapper = new CSapROTWrapper();
        object rot = sapROTWrapper.GetROTEntry("SAPGUI");
        object engine = rot.GetType().InvokeMember("GetScriptingEngine", System.Reflection.BindingFlags.InvokeMethod, null, rot, null);
        GuiConnection connection = (engine as GuiApplication).OpenConnection(connectionName);
        GuiSession session = connection.Children.ElementAt(0) as GuiSession;

而不是手动运行SAP Logon上面描述的问题是不能再现。

但在这种情况下我还有其他问题:GUI不同,第二个选项GUI看起来已损坏 - 某些GUI控件未显示(请参见屏幕截图)。请给我建议可能出错的地方?先感谢您 enter image description here

更新:我找到了解决下述问题的解决方案。在尝试获取会话连接时,必须使用object而不是var:

{ "_id" : ObjectId("58437bd02e0a90d8318cfab1"), "a" : 1, "b" : 1}
{ "_id" : ObjectId("58437bf02e0a90d8318cfab3"), "a" : 2, "b" : 1 }
{ "_id" : ObjectId("58437bf32e0a90d8318cfab4"), "a" : 2, "b" :2}