Difference between Refresh(), Reread(), Research() and ExecuteQuery() in AX 2012

In X++ we have the below methods for fetching data after any changes are made, below is the short description of what they are and when to use each one.

Refresh() refreshes the user view with whats stored in the caches. This does not touch the DB.
Use this after any form change has been made through code.

ReRead() fetches only the current record from database and does not re read the complete datasource.
Use this when you need to update only the current record after modifying any value.

ReSearch() will execute the same query again and fetch the results from the database.
Use this if you need to get the current most data from database.

ExecuteQuery() will run the query again just like research does but it will also take any query changes into account.
Use this is you have modified the query on run-time and need the updated results according to the new query.

Advertisements

Till when do I keep trying?

Everyone has dreams, not all come true but those who chase after their dreams often wonder till when do you chase them? what time should one give up? what if its just not going to happen? First of all know this that every successful person who has achieved his or her dream and made the impossible possible has had these thoughts many times over during their journey and what led them to success was ignoring these thoughts and never giving up.

Never stop trying, you might be this close.

 

The picture above says it all. The dream dies when we want it to die. Worked too hard, take a break but dont quit and get back on it with a fresh mind and will to achieve it this time around. Perfecting something takes time and so does achieving something big or doing something different. Normal is not what you want to be, do you ever refer to a billionaire as normal or the top athlete normal; think for a moment would you ever call Mr. Usain Bolt normal? the answer in your mind is probably no because people like that are extra ordinary! they are not even close to the average Joe. To be successful, to be an achiever and to be ahead of the game; you have to be not normal; you gotta do what others don’t; think what others don’t so you can achieve what others don’t. Now go out there and never quit! Be consistent and show persistence towards your goals so you may one day achieve them.

 

O ye who believe! Persevere in patience and constancy; vie in such perseverance; strengthen each other; and fear Allah.that ye may prosper (Surah Al-Imran, 200)

Connecting to an External Database from AX 2012 using ODBC

To connect to an external database with X++ you can use Open Database Connection (ODBC) protocol through the OdbcConnection class among other ways. This approaches requires you to setup us a Data Source Name(DSN) on your server machine with the required access. Below is the code sample for how you can achieve this.To read more about this visit MSDN.

 

// X++, Main method in a class.
static public void Main(Args _args)
{
    LoginProperty loginProperty;
    OdbcConnection odbcConnection;
    Statement statement;
    ResultSet resultSet;
    str sql, criteria;
    SqlStatementExecutePermission perm;
    ;

    // Set the information on the ODBC.
    loginProperty = new LoginProperty();
    loginProperty.setDSN("dsnName");
    loginProperty.setDatabase("databaseName");

    //Create a connection to external database.
    odbcConnection = new OdbcConnection(loginProperty);

    if (odbcConnection)
    {
        sql = "SELECT * FROM MYTABLE WHERE FIELD = "
            + criteria
            + " ORDER BY FIELD1, FIELD2 ASC ;";

        //Assert permission for executing the sql string.
        perm = new SqlStatementExecutePermission(sql);
        perm.assert();

        //Prepare the sql statement.
        statement = odbcConnection.createStatement();
        resultSet = statement.executeQuery(sql);

        //Cause the sql statement to run,
        //then loop through each row in the result.
        while (resultSet.next())
        {
            //It is not possible to get field 3 and then 1.
            //Always get fields in numerical order, such as 1 then 2 the 3 etc.
            print resultSet.getString(1);
            print resultSet.getString(3);
        }

        //Close the connection.
        resultSet.close();
        statement.close();
    }
    else
    {
        error("Failed to log on to the database through ODBC.");
    }
}

Connecting to an External Database from AX 2012 using SqlClient classes

Here is how you can connect to an external database using X++ SqlClient class. This is among the few others approaches you can connect to an external database.

