Code highlighting

Showing posts with label Tools. Show all posts
Showing posts with label Tools. Show all posts

Wednesday, October 28, 2020

[Tool] Display contents of an X++ container from SQL database field

Almost 15 years ago AndyD from AxForum blew me away with a post that was giving a glimpse into how the X++ containers are stored in the database. 

Ever since then I had a TODO for myself to write a blog post explaining this in detail and covering the various types that can be stored, basically allowing to review the contents of the container from DB without writing X++ code.

Luckily, today is the day! As they say, 


A colleague of mine, Maciej Plaza, has written a stored procedure, that shows the contents of a container stored in a database field. 

Some inspiration was taken from the following blog post too: http://abraaxapta.blogspot.com/2011/06/accessing-dynamics-ax-containers-from.html

Here's an example of how you could use this to see the batch task's infolog message contents:

declare @bin as varbinary(max);

select top(1) @bin = info from batch where recid = <recid>

exec ##PRINT_CONTAINER @bin

Here is how the output looks like:

Browsing the X++ container contents in SQL


Here is the stored proc (Also available as a file in OneDrive):

CREATE PROCEDURE ##PRINT_CONTAINER @container VARBINARY(MAX)
AS
BEGIN
DECLARE @pos AS int;
SET @pos = 1;
DECLARE @offset AS int;
DECLARE @indent as int;
set @indent = 0;
declare @result as varchar(max);
IF SUBSTRING(@container, @pos, 2) = 0x07FD
	BEGIN
	set @result = '<container>' + char(13);
	set @indent = @indent + 2;
	SET @pos = @pos + 2;
	WHILE @indent > 0
		BEGIN
			IF SUBSTRING(@container, @pos, 1) = 0x00 --STRING
				BEGIN
					set @result = @result + replicate(' ', @indent) + '<string>'
					SET @pos = @pos + 1;
					SET @offset = 0;
					declare @string as varchar(max);
					set @string = '';
					WHILE SUBSTRING(@container, @pos + @offset, 2) <> 0x0000
						BEGIN
							SET @string = @string + 
								CHAR(CAST(REVERSE(SUBSTRING(@container, @pos + @offset, 2)) AS binary(2)))
							SET @offset = @offset + 2;
						END
					SET @pos = @pos + @offset + 2;
					set @result = @result + @string + '</string>' + char(13);
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x01 --INT
				BEGIN
					set @result = @result + replicate(' ', @indent) + '<int>'
					SET @pos = @pos + 1;
					declare @int as int;
					SET @int = CAST(CAST(REVERSE(SUBSTRING(@container, @pos, 4)) AS binary(4)) as int);
					SET @pos = @pos + 4;
					set @result = @result + cast(@int as varchar(max)) + '</int>' + char(13);
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x02 --REAL
				BEGIN
					set @result = @result + replicate(' ', @indent) + '<real>'
					SET @pos = @pos + 1;
					DECLARE @temp as binary(8);
					SET @temp = CAST(REVERSE(SUBSTRING(@container, @pos + 2, 8)) AS binary(8));
					DECLARE @val bigint;
					SET @val = 0;
					DECLARE @dec AS int;
					SET @offset = 1;
					WHILE (@offset <= 8)
						BEGIN
							SET @val = (@val * 100) +
								(CAST(SUBSTRING(@temp, @offset, 1) AS int) / 0x10 * 10) +
								(CAST(SUBSTRING(@temp, @offset, 1) AS int) % 0x10);
							SET @offset = @offset + 1;
						END
					WHILE @val <> 0 AND @val % 10 = 0
						SET @val = @val / 10;
					SET @dec = (CAST(SUBSTRING(@container, @pos, 1) AS int) + 0x80) % 0x100;
					declare @real as real;
					SET @real = CAST(@val AS real);
					WHILE @dec >= LEN(CAST(@val AS varchar)) + 0x80
						BEGIN
							SET @real = CAST(@real AS real) * 10.0;
							SET @dec = @dec - 1;
						END
					SET @dec = (CAST(SUBSTRING(@container, @pos, 1) AS int) + 0x80) % 0x100 + 1;
					WHILE @dec < LEN(CAST(@val AS varchar)) + 0x80
						BEGIN
							SET @real = CAST(@real AS real) / 10.0;
							SET @dec = @dec + 1;
						END
					IF SUBSTRING(@container, @pos + 1, 1) = 0x80
						SET @real = 0 - CAST(@real AS real);
					SET @pos = @pos + 10;
					set @result = @result + @real + '</real>' + char(13);
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x03 --DATE
				BEGIN
					set @result = @result + replicate(' ', @indent) + '<date>'
					SET @pos = @pos + 1;
					DECLARE @year char(4);
					DECLARE @month char(2);
					DECLARE @day char(2);
					SET @year = SUBSTRING(@container, @pos, 1) + 1900;
					SET @month = SUBSTRING(@container, @pos + 1, 1) + 1;
					SET @day = SUBSTRING(@container, @pos + 2, 1) + 1;
					IF LEN(@month) < 2
						SET @month = '0' + @month;
					IF LEN(@day) < 2
						SET @day = '0' + @day;
					declare @date as date;
					SET @date = CAST(@year + '-' + @month + '-' + @day AS date);
					SET @pos = @pos + 3;
					set @result = @result + convert(varchar(max), @date) + '</date>' + char(13);
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x04 --ENUM
				BEGIN
					set @result = @result + replicate(' ', @indent) + '<enum>'
					SET @pos = @pos + 1;
					declare @enum as int;
					SET @enum = CAST(SUBSTRING(@container, @pos, 1) AS int);
					SET @pos = @pos + 3;
					set @result = @result + @enum + '</enum>' + char(13);
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x06 --DATETIME
				BEGIN
					set @result = @result + replicate(' ', @indent) + '<datetime>'
					SET @pos = @pos + 1;
					DECLARE @year2 char(4);
					DECLARE @month2 char(2);
					DECLARE @day2 char(2);
					DECLARE @hour char(2);
					DECLARE @min char(2);
					DECLARE @sec char(2);
					SET @year2 = SUBSTRING(@container, @pos, 1) + 1900;
					SET @month2 = SUBSTRING(@container, @pos + 1, 1) + 1;
					SET @day2 = SUBSTRING(@container, @pos + 2, 1) + 1;
					SET @hour = SUBSTRING(@container, @pos + 3, 1) + 0;
					SET @min = SUBSTRING(@container, @pos + 4, 1) + 0;
					SET @sec = SUBSTRING(@container, @pos + 5, 1) + 0;
					IF LEN(@month2) < 2
						SET @month2 = '0' + @month2;
					IF LEN(@day2) < 2
						SET @day2 = '0' + @day2;
					IF LEN(@hour) < 2
						SET @hour = '0' + @hour;
					IF LEN(@min) < 2
						SET @min = '0' + @min;
					IF LEN(@sec) < 2
						SET @sec = '0' + @sec;
					declare @datetime as datetime;
					SET @datetime = CAST(@year2 + '-' + @month2 + '-' + @day2 + ' ' + @hour + ':' + @min + ':' + @sec AS datetime);
					SET @pos = @pos + 12;
					set @result = @result + @datetime + '</datetime>' + char(13);
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x07 --CONTAINER
				BEGIN
					set @result = @result + replicate(' ', @indent) + '<container>' + char(13);
					SET @pos = @pos + 3;
					set @indent = @indent + 2;
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0xFF --CONTAINER END
				BEGIN
					SET @pos = @pos + 1;
					set @indent = @indent - 2;
					set @result = @result + replicate(' ', @indent) + '</container>' + char(13);
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x2D --GUID
				BEGIN
					SET @pos = @pos + 1;
					SET @offset = 0;
					declare @guid as uniqueidentifier
					SET @guid = CAST(CAST(
						REVERSE(SUBSTRING(@container, @pos, 4)) +
						REVERSE(SUBSTRING(@container, @pos + 4, 4)) +
						REVERSE(SUBSTRING(@container, @pos + 8, 4)) +
						REVERSE(SUBSTRING(@container, @pos + 12, 4)
					) AS binary(16))AS uniqueidentifier);
					SET @pos = @pos + 16;
					set @result = @result + replicate(' ', @indent) + '<guid>' + cast(@guid as varchar(80)) + '</guid>' + char(13)
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x30 --BLOB
				BEGIN
					SET @pos = @pos + 1;
					SET @offset = CAST(CAST(REVERSE(SUBSTRING(@container, @pos, 4)) AS binary(4)) AS int);
					SET @pos = @pos + 4;
					declare @blob as varbinary(max);
					SET @blob = CAST(SUBSTRING(@container, @pos, @offset) AS varbinary(max));
					SET @pos = @pos + @offset;
					set @result = @result + replicate(' ', @indent) + '<blob>' + CONVERT(VARCHAR(max), @blob, 2) + '</blob>' + char(13);
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0x31 --INT64
				BEGIN
					SET @pos = @pos + 1;
					declare @bigint as bigint;
					SET @bigint = CAST(CAST(REVERSE(SUBSTRING(@container, @pos, 8)) AS binary(8)) AS bigint);
					SET @pos = @pos + 8;
					set @result = @result + replicate(' ', @indent) + '<int64>' + cast(@bigint as varchar(max)) + '</int64>' + char(13)
				END
			ELSE IF SUBSTRING(@container, @pos, 1) = 0xFC --ENUMLABEL
				BEGIN
					SET @pos = @pos + 1;
					DECLARE @value int;
					DECLARE @name varchar(40);
					SET @value = SUBSTRING(@container, @pos, 1);
					SET @pos = @pos + 1;
					SET @offset = 0;
					SET @name = '';
					WHILE SUBSTRING(@container, @pos + @offset, 2) <> 0x0000
						BEGIN
							SET @name = CAST(@name AS varchar(40)) + 
								CHAR(CAST(REVERSE(SUBSTRING(@container, @pos + @offset, 2)) AS binary(2)))
							SET @offset = @offset + 2;
						END
					declare @enumlabel as varchar(max);
					SET @enumlabel = CAST(@name + ':' + CAST(@value as varchar(3)) as varchar(44));
					SET @pos = @pos + @offset + 2;
					set @result = @result + replicate(' ', @indent) + '<enumlabel>' + @enumlabel + '</enumlabel>' + char(13)
				END
			ELSE
			begin
			declare @errormsg varchar(max);
			set @errormsg = 'Unexpected type ' + CONVERT(VARCHAR(1000), SUBSTRING(@container, @pos, 1), 2);
			throw 50000, @errormsg, 1;
			end
		END
	END
