AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 12.08.2008, 12:05   #1  
Blog bot is offline
Blog bot
Участник
 
25,486 / 846 (79) +++++++
Регистрация: 28.10.2006
Kashperuk Ivan: Another useful Editor Script for AX developers
Источник: http://kashperuk.blogspot.com/2008/0...pt-for-ax.html
==============

In AX the principle of upcasting is used quite a lot. Some examples coule be the RunBase hierarchy or the InventMovement class hierarchy. Basically, the base (or super) classes contain the main part of the hierarchy logic, while subclasses only override a couple of methods performing actions specific to this class.

When browsing the AOT, trying to find a specific line of code (debugging without the debugger, basically), you often find yourself in a situation when you lookup a definition of a method from a derived class, and end up in this method of the base class instead (because upcasting was used in the code in question). And every time you need to see the same implementation in the child class, you need to go back to the AOT and open it from there manually.

Well, not any more.
Here is a small editor script, that you can use to navigate to an overridden method of a derived class.

I created 2 versions of the same script, one using xReferences, the second using Dictionary class. You will have to pick the one you like more. I, personally, prefer the xRef one, as it, generally, should work faster once the xRefs for the class hierarchy is updated (happens the first time you use the script).

You can read more about Editor Scripts and how to use them on Axaptapedia

