martes, 17 de julio de 2012

Leer un CSV Dynamics AX 2012 Con ADO


static void Job57(Args _args)
{
 
    System.Data.Common.DbConnection connection;
    System.Data.Common.DbCommand command;
    System.Data.SqlClient.SqlDataReader dataReader;
    System.Data.Common.DbProviderFactory factory=System.Data.Common.DbProviderFactories::GetFactory("System.Data.OleDb");
    int contar;
    ;
    new InteropPermission( InteropKind::ClrInterop ).assert();


    connection=factory.CreateConnection();
    connection.set_ConnectionString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\AbinsaCobranza\\;Extended Properties=\"text;HDR=Yes;FMT=Delimited\"");

    command=factory.CreateCommand();
    command.set_CommandText("select * from BANREGIO.csv");
    command.set_Connection(connection);

    //executing SQL-query
    try
    {
        //open within catch, so that the object can correcly be disposed
        //all these try-catch are quite ennoying in X++, but this because
        //X++ does not know finally...
        connection.Open();
        try
        {
            //All code after the open must be in a seperate catch, so that the
            //open connection-object can correcly be disposed.
            dataReader = command.ExecuteReader();

            while(dataReader.Read())
            {
                if(contar>=10)
                {
                   // contar=dataReader.get_FieldCount();
                    //use the named columns instead of index.
                   info(int2str(contar));
                   print dataReader.get_Item(6);
                    pause;
                }
               
               
                contar++;

            }
            //Dispose ADO.Net objects ASAP
            dataReader.Dispose();
        }
        catch //should be more precise in a real-world application
        {
            //if exception occures while reading, DataReader need to be
            info(CLRInterop::getLastException().ToString());
            dataReader.Dispose();
        }
        catch(Exception::CLRError) //CLR exception need to be handled explicitely
        //otherwise they might be 'lost'. Happy copy&pasteing
        {
            //if exception occures while reading, DataReader need to be
            info(CLRInterop::getLastException().ToString());
            dataReader.Dispose();
        }
        connection.Dispose();
    }
    catch //should be more precise in a real-world application
    {
        info(CLRInterop::getLastException().ToString());
        connection.Dispose(); //disposing connection if it fails before opening it
    }
    catch(Exception::CLRError)
    {
        info(CLRInterop::getLastException().ToString());
        connection.Dispose();
    }
    command.Dispose();
    CodeAccessPermission::revertAssert();


}

No hay comentarios:

Publicar un comentario