print @result
END

Hope this helps!

Saturday, October 08, 2016

Tutorial: Visual Studio Debugger capabilities in Microsoft Dynamics AX '7', or the case-sensitive horror of C# syntax

Introduction

With the move to Visual Studio with the release of Microsoft Dynamics AX 7, the debugging experience also moved to use the standard Visual Studio debugger.
That means that we get some goodies that were previously not available in the MorphX debugger.

One example of that is the Immediate Window, which allows you to write expressions that are evaluated in the context of the currently hit breakpoint in X++ code.
This basically gives you the ability to call methods, look up variable values, ultimately allowing to change the current state. That is obviously a very useful feature.
Unfortunately, the current version does not fully support X++, meaning there are certain quirks when it comes to using it.

In this post I will describe the capabilities and syntax you need to use, so you can overcome some of the learning curve that comes with the new debugger.

Restrictions

Here's a list of the quirks you'll have to account for:

  • There is no native support for X++, so you need to use C# syntax.
  • Intellisense for X++ is not provided. This is a consequence of the way the expression evaluator works.
  • X++ is case insensitive, while C# is not. This means that references made to identifiers need to be in the case that was used at the place of definition.
  • Not all expressions allowed in X++ are applicable. One unfortunate example is select statements. You can however use static find() methods if they exist
  • Since it's not X++, you cannot use X++ types, like str, boolean, utcdatetime. Instead, use the C# equivalents. EDTs are not preserved during compilation either, so, again, use base types. Base enums is the only exception, but, again, you need to use C# syntax
  • When invoking methods from class Global, you will need to use the full notation, Global.methodName()
  • Single quotes are used to represent characters in C#, so you should only use double quotes for representing strings
  • The Expression evaluator has no knowledge of labels, so you will need to use workarounds, like SysLabel.labelId2String("@WHS1399"), if necessary.
  • Intrinsic functions like fieldNum() are not available - you'll need to use a workaround, as I will show below, using Microsoft.Dynamics.Ax.Xpp.PredefinedFunctions
  • You may end in a situation where the types you want to use are not loaded. You can use the ReflectionCallHelper to load these types – As soon as they are loaded you will be able to use them normally. Use the following command in the immediate window to load a particular type: Microsoft.Dynamics.Ax.Xpp.ReflectionCallHelper.getType("Global")