Version 1:
public void addIns_OpenOverriddenMethodDef(Editor e)
{
#AOT
#define.AOTDelimiter('\\') // This does not exist in AX versions prior to AX 2009, so I just declare it here
TreeNode treeNode = TreeNode::findNode(e.path());
TreeNode treeNodeParent;
Dictionary dictionary = new Dictionary();
Counter classCnt = dictionary.classCnt();
Counter iClassCount;
ClassId classIdParent;
ClassId classIdChild;
Counter descendentsCount;
SysDictClass dictClassChild;
TreeNodeName methodName = treeNode.treeNodeName();
Map map;
MapEnumerator mapEnumerator;
;
if (subStr(treeNode.treeNodePath(), 1, strLen(#ClassesPath)) == #ClassesPath)
{
treeNodeParent = TreeNode::findNode(xUtilElements::getNodePathRough(xUtilElements::parentElement(xUtilElements::findTreeNode(treeNode))));
classIdParent = dictionary.className2Id(treeNodeParent.treeNodeName());
map = new Map(Types::String, Types::String);
for (iClassCount = 1; iClassCount
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
За это сообщение автора поблагодарили: aidsua (1).
Старый 12.08.2008, 18:18   #2  
Logger is offline
Logger
Участник
Лучший по профессии 2015
Лучший по профессии 2014
 
3,882 / 3148 (112) ++++++++++
Регистрация: 12.10.2004
Адрес: Москва
Записей в блоге: 2
В трешке вот этот кусок
if (xRefTypeHierarchy::findOrCreate(Types::Class, classIdParent).Children)
не компилится.
Поделитесь, плиз кто нить.
За это сообщение автора поблагодарили: kashperuk (5).
Старый 12.08.2008, 18:29   #3  
Logger is offline
Logger
Участник
Лучший по профессии 2015
Лучший по профессии 2014
 
3,882 / 3148 (112) ++++++++++
Регистрация: 12.10.2004
Адрес: Москва
Записей в блоге: 2
Ваня, вылезай, мы тебе репутации отгрузим

Зачотный скрипт. Очень радует.

Последний раз редактировалось Logger; 12.08.2008 в 18:36.
Старый 12.08.2008, 18:31   #4  
kashperuk is offline
kashperuk
Участник
Аватар для kashperuk
MCBMSS
Соотечественники
Сотрудники Microsoft Dynamics
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии 2011
Лучший по профессии 2009
 
4,361 / 2084 (78) +++++++++
Регистрация: 30.05.2004
Адрес: Atlanta, GA, USA
Ой, что ж это я, собственно, на других версиях забыл проверить
Спасибо за замечание.

Код методов с таблицы xRefTypeHierarchy:
X++:
public static xRefTypeHierarchy findOrCreate(Types _baseType, int _id)
{
    xRefTypeHierarchy xRefTypeHierarchy = xRefTypeHierarchy::find(_baseType, _id);

    if (!xRefTypeHierarchy)
    {
        new xRefUpdateTypeHierarchy().run();
        xRefTypeHierarchy = xRefTypeHierarchy::find(_baseType, _id);
    }

    return xRefTypeHierarchy;
}
X++:
public static xRefTypeHierarchy find(Types _baseType, int _id)
{
    xRefTypeHierarchy xRefTypeHierarchy;

    select firstonly xRefTypeHierarchy
        index BaseTypeIdIdx
        where xRefTypeHierarchy.BaseType == _baseType &&
              xRefTypeHierarchy.Id == _id;

    return xRefTypeHierarchy;
}
За это сообщение автора поблагодарили: mazzy (2), AlGol (1), belugin (5), Logger (4), gl00mie (8).
Старый 13.08.2008, 02:14   #5  
kashperuk is offline
kashperuk
Участник
Аватар для kashperuk
MCBMSS
Соотечественники
Сотрудники Microsoft Dynamics
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии 2011
Лучший по профессии 2009
 
4,361 / 2084 (78) +++++++++
Регистрация: 30.05.2004
Адрес: Atlanta, GA, USA
Корректировал сообщение (точнее удалил и создал заново), вставив туда недостающие методы (оказалось, что на АХ 4.0 этих методов еще тоже нет).
Вот что значит - заработался со своей АХ 2009

Новая ссылка - http://kashperuk.blogspot.com/2008/0...cript-for.html
За это сообщение автора поблагодарили: Raven Melancholic (3), MikeR (5).
Старый 13.08.2008, 09:17   #6  
Gustav is offline
Gustav
Moderator
Аватар для Gustav
SAP
Лучший по профессии 2009
 
1,858 / 1152 (42) ++++++++
Регистрация: 24.01.2006
Адрес: Санкт-Петербург
Записей в блоге: 19
Цитата:
You can copy-paste the code for the script from axaptapedia.com (There is a problem with copying over the code from blogger site directly)
Пилюля: можно сначала скопировать код с сайта в Excel, а затем из Excel в редактор X++.
Эстеты могут еще в Excel выключить "Выравнивание по центру", но это не обязательно
Старый 13.08.2008, 09:32   #7  
MikeR is offline
MikeR
MCT
Аватар для MikeR
MCBMSS
Лучший по профессии 2015
Лучший по профессии 2014
 
1,628 / 627 (24) +++++++
Регистрация: 28.11.2005
Адрес: просто землянин
Иван молодец! Спасибо
Старый 13.08.2008, 18:23   #8  
Gustav is offline
Gustav
Moderator
Аватар для Gustav
SAP
Лучший по профессии 2009
 
1,858 / 1152 (42) ++++++++
Регистрация: 24.01.2006
Адрес: Санкт-Петербург
Записей в блоге: 19
Немножко присоседюсь к Ивану
Показалось напряжным запускать пиклист заново, когда хочется посмотреть реализацию метода сразу в нескольких классах. Внёс небольшую модификацию, использовав SysInfoAction_Editor. По ходу получилось своеобразное инфолог-меню, которое можно подержать на экране, щелкая по строчкам. Ну, и добавил заодно доступ и к самим классам в целом (а не только к конкретному методу).
X++:
switch (descendents.elements())
{
    case 0:
        info(strFmt(@"The method '%1' is not overridden in any of the %2 descendent classes", methodName, descendentsCount));
        break;
    case 1:
        descendentsEnumerator = descendents.getEnumerator();
        if (descendentsEnumerator.moveNext())
            treeNode = TreeNode::findNode(descendentsEnumerator.currentKey());
        break;
    default:
// Gustav -->
        //treeNode = TreeNode::findNode(pickList(descendents, "@SYS24724", @"Pick required class to go to method definition"));
        info(strRep('-', 100));
        info(' Double click required string to go to method or class definition: ' );
        info(strRep('-', 100));

        descendentsEnumerator = descendents.getEnumerator();
        while (descendentsEnumerator.moveNext())
        {
            treeNode = TreeNode::findNode(descendentsEnumerator.currentKey());

            info( strFmt('CLASS: %1', subStr( treeNode.AOTparent().treeNodePath(),10,100 )),
                  '', SysInfoAction_Editor::newOpen( treeNode.AOTparent().treeNodePath() ));

            info( strFmt('%1 METHOD: %2', strRep('-', 50), treeNode.treeNodeName() ),
                  '', SysInfoAction_Editor::newOpen( treeNode.treeNodePath() ));
        }
}
if(descendents.elements()<=1)
{
    if (treeNode && SysTreeNode::hasSource(treeNode))
        treeNode.AOTedit();
}
// Gustav <--
Проверить можно, например, открыв метод AssetId класса InventMovement и выполнить для него этот скрипт.
За это сообщение автора поблагодарили: kashperuk (5), aidsua (1), alex55 (1).
Старый 13.08.2008, 22:20   #9  
kashperuk is offline
kashperuk
Участник
Аватар для kashperuk
MCBMSS
Соотечественники
Сотрудники Microsoft Dynamics
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии 2011
Лучший по профессии 2009
 
4,361 / 2084 (78) +++++++++
Регистрация: 30.05.2004
Адрес: Atlanta, GA, USA
Добавил метод через Dictionary и метод, предложенный Gustav (правда я его перекромсал, приведя к более презентабельному, с моей точки зрения, виду).
Выложил, как discussion к теме на axaptapedia:
http://www.axaptapedia.com/Talk:Edit...iddenMethodDef
За это сообщение автора поблагодарили: aidsua (1).
Старый 10.11.2008, 15:36   #10  
belugin is offline
belugin
Участник
Аватар для belugin
Сотрудники Microsoft Dynamics
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии 2011
Лучший по профессии 2009
 
4,622 / 2925 (107) +++++++++
Регистрация: 16.01.2004
Записей в блоге: 5
Плагин для табакса
Вложения
Тип файла: zip DEV_OpenOverriddenMethodDef.zip (3.0 Кб, 86 просмотров)
За это сообщение автора поблагодарили: kashperuk (2), aidsua (1).
Теги
editor script, полезное, ax2009, ax4.0, axapta

 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
Kashperuk Ivan: SysMultiTableLoookup - dynamic lookups based on multiple tables Blog bot DAX Blogs 11 16.10.2008 12:26
Kashperuk Ivan: 3 great Tabax Plugins Blog bot DAX Blogs 2 15.05.2007 11:55
Kashperuk Ivan: Buy MorphX IT in Russian Blog bot DAX Blogs 6 13.04.2007 17:48
Kashperuk Ivan: Adding Menu ReferencesMany developers often find... Blog bot DAX Blogs 0 26.01.2007 05:51

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 09:53.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.