Thursday, March 4, 2010

CLR Interop in X++ Example 1: Obtaining a Screen Shot

As part of a custom error handling routine, I came up with the idea of taking an automatic screen shot of the AX environment at the moment an error occured, which could then be emailed along with other error details to the development team. Whether or not such functionality is actually useful in a production environment is not the point of this entry. This idea rather, was more or less a proof of concept, and my first attempt at utilizing CLR Interop in X++.

The following simple code snippet is a function in C#.NET which simply takes a screen shot of the primary screen, and saves it to a specified location as a PNG file.

bool CaptureScreen(string SaveToFileName)
{
bool success = true;

try
{
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
bitmap.Save(SaveToFileName, ImageFormat.Png);
}
catch
{
success = false;
}

return success;

}

The second code snippet is my translation of the code from C# to X++

boolean CaptureScreen(str SaveToFileName)
{
System.Drawing.Bitmap bitmap;
System.Drawing.Graphics graphics;
System.Windows.Forms.Screen primaryScreen;
System.Drawing.Rectangle bounds;
boolean success;
;

success = true;

try
{
primaryScreen = System.Windows.Forms.Screen::get_PrimaryScreen();
bounds = primaryScreen.get_Bounds();

bitmap = new System.Drawing.Bitmap(bounds.get_Width(), bounds.get_Height());
graphics = System.Drawing.Graphics::FromImage(bitmap);

graphics.CopyFromScreen(0,0,0,0, bitmap.get_Size());

bitmap.Save(SaveToFileName, System.Drawing.Imaging.ImageFormat::get_Png());
}
catch
{
success = false;
}

return success;
}



The benefit of first writing a routine in .NET, whether it be in C# or VB.NET, is that you can use the rich GUI of Visual Studio to help you more easily create a CLR based X++ method. Simply by moving the mouse over a given object in your .NET code, you will be able to retrieve the exact namespace of the objects that will need to be explicitly defined in your X++ code. Coming soon, Example 2, which will feature the C# and X++ functions to send the saved PNG in an email...

No comments:

Post a Comment