Now, with that out of the way, let's look at some examples.

Examples

Immediate Window capabilities in Microsoft Visual Studio for Dynamics AX 7
Let's walk through these examples line my line, and I'll explain what happened in each case:
  1. worKLine - as you can see, it's not a problem for the compiler, because X++ is not case sensitive, but it is a problem for the debugger, which is. So worKLine with capital K will not be recognized, while workLine will be treated just fine. This is the reason for one of the most confusing moments with the new debugger - hovering over the worKLine variable in the code editor will not show its value, even though everything looks fine and compiles. 
  2. Even more evident is the following example, where workLine.wMSLocationId value cannot be shown when hovering over it. Nor can it be recognized as an existing field in the Immediate Window. That's because it was defined as WMSLocationId on the table. Again, casing is very important in the new debugger, so pay attention when you write code
  3. Finally, success, we use the right record variable name and the right field name - so we got our result, the value of that field in the current record.
  4. We are trying to invoke a method which resides on the Global class exactly the same way it is done in the code we are debugging, but that won't work, the method is not recognized.
  5. Now we try to invoke it using the full notation, Global::exceptionTextFallThrough(); - That does not work either, because we must use C# syntax, and :: is only X++
  6. Finally, we use the right notation, invoking Global.exceptionTextFallThrough() - that works. The method does nothing and returns no result, and we are informed about that
  7. Trying to get the value of a Base Enum using X++ notation will not work
  8. Using the "correct" C# notation will return the right result, WHSWorkStatus.Open
  9. Microsoft.Dynamics.Ax.Xpp contains a number of helpful classes to compensate for lack of full X++ support. TrueFalseHelper is one of them, and its method TrueFalse() will use the X++ logic for evaluating if an expression is true or false. We use it here and pass in the record buffer. It returns true, because the record has been selected. In real C# that would fail, as the record cannot be implicitly converted to bool, along with most other X++ types, like str, integer, etc. 
    1. Another example from this namespace is EqualHelper.Equal() which can compare two X++ types
  10. Yet another example is the PredefinedFunctions class. You can see all the available methods in the Appendix. Here we invoke the tableName2Id(), passing in the string containing WHSWorkLine. Remember 'single quotes' do not work, only "double quotes". In this case all looks good, but the function is not recognized. That's again because of the casing. This class is very inconsistent about the casing of its methods - so you just have to remember the ones you commonly use, or use the robust "trial-and-error" approach.
  11. Finally, using the right casing we get the expected result, the ID of WHSWorkLine table

I have on purpose taken the full screenshot, so you could see some of the other windows open in Visual Studio while debugging:
  • Locals window, which is similar to the Watch window, but shows the values for all local variables without you first adding them to the list. 
  • The Infolog window will show all the infolog messages, which is very convenient
  • The Callstack is pretty much the same as in X++, with the downside of showing the full types, meaning you see a lot of useless type namespace information which X++ developers are not used to
  • The Breakpoints window shows all of your breakpoints, and you can for each one decide to configure it further, disable it or remove it. You can now make the breakpoints conditional, however since it uses the same Expression evaluator, I had trouble with it, so I stopped using it after a while. The counter condition works fine though, so you can use that in various complex loops and stuff, setting the breakpoint inside the loop.
  • Autos window, which is supposed to show the current line variables plus any from the previous line is useful, because it shows the global state variables on top of that, ttslevel in particular. Company, Partition and UserId are of lower interest.
  • Watch window - that's as expected, you add variables, their values are shown and can be edited on the fly. Note all the above restrictions apply here as well, so watch the casing and syntax.

Conclusion

As you can see, the Visual Studio debugger is much more powerful than what we had in AX 2012 and prior, however it also has a number of limitations due to lack of support for X++ language. Note, that it's not just X++, other languages which you can use in VS also have problems here and there.

Let me know how you find the new debugger. What features do you like? Something you miss from the old days?

Appendix

