CLRInterop AX example (Como calcular el SHA1 de un fichero desde AX 2009)

Filed under:5.0,axapta,desarrollo,dynamics2009,x++ — posted by admin on February 26, 2009 @ 8:51 am

static void AXL_TestSHA1(Args _args)
{
#define.ClrFileStream (‘System.IO.FileStream’)
#define.ClrFileModeEnum (‘System.IO.FileMode’)
#define.ClrFileModeOpen (‘Open’)
#define.ClrFileAccessEnum (‘System.IO.FileAccess’)
#define.ClrFileAccessWrite (‘Write’)
#define.ClrFileAccessRead (‘Read’)//(‘ReadWrite’)

System.IO.FileStream fileStream;
ClrObject fileMode;
ClrObject fileAccess;
str _filename = ‘C:\\Log.txt’;

System.Type typeOfByte;
System.Array arrayOfByte;
int arrayOfByteLength = 1;
int i;
System.Security.Cryptography.SHA1CryptoServiceProvider SHA1;
System.Text.ASCIIEncoding encoding;

str strError;
CLRObject exc;
CLRObject innerExc;
CLRObject clrExcMessage;
int Struct1[];
container cont;
;
try
{
typeOfByte = System.Type::GetType(“System.Byte”);
arrayOfByte = System.Array::CreateInstance( typeOfByte, arrayOfByteLength );

fileMode = CLRInterop::parseClrEnum(#ClrFileModeEnum, #ClrFileModeOpen);
fileAccess = CLRInterop::parseClrEnum(#ClrFileAccessEnum, #ClrFileAccessRead);
SHA1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
fileStream = new CLRObject(#ClrFileStream, _filename, fileMode, fileAccess);
arrayOfByte = SHA1.ComputeHash(fileStream);
fileStream.Close();

arrayOfByteLength = ClrInterop::getAnyTypeForObject(arrayOfByte.get_Length());
for( i = 0; i < arrayOfByteLength; ++i )
{
cont = conins(cont,i+1,(ClrInterop::getAnyTypeForObject( arrayOfByte.GetValue( i ) )));
print int2hex(ClrInterop::getAnyTypeForObject( arrayOfByte.GetValue( i ) ));
}
}
catch( Exception::Internal )
{
// BP Deviation Documented
exc = CLRInterop::getLastException();
if( exc )
{
clrExcMessage = exc.get_Message();
// BP Deviation Documented
strError = CLRInterop::getAnyTypeForObject( clrExcMessage );

throw error(strError);
}

}
catch( Exception::CLRError )
{
// BP Deviation Documented
exc = CLRInterop::getLastException();
if( exc )
{
clrExcMessage = exc.get_Message();
innerExc = exc.get_InnerException();

while(innerExc != null)
{
clrExcMessage = innerExc.get_Message();
innerExc = innerExc.get_InnerException();
}

// BP Deviation Documented
strError = CLRInterop::getAnyTypeForObject( clrExcMessage );

throw error(strError);
}

}

pause;
}

Uso de contenedores Con AX Business Connector Net

Filed under:.NET,4.0,5.0,axapta,desarrollo,dynamics,dynamics2009,x++ — posted by admin on February 2, 2009 @ 7:54 am

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using Microsoft.Dynamics.BusinessConnectorNet;

namespace ConsoleApplication3
{
class Program
{

static void Main(string[] args)
{
Axapta AX;
AX = new Axapta();
AX.Logon(“CNS”, null, “DYmanicsAx1:2713″ , null);
object[] Parmlist = new object[1];

AxaptaContainer Container = AX.CreateAxaptaContainer();
Container = (AxaptaContainer)AX.CallStaticRecordMethod(“InventDim”, “dimEnabledFieldList”, 1);
Console.WriteLine(BankAccountTable.Call(“balanceCur”, Container));

AX.Logoff();
}

Microsoft.Axapta.BusinessConnector Code Samples

Filed under:.NET,4.0,5.0,axapta,desarrollo,x++ — posted by admin on January 23, 2009 @ 5:29 am

Delete sample

// Execute a query to retrieve an editable record
// where the name is MyStateUpdated.
axRecord.ExecuteStmt(“select forupdate * from %1 where %1.Name ==
‘MyStateUpdated’”);

// If the record is found then delete the record.
if (axRecord.Found)
{
// Start a transaction that can be committed.
ax.TTSBegin();
axRecord.Delete();
// Commit the transaction.
ax.TTSCommit();
}

INSERT

// Create the .NET Business Connector objects.
Axapta ax;
AxaptaRecord axRecord;
string tableName = “AddressState”;

try
{
// Login to Microsoft Dynamics AX.
ax = new Axapta();
ax.Logon(null, null, null, null);

// Create a new AddressState table record.
using (axRecord = ax.CreateAxaptaRecord(tableName));
{

// Provide values for each of the AddressState record fields.
axRecord.set_Field(“NAME”, “MyState”);
axRecord.set_Field(“STATEID”, “MyState”);
axRecord.set_Field(“COUNTRYREGIONID”, “US”);
axRecord.set_Field(“INTRASTATCODE”, “”);

// Commit the record to the database.
axRecord.Insert();
}
}
catch (Exception e)
{
Console.WriteLine(“Error encountered: {0}”, e.Message);
// Take other error action as needed.
}
READ

// Create the .NET Business Connector objects.
Axapta ax;
AxaptaRecord axRecord;
string tableName = “AddressState”;

// The AddressState field names for calls to
// the AxRecord.get_field method.
string strNameField = “NAME”;
string strStateIdField = “STATEID”;

// The output variables for calls to the
// AxRecord.get_Field method.
object fieldName, fieldStateId;

try
{
// Login to Microsoft Dynamics AX.
ax = new Axapta();
ax.Logon(null, null, null, null);

// Create a query using the AxaptaRecord class
// for the StateAddress table.
using (axRecord = ax.CreateAxaptaRecord(tableName));
{

// Execute the query on the table.
axRecord.ExecuteStmt(“select * from %1″);

// Create output with a title and column headings
// for the returned records.
Console.WriteLine(“List of selected records from {0}”,
tableName);
Console.WriteLine(“{0}\t{1}”, strNameField, strStateIdField);

// Loop through the set of retrieved records.
while (axRecord.Found)
{
// Retrieve the record data for the specified fields.
fieldName = axRecord.get_Field(strNameField);
fieldStateId = axRecord.get_Field(strStateIdField);

// Display the retrieved data.
Console.WriteLine(fieldName + “\t” + fieldStateId);

// Advance to the next row.
axRecord.Next();
}
}
}

catch (Exception e)
{
Console.WriteLine(“Error encountered: {0}”, e.Message);
// Take other error action as needed.
}

UPDATE

// Create an Axapta record for the StateAddress table.
axRecord = ax.CreateAxaptaRecord(tableName);

// Execute a query to retrieve an editable record where the name is MyState.
axRecord.ExecuteStmt(“select forupdate * from %1 where %1.Name ==
‘MyState’”);

// If the record is found then update the name.
if (axRecord.Found)
{
// Start a transaction that can be committed.
ax.TTSBegin();
axRecord.set_Field(“Name”, “MyStateUpdated”);
axRecord.Update();

// Commit the transaction.
ax.TTSCommit();
}

Como imprimir directamente sobre la impresora desde x++

Filed under:3.0,desarrollo,x++ — posted by admin on April 15, 2008 @ 12:34 am

Uno de los principales problemas que se plantean al implementar facturas o informes es como imprimir verticalmente por regla general es imposible en impresoras matriciales ya es una odisea. Si nuestro cliente es muy pero q muy “rata” o “cicatero y no quiere entrar en la era de las nuevas tecnologías con una impresora láser o estamos atados por una ISO que nos obligue a dar formatos extraños a la factura, podemos utilizar las dll’s del sistema para acceder a los documentos e incluso voltear o girar las fuentes de impresión para imprimir el famoso registro empresarial de las facturas.

20080415090605_25.JPG

axl_gdi_2.xpo

Como contabilizar facturas de clientes o proveedores sin usar secuencias numericas

Filed under:3.0,axapta,desarrollo,x++ — posted by admin on April 7, 2008 @ 3:31 am

Buenas a todas y a todos. Por regla general las secuencias de facturación suelen configurarse y no dar problemas, pero en el caso que nos ocupa tenemos una multinacional que utiliza unos terminales de venta para generar facturas y albaranes etc, con numeraciones propias y esto hay que trasladarlo al AX con el minimo de problemas y de accesos a base de datos.

Nada de soluciones Salomónicas de update a “cholones” contra la custinvoicejour y cosas así que se os ve la pinta de “programatas” de medio pelo salidos de la vieja escuela del “clipper 5″, ahora el famoso “Delfi 6″. (jejejejej)

Bueno lo dicho aquí va el código para contabilizar facturas o albaranes con la numeración que queramos sin que el estándar de deje de chutar.

protected void insertJournal()
{;
ttsbegin;

numberSeq = this.allocateNumAndVoucher();
//axl numero de factura..
if (salesParmUpdate.invoiceid != ”)
{
number = salesParmUpdate.invoiceid;
numberSeq.parmNumberSequenceCode(”);
ttsbegin;
voucher = numberSeq.voucher();
ttscommit;
}
else
{
[number, voucher] = this.getNumAndVoucher();
}

if (this.updateNow())
{
this.postUpdate();

TransactionLog::create(this.transactionLogType(),this.transactionLogTxt());
ttscommit;
}
else
throw error(strFmt(“@SYS21533″));
}

Tan solo hay que sobre escribir el método insertjournal de la salesformletter

Como ejecutar un archivo cmd o .bat desde un cliente sobre el servidor AOS

Filed under:3.0,4.0,AOS,dynamics,x++ — posted by admin on March 27, 2008 @ 4:27 am

Para poder crear un archivo tipo bat o cmd con definirlo de esta manera “file = new asciiio(‘c:\\filex.bat’,'w’);” ya tenemos un fichero llamado filex.bat en c:\ . Ahora bien en nuestro c: o en el del sevidor???? Pues eso solo lo sabremos si el metdodo q hemos ejecutado se lanza del lado del cliente o del lado del servidor, y para salir de dudas mejor definir una metodo static y ponerle server para que de fijo se lance en el servidor donde se este ejecutando nuestro AOS (AX32serv.exe).

static server void Start()
{
asciiio file;
str txt;
;
winapi::deleteFile(‘C:\\file2.txt’);

file = new asciiio(‘c:\\filex.bat’,'w’);

if (file)
{
txt = (strfmt(‘net start “Axapta batch 1″ ‘));
file.write(txt);

file = null;

winapi::shellExecute(‘c:\\filex.bat’);
winapi::deleteFile(‘C:\\filex.txt’);
}

}

ftx_tpv_shutdownrestartservices.xpo

dibujo111111.JPG

Como pasar parametros entre objetos usando la clase args AX axapta

Filed under:3.0,4.0,Uncategorized,aot,axapta,desarrollo,dynamics,x++ — posted by admin on February 19, 2008 @ 5:01 am

Args  es utiliza para pasar argumentos al constructor de una clase. Args pueden transmitir información como el nombre, y los parámetros que llaman a una nueva clase.

Los formularios, informes y consultas utilizan  la clase Args como primer argumento en el constructor.

Pasandole el nombre del objeto a crear a una clase args y despues llamar a classfactory con estos argumentos podemos inicializar fomularios, informes etc.

    Args a = new Args(“CustTable”);
    formRun fr = ClassFactory.FormRunClass(a);
    fr.init();
    fr.run();
 

para recuperar el objeto args en la clase de destino, por regla general existe un metodo que nos devuelve este dato.

elment.args() en el caso de formulario.

El objetivo de esto es poder pasar a traves de args objetos completos a otros contextos de ejecución de forma que podriamos abrir un formulario inicial F1 ejecutar otro formulario secundario F2 y poder ejecutar metodos del formulario 1 desde el formulario 2.

un ejemplo.

Hemos creado un from con un metodo para recuperar el texto de un strignedit y este texto lo vamos a pintar desde un report, utilizando para ello una clase intermedia o el metodo del form que lo ha llamado.

fir_dem.xpo 

public void init()
{
    object ob;
    FIR_ReportClas FIR_ReportClas;

    super();

    //axl si no es la clase entonces es el formmm…
    if (classIdGet(element.args().caller()) == classNum(FIR_ReportClas))
    {
            FIR_ReportClas = element.args().caller();
            print FIR_ReportClas.texto();
    }
    else
    {
        ob = element.args().caller();
        print ob.texto();
    }

dibujoaaxxzee.bmp



image: detail of installation by Bronwyn Lace