Skip to main content

Posts

Showing posts from 2012

Execute SQL command

static void Job3 ( Args _args ) {     LogInProperty   Lp = new LogInProperty ( ) ;     OdbcConnection  myConnection;     Statement       myStatement;     ResultSet       myResult;     str             sqlQuery; ;     sqlQuery = 'SELECT TOP 10 * FROM CustTable ORDER BY NewID()' ;     LP. setServer ( "Server" ) ;     LP. setDatabase ( "db" ) ;     Lp. setUsername ( "user" ) ;     Lp. setPassword ( "password" ) ;     try {         myConnection = new OdbcConnection ( LP ) ;     }     catch {         info ( "Check username/password." ) ;         return ;     }     myStatement = myConnection. createStatement ( ) ;     myResult = myStatement. executeQuery ( sqlQuery ) ;     while ( myResult. next ( ) ) {         box :: info ( myResult. getString ( 1 ) ) ;     } }

Purchline Change confirmed date Axapta

void clicked ( ) {   PurchLine                 tmpPurchLine;   PurchLine                 updatePurchLine;   PurchLine                 selectedRecord;   Dialog            dl;   DialogField       dlfTransdate; ;     dl   = new Dialog ( "Change confirmed date" ) ;     dlfTransdate = dl. addFieldValue ( typeid ( "Transdate" ) , today ( ) , "Confirmed date" ) ;     if ( dl. run ( ) ) {         selectedRecord =  PurchLine_ds. cursor ( ) ;         for ( tmpPurchLine = PurchLine_ds. getFirst ( true ) ? PurchLine_ds. getFirst ( true ) : PurchLine_ds. cursor ( ) ;         tmpPurchLine;    tmpPurchLine = PurchLine_ds. getnext ( ) )         {             ttsbegin ;             SELECT FORUPDATE updatePurchLine               WHERE updatePurchLine. PurchId == tmpPurchLine. PurchId                 && updatePurchLine. VendAccount == tmpPurchLine. VendAccount                 && updatePurchLine. LineNum == tmpPurchLin

List of new tools released for Microsoft Dynamics AX 2012

  1.    Application analysis Tool (Beta): The Application Analysis tool is designed to enable developers to easily understand how the application has been constructed. The tool can analyze X++ code, create UML sequence diagrams of the data model using progressive discovery. 2.    Data Migration Framework Tool (Beta): The Data Migration Framework (Beta) is an extension to Microsoft Dynamics AX that provides a way to migrate data from external sources to source Microsoft Dynamics AX 2012. The framework also supports exporting and importing data (for entities defined in the Data Migration Framework) from a Microsoft Dynamics AX 2012 instance to another one. 3.    Combine XPO Tool (Beta): The Combine XPO Tool (Beta) 1.0 is a command line program that combines a set of interdependent XPO files into a single XPO. For example, if a team of developers is making code changes to different aspects of an application, use this tool to merge those changed files into on

Dünyanın en çok bilinen markası Coca-Cola’nın CEO’su Muhtar Kent, başarısının sırrını paylaştı.

Muhtar Kent'in Başarı Sırları Dünyanın en çok bilinen markası Coca-Cola’nın CEO’su Muhtar Kent, başarısının sırrını paylaştı. Başarı için belirlediği 10 temel ilkesi olan Kent’in kariyer yaşamında dikkat edilecekler listesinin başında; "Herkes kendi çantasını kendi taşımalı" prensibi yer alıyor...   MUHTAR KENT’TEN BAŞARI VE KARİYER TAVSİYELERİ Muhtar Kent’in başarı olma kavramı ile ilgili vermiş olduğu ipuçlarını ilgiyle takip ediyorum. Kendisi bunun için 10 ilke belirlemiş. 1. Her iş mutfağında pişer. 2. Dururken düşmezsin ama, ilerlemekten de korkmayın. 3. Ofisine yapışıp kalma. 4. Fedakarlıktan kaçınma. 5. Hobilerine zaman ayır. 6. Değişim her zaman iyi olmayabilir. 7. Tutarlılık güven verir. 8. Gündem oluştur. 9. Büyük resme odaklanın. 10. Çinlileri örnek al.   Kariyer yaşamı için vermiş olduğu tavsiyelere bakacak olursak; - Öncelikle herkes kendi çantasını kendi taşımalı - Hiç yalnız yemek yemeyin. Böylece aldığınız her lokmadan ayrı bir tat alır ve sürekli gülümse

Microsoft Dynamics AX 2012 Source to Target data upgrade

What is this feature ? The source to target upgrade model provides a framework to reduce the downtime for AX upgrade.The upgrade downtime is achieved by enabling upgrade on both the source AX system (Ax 4.0 or AX 2009) and target AX system (Ax 2012). The upgrade consists of following steps. 1. Pre-upgrade processing on a live source AX system 2. Bulk data copy to target system, 3. Optimized data transformations (write once per table), and sync-on-the-fly to the target AX 2012 4. Fix duplicate RecID as a part of the upgrade process How do we upgrade using this feature ? The user installs an XPO on the source AX system being upgraded, launches the pre-upgrade checklist, and walks through the pre-upgrade checklist items. Most of the checklist tasks can be executed on a live AX system and rest within a single user mode. Concurrently the user can setup the AX 2012 environment for upgrade by installing AX 2012, choosing the upgrade option, and then launching the upgrade checklist an

How to update vendor addresses in Dynamics AX 2009

static void  UpdateVendAddressType(Args _args) { VendTable      vendTab; // Replace VendTable with CustTable when run this for  customers. DirPartyTable dirPartyTab; Address           addTab; ; ttsbegin; while select vendTab join dirPartyTab join forupdate addTab where vendTab.PartyId == dirPartyTab.PartyId && addTab.AddrTableId == dirPartyTab.TableId && addTab.AddrRecId == dirPartyTab.RecId {       if(addTab.Name == ‘Birincil Adres’)      {         addTab.type = AddressType::Payment;         addTab.update();      } } ttscommit; }

Merging Two records

//we will explore how to correct such a situation by merging two records including //all their related transactions. For the demonstration, we will merge two vendor accounts 5001 //and 5002 into a single one, that is, 5001. static void VendAccountMerge(Args _args) { VendTable vendTable; VendTable vendTableDelete; PurchJournalAutoSummary jourSummary; #define.vend('5001') #define.vendDelete('5002') ;      ttsbegin; delete_from jourSummary where jourSummary.VendAccount == #vendDelete; select firstonly forupdate vendTableDelete where vendTableDelete.AccountNum == #vendDelete; select firstonly forupdate vendTable where vendTable.AccountNum == #vend; vendTableDelete.merge(vendTable); vendTable.doUpdate(); vendTableDelete.doDelete();      ttscommit; }

Exporting data to Excel

As there are merits of a solution which depend on the situations and conditions in which they are used, I am suggesting one more alternate for achieving the objective i.e. Exporting data to Excel. In this solution we will make use of standard AX’s Reports and the concept of exporting the report data to an Excel file. I assume that we all understand that any standard AX report can be sent to a variety of Output devices such as Printer,Screen,Fax,File ( CSV,TXT,PDF,EXCEL etc) . The disadvantage in this is that the report headers is repeated after every page break and that is an undesired part . In the following walkthrough we will get over this problem as well as restrict the output to a file so that it gives a look and feel of an data export functionality. We will create a sample report for exporting the Price agreements data to Excel Start creating a report in AOT as per the following steps : Step 1: Create a class as shown below in which we would declare objects.

Ax 2009 FTP

static void readFromFTP() {     object                                        ftpo;     System.Net.FtpWebRequest     request;     System.IO.StreamReader          reader;     System.Net.NetworkCredenti al credential;     System.Net.FtpWebResponse   response;     System.String                            text;     ;     ftpo = System.Net.WebRequest::Cre ate(" ftp:/ /ftp.iso.com/i ntro.html " );     request = ftpo;   //  credential = new System.Net.NetworkCredenti al("user", "password" );   //  request.set_Credentials(cr edential);     response = request.GetResponse();     reader    = new System.IO.StreamReader(res ponse.GetR esponseStr eam());     text        = reader.ReadToEnd();     info(text); }

Append a txt file to another txt file

Copy this method to your Global Class in AX. public static void appendTextFile(str fromFilePath,str toFilePath) {     FileIOPermission fromPerm;     FileIOPermission toPerm;     System.String text;     System.IO.FileStream fs;     System.IO.StreamReader reader;     ;     if(System.IO.File::Exists(fromFilePath) && System.IO.File::Exists(toFilePath))     {          // Read text from file         reader = new System.IO.StreamReader(fromFilePath);         text = reader.ReadToEnd();         reader.Close();         // Append         System.IO.File::AppendAllText(toFilePath,text);     }     else     {         throw error("Invalid path or file does not exist");     } }

Dynamics AX 2009: FTP Adapter for AIF

from Markus Nöbauer The Application Integration Framework in Dynamics AX is an extensible framework for data transportation and reception. It support the separation of transport technology (e.g. MSMQ, XML/SOAP Webservices, Filesystem Share) security aspects (services, permissions, transported data) and data manipulation. Creating new adapters to support other transport technologies is simple. Here is an example to support FTP. Develop AIF FTP Adapter First, create a new parameter table AifFTPParameters to store FTP server name, user, password and directory (4 strings). Next create a setup form for the AifFTPParameters table and a display menu item. Add an OK command button. Add this code to the buttons clicked event: void clicked() {;     super();     // use the server name as selected value      element.closeSelect(Setup_ServerName.text()); } Create a new AifFTPSendAdapter class that implementes the AifSendAdapter in

Export and import Dynamics Ax labels

static void ExportLabels(Args _args) { str module = "TUS"; str exportFile = "\\\\tsclient\\c\\fil1.txt"; Label l; str s; int i; System.IO.TextWriter tw; ; l = new Label(); i = 0; tw = new System.IO.StreamWriter(exportFile); while(i < 9999) { s = l.extractString("@" + module + int2str(i)); if(substr(s,1,1) != '@') tw.WriteLine("@" + module + int2str(i) + ";" + s); i++; } tw.Close(); } static void ImportLabels(Args _args) { str module = "TUS"; str importFile = "\\\\tsclient\\c\\fil2.txt"; Label l; str s; System.IO.TextReader tw; System.String ss; str labelid, labeltext; int i; str existingLabel; ; l = new Label(); tw = new System.IO.StreamReader(importFile); ss = tw.ReadLine(); while(ss) { s = ss; i = strScan(s, ";", 1, 10);

Job to export all AX 2009 security groups to files

Alex wrote a nice and quick job that can export the existing security settings in Dynamics AX 2009 to a folder This is very helpful when we make frequent changes to security and need to have a quick backup of the existing settings. I have been changing security a bunch lately and it's nice to have a backup of your previous settings if you make a mistake. Here is a quick job I wrote to export your existing security settings to a folder.   static void ExportSecurityGroups(Args _args) {   SysSecurityUserGroup sysSecurity = SysSecurityUserGroup::construct();   UserGroupInfo userGroupInfo;   #file Dialog dialog = new Dialog( "@SYS14863" );   DialogField dialogFileName;   Object formdialog;   ;   dialogFileName = dialog.addField(typeid(FilePath), "@SYS16423" );   dialog.doInit();   formdialog = dialog.formRun();   formdialog.filenameLookupTitle( &

calculate total sales order or sales quotation amount / discounts / tax etc., through code( X++ ) in AX

this can be achieved through code using SalesTotals class. Check out the below code snippet. SalesTotals   salesTotals; SalesTable   salesTable; container   displayFields; str     totalTax, amountWithoutTax, amountInclTax; salesTable = salesTable::find('SO-1112345'); salesTotals = SalesTotals::construct(salesTable, salesUpdate::All); salesTotals.calc(); displayFields = salesTotals.displayFieldsCurrency( salesTotals.currencyCode() ); amountWithoutTax = conpeek(displayFields, TradeTotals ::posBalance()); amountInclTax   = conpeek(displayFields, TradeTotals::posTotalAmount()); totalTax    = conpeek(displayFields,TradeTotals::posTaxTotal()); In the above way, we can get all the values available in the totals form in the Sales Order Form by changing the TradeTotals values. We can get the values in the desired currency by providing a valid currency as a parameter to the displayFieldsCurrency method. In the same way we

Send message to online user in Dynamics AX

static void sendAlert(Args _args) { EventInbox inbox; EventInboxId inboxId; inboxId = EventInbox::nextEventId(); inbox.initValue(); inbox.ShowPopup = NoYes::Yes; inbox.Subject = "Message to online user"; inbox.Message = "Message you want to send to user"; inbox.SendEmail = false; inbox.UserId = curUserID(); inbox.InboxId = inboxId; inbox.AlertCreatedDate = systemdateget(); inbox.AlertCreateTime = timeNow(); inbox.insert(); }

How to read a CSV , txt file in AX 2009

1. First of all, make sure that the file is accessible and has sufficient permissions to read the file. 2. Now follow the below code which reads the file, reads all the lines in the file and inserts into the table. #File CommaIo aSCIIFile; Container recordsCon; FileIoPermission               perm; StudentTable                    studentTable; #define.ExampleFile(@"c:\test.txt") ; perm = new FileIoPermission(#ExampleFile, #io_read ); if (perm == null) { return; } // Grants permission to execute the CommaIo.new method. // CommaIo.new runs under code access security. perm.assert(); // BP deviation documented. aSCIIFile = new CommaIo( #ExampleFile ,#io_read); ttsbegin; while (aSCIIFile.status()== IO_Status::Ok) //Reading the ASCII file if records are there { recordsCon = aSCIIFile.read(); for(j=1;j<=Conlen(recordsCon);j++) {

Send message to online user in Dynamics AX 4.0 (quick & dirty)

I am missing the functionality to send messages to online users that existed in Axapta 3.0 and is now gone. Well, I thought you could use the "Alert" functionality introduced in DAX 4.0. What to do: 1. make sure the user options are configured correctly (that means: set "Time poll interval" to 1 minute, set "Show popup" to "For all event rules") 2. make a button in the online user form that will open a dialog where you could enter your text 3. send the message to all users selected in the online user form datasource Here is a little job that creates an alert for a user. Remember this is a quick & dirty solution, so there are some drawbacks: * you will get an error in the alert form on the second tab * the message will only be displayed about 15 sec and disappears afterwards (you can check FRM EventAttentionGrabber to change that. Check methods fadeIn and fadeOut for variable opacity. This should give you a hint on how to display the f

Be careful when resetting your usage data

in Dynamics AX 4.0, a "Favorites" menu was introduced. You can drag a form to your favorites pane. Then you will be asked to give it a name, and: you can add a saved query to it. With that, you can easily make favorites the open the forms filtered on the data you just need. But there's another thing: as long as your system is still in change, everybody recommends that you delete your usage data from time to time (in User/Options). But what happens to your favorites if you delete all your usage data? The answer is: you'll get an error message. The system will tell you that it cannot find your saved query anymore. So, the whole work saving your queries and making your favorites is lost. A small little addition to the method " reset " in the form " SysLastValue " will help you avoid that. Add the line && _sysLastValue.recordType != UtilElementType::UserSetupQuery; in the "delete_from" statement. So, the deletion will not delete your

Activating query tracing for all users

Sometimes when you are tracking performance (or other) problems, you may want to activate the long running query tracing for all users. Here is a little job that will do that. Beware: you have to activate trace settings on your AOS server, unless most of the queries will not be caught. static void Set_SQLTrace_AllUsers(Args _args) { #LOCALMACRO.FLAG_SQLTrace (1 << 8) #ENDMACRO #LOCALMACRO.FLAG_TraceInfoQueryTable (1 << 11) #ENDMACRO boolean set; UserInfo userInfo; ; set = true; ttsbegin; while select forupdate userinfo { userinfo.querytimeLimit = 1000; if (set) { userInfo.DebugInfo = userInfo.DebugInfo | #FLAG_SQLTrace; userInfo.TraceInfo = userInfo.TraceInfo | #FLAG_TraceInfoQueryTable; } else { userInfo.DebugInfo = userInfo.DebugInfo ^ #FLAG_SQLTrace; userInfo.TraceInfo = userInfo.TraceInfo ^ #FLAG_Trac

Executing direct SQL on an external database using ODBC

public static server void main ( Args _args ) {     Statement             statement;     str                         query;     Resultset              resultSet;     LoginProperty      loginProperty;     OdbcConnection  odbcConnection;     ;     loginProperty = new LoginProperty ( ) ;     loginProperty. setDSN ( 'YOURDSN' ) ;     odbcConnection = new OdbcConnection ( loginProperty ) ;     // Create new Statement instance     statement = odbcConnection. CreateStatement ( ) ;     // Set the SQL statement     query = 'select name from CustTable' ;     // assert SQL statement execute permission     new SqlStatementExecutePermission ( query ) . assert ( ) ;     // when the query returns result,     // loop all results for processing by handler     //BP Deviation documented     resultSet = statement. executeQuery ( query ) ;     while ( resultSet. next ( ) )     {         // do something with the result         info ( resultSet. getS

Executing direct SQL on the current AX database

When you execute a SQL statement, there are two options: - either you did a select and you expect a result to be returned - or you did insert/update/delete and you don’t expect a result. The first sample is for a SQL statement that returns a result: public static server void main ( Args _args ) {     Connection    connection;     Statement      statement;     str                  query;     Resultset       resultSet;     ;     // create connection object     connection = new Connection ( ) ;     // create statement     statement = connection. createStatement ( ) ;     // Set the SQL statement     query = 'select name from CustTable' ;     // assert SQL statement execute permission     new SqlStatementExecutePermission ( query ) . assert ( ) ;     // when the query returns result,     // loop all results for processing     //BP Deviation documented     resultSet = statement. executeQuery ( query ) ;     while ( resultSet. next ( ) )    

Linked server sql statements

Some time ago, I talked about executing direct sql statements , and now I want to share some sql statements that I used to manage linked server connections. What follows are 4 sql statements that allow you to add en remove linked servers on a database at runtime. Some assumptions: - There is a str variable named “query” that will contain the query - there is a parm method on the class that return the sql server (“server” or “server\instance”) - there is a parm method that returns a username - there is a parm method that returns a password Check if linked server exist First check if the linked server doesn’t exist yet, or you will get an error when you try to add one that already exists. query = strfmt ( "select top 1 * from sys.servers where name = '%1'" , this. parmServer ( ) ) ; Add linked server When the linked server doesn’t exist, add it. query = strfmt ( "EXEC sp_addLinkedServer @server = '%1', @srvproduct=N'SQL Server'&quo

Remove duplicate key entry from a table

Sometimes, you can’t synchronize a table because is contains duplicate records. This can occur when you change field lengths on a extended data type for example. I’ve seen people write huge SQL statements, and even jobs that create these SQL statements to remove these duplicates from a table, but there’s actually a easy way to do this in AX. Say you have a table KLFTestDuplicates that contains duplicates, then simple run the following job to remove them. static void KLFRemoveDuplicates ( Args _args ) {     Set fieldSet = new set ( Types :: Integer ) ;     DictIndex  dictIndex = new DictIndex (         tablenum ( KLFTestDuplicates ) ,         indexnum ( KLFTestDuplicates , AUniqueIdx ) ) ;     int i;     ;     if ( dictIndex. numberOfFields ( ) )     {         for ( i = 1 ;i <= dictIndex. numberOfFields ( ) ;i ++ )         {             fieldSet. add ( dictIndex. field ( i ) ) ;         }         ReleaseUpdateDB :: indexAllowDup ( dictIndex ) ;         Relea

Append text from one file to an other

This method will append all text from the original file to the destination file. While this is a very easy task, the method shows many of the things you come across when you are working with files in AX, like: - Using the #File macro - Asserting FileIOPermission to be able to access files - Asserting InteropPermission to be able to use .NET Interop - Using a set to assert multiple permissions at once - Using .NET Clr Interop in AX (better than winapi and winapiserver) - Optional cleaning up after you’re done using reverAssert() void AppendFileToFile ( FileName original , FileName distination ) {     #File     FileIOPermission    FileIOPermissionA   = new FileIOPermission ( distination , #io_append ) ;     FileIOPermission    FileIOPermissionR   = new FileIOPermission ( original , #io_read ) ;     InteropPermission   InteropPermission   = new InteropPermission ( InteropKind :: ClrInterop ) ;     Set                 permissionset       = new set ( types :: Class

Get folders and subfolders

static void KlForLoopFoldersSystemIO ( Args _args ) {     int                 k;                   // counter for result loop     container           dirs;               // container for result     filePath            path = @ "C: \t emp" ;   // input path     container getDirectories ( str _dir , boolean _inclSubDirs = true )     {         container           dList;           // container to cast array into         int                 i;               // counter for array loop         System. Array        directories;     // array for result from .NET call         #Define. Pattern ( "*" )                 // input pattern: * = all         ;         // assert interoppermissions for .NET interop         new InteropPermission ( InteropKind :: ClrInterop ) . assert ( ) ;         // get directories using .NET interop         if ( _inclSubDirs )         {             // include subdirectories             directories = System. IO . Director

Delete an AX company on SQL

This week, we were shrinking a database of a development environment by deleting some companies. Here a nice little SQL statement that uses the sp_MSforeachtable stored procedure to delete all records of a specific company (CEU in this case) from all tables. EXEC sp_MSforeachtable 'delete from ? where ?.DataAreaID = "CEU"' Certainly fast(er than AX) and gets the job done. Use at your own risk ;-) Update: You’ll want do do some cleaning up to: delete the company id from the DataArea table and from the CompanyDomainList table DELETE FROM DataArea WHERE DataArea . ID = 'CEU' DELETE FROM CompanyDomainList WHERE CompanyDomainList . CompanyID = 'CEU' Update 2: When you want to delete all companies execpt a few (like DAT), just use this: EXEC sp_MSforeachtable 'delete from ? where ?.DataAreaID <> "DAT" AND ?.DataAreaID <> "DEMO"' DELETE FROM DataArea WHERE DataArea . ID <> 'DAT