This appendix lists the predefined functions in the Microsoft.Dynamics.Ax.Xpp.PredefinedFunctions class. Pay special attention to the casing for the below methods.

Note. The methods starting with q deal with containers.
  • decimal Abs(decimal arg);
  • decimal AcceleratedDepreciation(decimal price, decimal scrap, decimal life, int period);
  • decimal Acos(decimal arg);
  • void AddToContainer(object element, int index, object[] container);
  • object Any2Enum(object a);
  • Guid any2guid(object input);
  • Date Anytodate(object arg);
  • decimal Asin(decimal arg);
  • object[] AssignPlusToContainer(object element, object[] container);
  • decimal Atan(decimal arg);
  • void Beep();
  • void catchUCDK(int ttsCount);
  • IDisposable changecompany(string newCompany);
  • int Char2Num(string text, int position);
  • int classget(object value, int classIdByType);
  • string ClassId2Name(int classId);
  • int classidget(XppObjectBase obj, int objId);
  • int ClassName2Id(string className);
  • int CompareStrings(string l, string r);
  • int ConfigurationKeyNum(string configurationKey);
  • object ContainerPack(object element);
  • object ContainerUnpack(object element);
  • decimal ContributionRatio(decimal sale, decimal purchase);
  • decimal corrflagset(decimal real, int arg);
  • decimal Cos(decimal arg);
  • decimal Cosh(decimal arg);
  • string curext();
  • string curusrid();
  • int Date2Num(Date date);
  • string Date2Str(Date date, int sequence, int day, int separator1, int month, int separator2, int year);
  • string Date2StrConvert(Date date, int sequence, int day, int separator1, int month, int separator2, int year, int convert_to_calendar);
  • string Datetime2Str(utcdatetime d, int f);
  • string DayName(int number);
  • int Dayofmth(Date d);
  • int DayOfWeek(Date arg);
  • int Dayofyr(Date d);
  • decimal Decround(decimal figure, int decimals);
  • object DefaultValue(Types t);
  • string dellspc(string text);
  • IntPtr delprefix(IntPtr value);
  • string delrspc(string text);
  • string delstr(string text, int position, int number);
  • decimal Depreciation(decimal price, decimal scrap, decimal life, int period);
  • int Dimof(object o);
  • Date EndMonth(Date arg);
  • string Enum2Str(object e);
  • string EnumExtension2Str(object value, string enumTypeName);
  • int Enumname2id(string enumName);
  • int EnumSymbol2EnumValue(string enumName, string enumValueName);
  • string EnumTypeToString(Types type);
  • decimal Exp(decimal arg);
  • decimal Exp10(decimal arg);
  • string Fieldid2name(int tableId, int field, int arrayIndex);
  • string Fieldid2pname(int tableId, int field, int arrayIndex);
  • int Fieldname2id(int tableId, string fieldName);
  • void FillArray(int size, T value, Dictionary array, T zeroValue);
  • void FillEdtArray(int size, T value, EdtArray array);
  • string FldPNam(int dataset, int fieldnum);
  • void Flush(int dataset);
  • decimal formattedstr2num(string text);
  • decimal Frac(decimal arg);
  • decimal FutureValue(decimal Payment, decimal Interest, decimal Life);
  • string getbuildversion();
  • string getcurrentauthor();
  • string getcurrentbranchname();
  • string getcurrentcustomerid([Optional, DefaultParameterValue(0)] int dbFlag);
  • string getcurrentdevicename();
  • string getcurrentipaddress();
  • string getcurrentmachinename();
  • long getcurrentpartitionrecid();
  • Guid getcurrentrequestid();
  • string getcurrentruntimemessage();
  • string getcurrentserviceunitid();
  • string getcurrentserviceunittype();
  • string getcurrentsessionid();
  • string getcurrenttenant();
  • string getcurrentuserid();
  • string getcurrentuserlanguage();
  • Dictionary GetFieldQCollection();
  • T GetFromArray(int position, Dictionary array, T zeroValue);
  • Date GetNullDate();
  • utcdatetime GetNullDateTime();
  • string GetNullString();
  • string getprefix();
  • void GroupQ(Dictionary collection);
  • string Guid2Str(Guid value);
  • decimal Idg(decimal purchase, decimal contribution_ratio);
  • string image(object o);
  • string Indexid2name(int tableId, int index);
  • int Indexname2id(int tableId, string indexName);
  • string insstr(string text1, string text2, int position);
  • string int2str(int param);
  • string int642str(long param);
  • int IntervalMax(DateTime inputDate, DateTime refDate, int func);
  • string IntervalName(DateTime refDate, int col, int func);
  • int IntervalNo(DateTime inputDate, DateTime refDate, int func);
  • DateTime IntervalNorm(DateTime inputDate, DateTime refDate, int func);
  • int intvmax(Date input_date, Date ref_date, int func);
  • string intvname(Date d, int col, int func);
  • int intvno(Date input_date, Date ref_date, int func);
  • Date intvnorm(Date input_date, Date ref_date, int func);
  • bool IsNonEmpty(string s);
  • int LicenseCodeNum(string licenseCode);
  • bool Like(string arg1, string arg2);
  • decimal Log10(decimal arg);
  • decimal Logn(decimal arg);
  • string LookupLabel(string pattern);
  • int Match(string pattern, string text);
  • object Max(object[] args);
  • object Min(object[] args);
  • Date Mkdate(int day, int month, int year);
  • string MonthName(int number);
  • int Mthofyr(Date d);
  • Date NextMonth(Date arg);
  • Date NextQuarter(Date arg);
  • int nextTraceSequence();
  • Date NextYear(Date arg);
  • bool NullDate(Date d);
  • bool NullDateTime(utcdatetime d);
  • bool NullGuid(Guid g);
  • string Num2char(int figure);
  • Date Num2Date(int days);
  • string Num2Str(decimal number, int character, int decimals, int separator1, int separator2);
  • string ObjectToString(object o);
  • void OrderQ(Dictionary collection);
  • decimal PercentAdd(decimal amount, decimal percentage);
  • decimal Periods(decimal payment, decimal interest, decimal future_value);
  • decimal PeriodsRequired(decimal Interest, decimal FutValue, decimal PresValue);
  • decimal Power(decimal arg, decimal exponent);
  • decimal PresentValue(decimal Paym, decimal Interest, decimal Life);
  • Date PreviousMonth(Date arg);
  • Date PreviousQuarter(Date arg);
  • Date PreviousYear(Date arg);
  • decimal PricePerPeriod(decimal principal, decimal interest, decimal life);
  • object[] qdel(object c, int position, int numElements);
  • int qfind(object c, object[] parameters);
  • object[] qins(object c, int position, object[] parameters);
  • int qlen(object[] container);
  • object qpeek(object c, int position);
  • object[] qpoke(object c, int position, object[] parameters);
  • decimal Rate(decimal future_value, decimal current_value, decimal terms);
  • string remove(string text1, string text2);
  • decimal Round(decimal dbl0, decimal dbl1);
  • void SecAuthzCheck(string className, string methodName);
  • int sessionid();
  • void SetInArray(int position, T value, Dictionary array, T zeroValue);
  • int setprefix(string prefix, ref IntPtr ptr);
  • decimal Sin(decimal arg);
  • decimal Sinh(decimal arg);
  • int Sleep(int duration);
  • decimal Sln(decimal cost, decimal salvage, decimal life);
  • int Sound(int frequency, int duration);
  • Date Str2Date(string text, int sequence);
  • utcdatetime Str2Datetime(string text, int sequence);
  • object Str2Enum(object e, string s);
  • object Str2EnumExtension(object dummyParm, string valueName, string enumTypeName);
  • Guid str2guid(string input);
  • int str2int(string text);
  • long str2int64(string text);
  • decimal Str2Num(string text);
  • int str2time(string text);
  • string StrAlpha(string text);
  • string strcolseq(string text);
  • int StrFind(string text, string characters, int position, int number);
  • string strfmt(string text, object[] parameters);
  • Types StringToType(string t);
  • string StrKeep(string text1, string text2);
  • int Strlen(string text);
  • string StrLine(string s, int count);
  • string Strlwr(string text);
  • int StrNFind(string text, string characters, int position, int number);
  • string StrPoke(string arg1, string arg2, int position);
  • string StrPrompt(string _string, int _len);
  • string StrRep(string text, int number);
  • int StrScan(string text1, string text2, int position, int number);
  • string Strupr(string text);
  • string Substr(string text, int position, int number);
  • Date systemdateget();
  • Date systemdateset(Date d);
  • string Tableid2name(int tableId);
  • string Tableid2pname(int tableId);
  • int Tablename2id(string table);
  • string TabPNam(int dataset);
  • decimal Tan(decimal arg);
  • decimal Tanh(decimal arg);
  • string Time2str(int time, int separator1, int separator2);
  • int Timenow();
  • Date Today();
  • decimal Trunc(decimal arg);
  • void truncate_infolog();
  • int TryStart(ref IntPtr ptr);
  • void ttsabort();
  • void ttsbegin();
  • void ttscommit();
  • int ttscount();
  • int Typename2id(string typeName);
  • Types Typeof(object o);
  • string uint2str(int param);
  • IDisposable Unchecked(int uncheckValue, string className, string methodName);
  • int WeekOfYear(Date arg);
  • void Where(exprNode node, Common table);
  • int Year(Date d);