public System.Data.SqlClient.SqlConnection getConnection()
{
str connectionString;

System.Exception exception;
System.Data.SqlClient.SqlConnection connection;

connectionString = “Persist Security Info=False;User ID=UserID;Pwd=Password;Initial Catalog=DatabaseName;Data Source=localhost;”;

try
{
connection = new System.Data.SqlClient.SqlConnection(connectionString);
connection.Open();

return connection;
}
catch (Exception::Error)
{
error(“An exception has occurred.”);
}
catch (Exception::CLRError)
{
error(“A CLR exception has occurred.”);

exception = CLRInterop::getLastException();

if (exception != null)
{
info(exception.ToString());
}
}

return null;
}

To run a query after a successful connection, use this code:

System.Data.SqlClient.SqlConnection conn;
System.Data.SqlClient.SqlCommand cmd;
System.Data.SqlClient.SqlDataAdapter da;
System.Data.SqlClient.SqlDataReader dr;
System.Exception netExcepn;

str sql, attributeName, attributeValue;
str 30 materialCode;

mzkConnectToDB = new MzkConnectToDB();
conn = mzkConnectToMSDgen.getConnection();

sql = strFmt(“select * from tablename;”);
cmd = new System.Data.SqlClient.SqlCommand(sql,conn);

dr = cmd.ExecuteReader();

while(dr.Read())
{
try
{
materialCode = dr.get_Item(‘material_id’);

}
}
catch(Exception::Error)
{
error(“@SYS85688”);
}
}

//Close the connection.
dr.Close();
conn.Close();
}

Solution to Error: Save encoded certificate to store failed => 0x5 (5)

While creating a certificate with the MakeCert utility you might face this Error: Save encoded certificate to store failed => 0x5 (5) as I did, dont be worried its not about your command the solution to this is to simply start your command prompt or powershell as an administrator and then run the command; the certificate will be created successfully.

Start Here

New to MohsinKhalid.com? Welcome aboard.

MohsinKhalid is a personal career, lifestyle and travel blog. It’s my outlet to share thoughts and experiences on the work I do, the places I go and the tips I have in general about life.

The blog covers 3 main topics (please click on each to get into more detail):

 Career

Lifestyle

Travel

If you would like to browse through my posts in chronological  order or simply pick a post by category or tag, you can find all content easily on the left sidebar.

#EuropeTour Part 2: 11 Things You Should Not Forget To Pack

So you have gotten your visa and tickets, everything seems to be in order and you are ready to pack for your Europe trip, besides clothes and the stuff you will want to take with you, I want to mention the things you should not forget. So whether you are going in the summer or winter here is what you must have with you.

Image credit: The Disney Den
  1. An empty bottle of water.
  2. Good shoes, its best to have long backs mostly called work boots cause bare in mind you need to walk a lot. I got myself these:
  3. Your own toiletries.
  4. Dry snacks.
  5. A phone that has a good battery, none have a good battery these days so I kept two phones.
  6. Two pin socket adapter, like the ones below (all hotels/hostels have sockets that fit only these) if you dont have one you might have to buy one for as much as 4 euros.
  7. Good quality padlocks, keep at least one extra padlock with you.
  8. A Diary or notebook that contains your hotel addresses(write down the route you plan to take from airport to hotel and from hotel to airport); flight, bus and train details along with the activities you plan to do each day or in each city. This helped me a lot as there is so much to see and so much to do that you might miss out on something you should have included in your trip. Keep this diary with you at all times.
  9. Medicines, pain killers, muscle relaxants and others if you need any.
  10. Plastic bags, lots of them to keep any wet or dirty clothes.
  11. Tissue roll.

Bonus: Earplugs and a sleep mask.

Try to stay as light as possible, keep a 20 – 25 kg suitcase and one backpack that you will carry everywhere. Remember if you are on a budget, even if you are not its always good to take the metro, bus or tram to where ever you want to go, public transport system is really good in Europe specially in Turkey; taxi’s are to be avoided as much as possible; therefore pack keeping in mind that it should be easy for you to travel with all of your stuff. If you plan to take domestic flights then you will have to pay a good amount of money (30-40 euros) just for that suitcase. They allow hand carries that are not more than 10kg. However you can take your suitcase without any extra charge for baggage while travelling through train or bus. Lastly to save space remember to roll and not to fold. Hope this help, stay tuned for more in this series!