Thursday, October 06, 2016

Development tool: Copy 'Find references' results to clipboard (to Excel) in Visual Studio for AX 7

Problem

With the release of Microsoft Dynamics AX 7 the development moved to the Visual Studio environment.

This had a lot of advantages, like the ability to use any 3rd party add-ons of various sort (which we actually have not seen that many of being applied to AX so far), all the VS goodies that come out of the box, a more familiar IDE for new developers, etc.

But it also has its disadvantages, like the Cross-References display window.

  • First of all, the indicator of whether a particular reference is writing or reading is gone. 
  • And we now display the xRefs using the standard Visual Studio "Find Symbols Results" window, which has one huge drawback as well - no way to filter on the data displayed, or copy that data somewhere else to do that.

Solution

I was bothered by this lack of functionality for a while, so I went out to find if there's an existing solution. I came across this post, which seems like a sufficient solution for the problem, in my opinion. Kudos to the author!

I have modified the project a bit to better suite AX needs, as I planned to browse the data in Excel, which has rich filtering capabilities and more convenience in navigation, and uploaded it to GitHub so anyone can use and extend it. You can also just download the executable, if are OK with the out-of-the-box functionality I will describe below.

Project on GitHub:

Executable on my OneDrive:

Installation guide

Once you have the executable, place it in a folder on your environment running Visual Studio for AX, say, C:\Tools or whatever you prefer.

Now, from Visual Studio, go to Tools and select External tools..., as shown below:

External Tools... under Tools menu in Visual Studio

Now add a new tool by clicking Add, and specify the Title, Command and Initial directory.
The Command  should contain the path to the CopyFindReferencesToClipboard executable

Add the CopyFindReferencesToClipboard tool

User guide

Using the tool is very simple. Say I wanted to find all references to the WHSLoadLine.Qty field.
I would navigate to that field and select Find references from the context menu. 

Find references to the WHSLoadLine.Qty field
This would bring up the standard Visual Studio dockable window Find Symbol Results, containing all the references to the selected table field.

Now, all you need to do is go to Tools and select the newly added tool from the list, as shown below:

Run the tool to copy the references to clipboard
After a few seconds you will get a message box to pop up telling you the references have been copied to clipboard successfully, which means you can now to and paste the data to Microsoft Excel.



Note. Since the tool uses UI-level automation to copy the cross-references, the Find references window needs to be open and visible for the tool to work.

Now, you can do whatever you want with that data in Excel.
The way I typically use it is by just showing the data as a Table, after which:
- Exclude test related files (Actual tests and Test frameworks we used)
- Filter out only elements in a certain area, like WHS
- Build pivot tables/charts, if I am doing complexity analysis for a change / feature
- etc.

Here's how it looks:

Analyze the cross-references in Microsoft Excel

Feeback

Give it a try and let me know what you think!

Saturday, December 14, 2013

Tool: Update: User preferred startup menu for AX 2012


I have over the last year received a couple mails and comments from people, asking to publish an update for the below tool for AX 2012

http://kashperuk.blogspot.dk/2010/04/tool-user-preferred-startup-menu-for.html

There aren't really any serious changes to it as such, just some minor things.
Again, note, that there are a few changes to some of the existing "high profile" AOT elements, so please read through the description of changes in the above post.

Download updated xpo

Sunday, October 09, 2011

Tool: Updating a field value for all selected records on a form

Update:
It looks like I was re-inventing the wheel here.
Turns out that a tool doing exactly the same (and even invoked from the same place on Record info form) already exists and is called "Fill Utility". The problem is that it's disabled by default in the License configuration, so it not available.
More information about how to get it and what it does can be found in this MSDN article


Problem statement:
During a recent customer visit we received a suggestion from the developers working on customizing the customer application to their needs. The suggestion was about being able to modify the value of a certain field on a form for multiple records at once.
As you know, in AX 2012, if we wanted to change a certain property for a number of entities (for example, update the default transfer order overdelivery allowence on a number of items at once), we would have to go through them one by one, which is time consuming and definitely not fun.

Solution:
Using the small example I created we can in a simple and intuitive manner update the selected field value for all the marked records.

It looks something like this:

1.    First, you multi-select the records where a certain field needs to be updated, and open the Record information for them


2.    Then, you click Update, select the field that needs to be updated and put in the new value


3.    After you confirm the changes, all the selected records will be updated with the new value.

Download:
Download the project from my SkyDrive


Issues:
These aren't really issues, just things I did not spend time on.
  1. I did not develop the idea of selecting multiple fields to update at once. Might be a good idea. I just did not want to add more code into this little project. There's however a nice UI for selecting 1 or more fields in the DEV_SysTableBrowser project (link)
  2. I did not spend enough time trying to figure out the validation that should be in place for this. I figured, if people are gonna use it, they know what they are doing.
  3. The project is based on AX 2012. There's only 1 method with code, the rest is form controls. I figured it should be pretty easy to port this to other versions if needed.
If people find this useful, I encourage them to add whatever else modifications. I can also re-post them here on request.


Thanks

Tuesday, May 04, 2010

Tool: DEV_SysTableBrowser and DEV_CreateNewProject tools now on AX 2009

3 or so years ago I created a couple of tools that provide extra capabilities for AX developers, specifically, ease up the creation of a new project with a predefined structure and name pattern, and add functionality to the way we browse tables with the standard SysTableBrowser, allowing to specify the exact fields you want to see, browsing temporary tables. Both tools were also available as Tabax plugins

You can read more about the tools, as well as Tabax, on the following pages on Axaptapedia:
DEV_SysTableBrowser home page on Axaptapedia
DEV_CreateNewProject home page on Axaptapedia

You can download the new versions of these tools through the pages on Axaptapedia, or directly from my SkyDrive: DEV_SysTableBrowser, DEV_CreateNewProject
If you are unfamiliar with these tools, I suggest you go through Axaptapedia, as it also contains a detailed description of the features provided.

A couple of things I would like to note:
  • There is a kernel bug in AX 2009 that heavily impacts the SysTableBrowser user experience. It takes around 10 seconds each time you want to browse the contents of a specific table. This bug was fixed with a hotfix rollup 3, so users of AX 2009 without the hotfix might have problems enjoying the DEV_SysTableBrowser tool.
  • In AX 2009 the behavior of SysTableBrowser changed a bit. Instead of re-opening the browser window each time the user changes from All fields to AutoGroup only, now 2 grids with these fields are added from the beginning, and hidden/shown based on user selection. DEV_SysTableBrowser provides much more flexibility when selecting the fields to display, so I was not able to follow the same approach. Thus, see bullet 1
  • I have not added any new AOT nodes to the template in DEV_CreateNewProject tool (Data sets, Report Libraries, etc). I don't think AX developers will invest that much time into SSRS reports and EP, and in these cases they will be able to manually create the remaining group nodes in the project.

Let me know if you have comments, suggestions or ideas for these tools.
Thanks

Thursday, April 22, 2010

Tool: User preferred startup menu for Dynamics AX 2009

In AX 2009, the user has no control over which menu is opened in the navigation pane and address bar when AX client is started. Most of the time you simply get the Home page, which is frustrating for a number of users. Another thing that is frustrating for them is the company account the application opens with. The latter can actually be setup using standard application functionality in the User options form. Just set the 'Start company accounts' to the account you want for the user by default. I wrote a small tool, that allows the user to select a preferred startup menu, ensuring that this menu is the one open every time AX client is started. Something similar existed in Axapta 3.0 application. You can download the xpo for this tool from my SkyDrive. Note, that it contains minor changes to a number of existing application objects. I suggest that you compare the xpo from the import dialog and ensure that you don't override any of your changes during import - the best thing would be to re-implement these minor changes manually. Below is a list of changes that I am referring to above:
  • SysUserInfo table - 1 new field was added
  • SysUserSetup form - 1 new control was added. Lookup method on datasource field overridden
  • Info class - startupPost method changed
In order to enable the functionality, simply select one of the menus in the User options, as shown in the below screenshot. Next time you start AX, the selected menu will be open by default. Start Menu in User options, Microsoft Dynamics AX 2009 Below is a short listing of "code patterns" used in the project, that can serve as examples for your future projects:
  • SysTableLookup - for displaying a lookup form with a list of menus
  • infolog.globalCache() - for storing a global reference to the navigator class
  • TreeNode iteration - for finding all menu references in MainMenu
  • QueryBuild classes - for constructing and filtering a list of menu references in MainMenu, used in the lookup form
  • infolog.addTimeOut() method - for scheduling execution of another method in a set period of time

Thursday, March 04, 2010

Highlighting your code on Blogger

A couple of people have now asked me for the tool that I use for pasting the source code on my blog.
In order to use the same, you will have to change the template of your blog and include the following scrips:


<script src='http://amalafe.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'/>
<script src='http://amalafe.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'/>
<script src='http://amalafe.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'/>
<script src='http://amalafe.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'/>
<script src='http://amalafe.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'/>
<link href='http://amalafe.googlecode.com/svn/trunk/Styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://amalafe.googlecode.com/svn/trunk/Styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script type='text/javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://amalafe.googlecode.com/svn/trunk/Scripts/clipboard.swf';
SyntaxHighlighter.all();
</script>


After that, you will be able to create code by specifying the following:

<pre class="brush: c-sharp;">
Your code goes here...
</pre>

Tuesday, January 05, 2010

Editor script for simplifying the search in AOT

When doing code refactoring, or when investigating a particular class or form to understand the functionality behind it, it is often handy to search for variables used in its methods, looking at where and how each variable is used.

It is tedious to manually go through the steps of copying the name of the variable into the clipboard, opening up the parent class/form, opening up the AOT Find dialog for it, pasting the variable name into the Selected Text field and pressing Find now.

I have automated these steps, putting the code into an editor script.

You can download the xpo, which contains the EditorScripts class with the additional method, by following this link.

Now you should be able to very easily and quickly find the required code.

The code of the editor script:

///
/// Editor script for finding all occurrences of the selected text in the parent node of the selected method
///

///
/// Reference to the AX editor
///
///
/// 2010-01-05, ivanv
///

void addIns_FindAllOccurrencesInNode(Editor e)
{
#AOT
TreeNode treeNode;
FreeText selectedText;

FreeText GetSelectedTextFromEditor(Editor _e)
{
str 1 curSymbol;
int iCopyFrom;
int iCopyTo;
FreeText _selectedLine;
;
if (_e.markMode() != MarkMode::NoMark && _e.selectionStartCol() != _e.selectionEndCol())
{
_selectedLine = strLRTrim(subStr(_e.currentLine(), _e.selectionStartCol(), _e.selectionEndCol() - _e.selectionStartCol()));
}
else
{
_selectedLine = _e.currentLine();
for (iCopyFrom = _e.columnNo()+1; iCopyFrom >= 0; iCopyFrom--)
{
curSymbol = subStr(_selectedLine, iCopyFrom, 1);
if (!strAlpha(curSymbol) && curSymbol != '_')
break;
}
for (iCopyTo = _e.columnNo()+1; iCopyTo <= strLen(_selectedLine); iCopyTo++)
{
curSymbol = subStr(_selectedLine, iCopyTo, 1);
if (!strAlpha(curSymbol) && curSymbol != '_')
break;
}
_selectedLine = (iCopyFrom < iCopyTo) ? subStr(_selectedLine, iCopyFrom + 1, iCopyTo - iCopyFrom - 1) : '';
}
return _selectedLine;
}

void FindLinesContainingSelectedText(FreeText _selectedLine)
{
Args args = new Args(formstr(SysAOTFind));
FormRun sysAOTFindFormRun;
FormStringControl containingTextCtrl;
FormButtonControl findNowBtnCtrl;
;

sysAOTFindFormRun = classFactory.formRunClass(args);
sysAOTFindFormRun.init();
sysAOTFindFormRun.run();

// Set the text to find
containingTextCtrl = sysAOTFindFormRun.design().controlName(identifierStr(ContainingText));
containingTextCtrl.setFocus();
containingTextCtrl.pasteText(_selectedLine);

sysAOTFindFormRun.detach();

// Launch the search process
findNowBtnCtrl = sysAOTFindFormRun.design().controlName(identifierStr(FindNow));
findNowBtnCtrl.clicked();
}
;

selectedText = GetSelectedTextFromEditor(e);
if (selectedText)
{
// Find the currently open method node
treeNode = TreeNode::findNode(e.path());
// Find the parrent node of the method
treeNode = TreeNode::findNode(xUtilElements::getNodePathRough(xUtilElements::parentElement(xUtilElements::findTreeNode(treeNode))));
if (treeNode)
{
treeNode.AOTnewWindow();

FindLinesContainingSelectedText(selectedText);
}
}
}

Thursday, December 11, 2008

Tool for protecting your Dynamics AX source code

"Is there a way to protect/hide my X++ code?"
People asked me this question a million times by now.

To most of them, I described 2 possible ways to go, that I know of:
- Do not share the source code, but instead provide the customers with an AOD file.
- Use a tool that would produce obfuscated code out of your modifications.

Both ways are not perfect, of course. If you provide the code as an AOD file, you need to be sure that the customer does not have X++ license. If you provide obfuscated code, the customer developers (if they are present) will have a hard time interacting with your code. And, eventually, both ways leave the customer at a disadvantage. As soon as the vendor is not there to support (provide fixes in terms of an updated AOD file or XPO with obfuscated code) them for whatever reason, the customer has no way of supporting the add-on solution on their own.

But this post is not about the cons of trying to protect your code.
It's about the possibilities. Today, finally, I can support my previous suggestion #2 with an actual link to such a tool: Next Innovation Code Scrambler Homepage

Here is a screenshot of how the code looks after Code Scrambler is finished with it:


Note, that the tool is not free, and I have not actually tried it out.
But there is a sample project showing the resulting scrambled code. You can download it for a first impression, and contact the company if you are interested in the tool.

Another note - this is not an advertisement, I am not in any way related to Next Innovation Company.

Friday, September 14, 2007

DEV_SysTableBrowser version 2.0 is out!

I have been asked by a number of my blog readers to move this tool to Dynamics AX 3.0, so here is the updated version of this tool. Now it works on both DAX 3.0 and 4.0 (tested on 3.0 SP5 KR2 and 4.0 SP1 and SP2).

Also, I added a couple of things I considered useful to this new release:
- The user field select dialog option has now, by default, all the non-system fields selected, so that users don’t get surprised when no fields are selected. I agree – it does look strange :)
- Now it’s possible to select display methods along with table fields in the user field select dialog. This feature was already working with FieldGroups, so I decided it could be a nice add-on to the User Field List option
- I also fixed a couple of old (and new, brought to us by 4.0 SP2) bugs that existed in the tool
- After reading some of the last posts on AxForum, I decided to add the ability of browsing temporary tables into my project as well, so that others may use them if they want :) (this will also include browsing temp tables data shown in forms from Tabax when the next version comes out)
- Now you can also use the browser for debugging purposes, launching it from code (this works for temp tables as well). Just write:

SysTableBrowser::browseTable(table.TableId, table);

where table is a cursor (second parameter can be omitted for non-temp tables). In this case the browser will open and code execution will stop until you close the browser (if not in a transaction). Third parameter controls if code execution should be stopped.

- There are two variables in method new of class SysTableBrowser
saveQueryRun = true; // Enables/Disables queryRun saving when new options are specified
savePosition = true; // Enables/Disables cursor position saving when new options are specified

The options allow to save the user filters and cursor position when changing setup options.
Both operations could result in performance problems on large tables.
If that happens (or you just don't need them), just turn them to false. :)

The download link is: DOWNLOAD

See extended installation instructions and tool description on: HOMEPAGE

What was a little disappointing is that a number of bugs I wrote about earlier were not fixed since SP1. Here are the 2 I mentioned before, again:
- UPDATE_RECORDSET command, when used in the table browser, crashes DAX.
- The left top edge position (the coordinates) of the table browser gets reset when any of the options are changed. I fixed this by specifying 0 instead of -1 for the leftMode and topMode properties of the design. So when you download this tool, the browser will stay in one place, which is nice ;)

Also, 1 new bug I found is for the Russian localization team.
- Changing the view (in the Unmodified version of the browser was causing the full table list to open, prompting the user for a selection of the table). This is caused by a small validation in the SysTableBrowser::main() method. SysSetupFormRun is supposed to be the classId of the calling object. And it is not, because some system wide changes were made to the SysSetupFormRun::construct() method. Anyway, I fixed this small bug as well.

OK. That’s all about the tool and the bugs. I have also been asked by a couple of my readers to write a tutorial on using the SysListPanel class.

That’s exactly what I am going to write about in my next blog entry. After all, there is a new class extending from the SysListPanel class in the DEV_SysTableBrowser project.

Saturday, April 07, 2007

Add-On: Extended SysTableBrowser

Hello, readers.
Today I provide you with another tool for Dynamics AX developers. It is a modified version of the SysTableBrowser (See picture 1).
picture 1


Important:
After importing the project refresh the AOD (Tools\Development Tools\Application Objects\Refresh AOD)

Modifications:

  1. The table browser does not change its position when a different setup is selected. (Unlike standard system behavior in DAX 4.0)

  2. The AutoReport option was extended, and now you are able to select any of the table field groups (See Credits).

  3. Another selection option was added, providing the means to select any of the table fields to be shown in the grid. To do this, just press the ‘Select Fields’ button and select the fields you want displayed (See picture 2).

  4. Added a list of presets for the SQL window. (SELECT, UPDATE, DELETE). The list can be easily extended to include other presets you often use.

  5. Extra logic was added to the ExecuteSQL button, which executes the SQL string that the user has put into the SQL window. If it is a simple select (for example, generated by the SELECT preset), the ds query is executed instead of the sql string. This will bring back the sorting and filtering options that disappear after using the sql string query.
  6. Added the ability to sort columns by name or by id. In some cases (when, for example, you cannot find a specific field) it really helps out! (See picture 3)

picture 2
picture 3


Possible future improvements:

  1. Add display methods of the selected table to the list of fields in the select dialog.

Credits:


The modification was inspired by a similar one performed by Nicolai Hillstrom for Dynamics AX 3.0. I moved it to DAX 4.0 and added some extra features I considered useful. One of them is implemented here (even thought I wasn’t able to download it and see how it is programmed).