Tuesday, April 24, 2012

MSVS Setup Autodesk Autocad 2012 Autoloader

After explaining how to create bundles and use the new Autoloader feature within Autodesk 2012 products to load plugins I show you how to create an msi of your bundle within Visual Studio. An msi is a very easy way to get things done correctly. Enjoy!!!


Download the full msi project.

Autodesk Autocad Autoloader

Introduction

With the launch of Autocad 2012 there is a new way to install custom made plug-ins build in MSVS. They refer to them as bundles or packages who are read by Autocad on startup. The Autoloader doesn't change anything to previous solutions who install plug-ins, but is an additional and new way of Autodesk to easily install all your plug-ins without too much hassle.


1.New C# Example Autoloader Project
Start a new C#.net project and name it to your heart's desire. (This example could easily be translated to VB.net). Make sure you create a class library project.

2.Add Autocad references
Add references to the acdbmgd and the acmgd dll. (These files are located inside your Autocad installation folder) Make sure you change the properties of the dll's inside MSVS and set it to Copy Local = False.

3.Set Autocad as startup while debugging

MSVS Full version
In the properties of your project make sure you debug using Autocad as an external program. This option is only available in the full version of MSVS. In the express version you'll need a work-around to accomplish the same behavior.

MSVS Express Edition
Add the following to your project xml file to launch Autocad from within MSVS C# Express.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
    <StartAction>Program</StartAction>
    <StartProgram>C:\Program Files\Autodesk\AutoCAD 2012\acad.exe</StartProgram>
  </PropertyGroup>
</Project>


4.Class Code
 Rename Class1.cs and name it Commands and place following code inside the class. Make sure you reference the acdbmgd assembly found in the autocad installation folder!

using Autodesk.AutoCAD.Runtime;
using System.Windows;

namespace AutoLoaderExample
{
    public class Commands
    {
        [CommandMethod("AutoLoaderExample")]
        public void AutoLoaderExample()
        {
            MessageBox.Show("AutoLoader Example");
        }
    }
}


Now that we have set up visual studio build your solution and we head over to the Autoloader bundle and its contents.

5.Availability Autoloader bundle

The first thing to point out is that it's possible to install the plug-in for all users and to install it for only a particular user.
·         For all user access to your plug-in we will place the plug-in in our installation folder under the map ApplicationPlugins. (Most likely this will be the Program Files/Autodesk/ ApplicationPlugins/ folder)
·         To install the plugin for a particular user place the plug-in inside the [AppDataFolder]/Autodesk/ ApplicationPlugins.


6.Autoloader map and file structure

It is important to understand that the autoloader looks for folders of a particular format. The folder has to look like this => AutoLoader.bundle, where the .bundle behind any given name is very important to the Autoloader to identify your bundle. The AutoLoader folder can be renamed to anything you like as long as it's followed by the .bundle.
 Because of the .bundle format we won't talk about plug-ins anymore if we talk about any .bundle under the ApplicationPlugins folder. I'll refer to them as bundles or packages.
Now we know that your bundle can be placed on 2 different locations on your hard drive let's look at the content of a one.

7.Autoloader contents

There are 2 files a bundle should always have inside, and it's the PackageContents.xml file which contains all necessary information for the autoloader on how to load your plug-in inside Autocad. And the second file is the assembly that contains all your Autocad commands. Or in case of multiple assembly files you could place them inside a separate folder. In my projects I try to separate my assemblies and resources within their own respective folder to make things more manageable.
In this example I'll place my bundle inside the "available to all Autocad users".


Inside the AutoLoader.bunde I place my example assembly , produced by Visual Studio on Build, and an PackageContents.xml file.


8.Assembly Location MS Visual Studio Example

For those who are new to how MSVS works when you have build the project you created earlier you can find the .dll inside the bin folder of your project. The default projects folder of MSVS can be found under Documents/ Visual Studio 2010/ and the picture should give you an idea how to find your assembly file.


9.PackageContent.xml definition

Place the following code inside the xml file you created earlier. If you placed yours inside a folder, make sure you adjust the attribute ModuleName to match the correct path.


<?xml version="1.0" encoding="utf-8" ?>
<ApplicationPackage SchemaVersion="1.0" Name=" AutoLoaderExample " AppVersion="1.0">
  <Components>
    <ComponentEntry AppName="AutoLoader"
             ModuleName="AutoLoaderExample.dll"
          AppDescription="AutoLoader Example" />
  </Components>
</ApplicationPackage>

Let's take a look at the contents of the xml file first. I've kept it very simple and only the bare minimum got placed inside the file to ensure the plug-in is loaded when Autocad is launched.
If you wish to define the file in depth, I advise you to take a look at the section provided inside AutoDesk Help which explains in detail how to apply certain element and attributes inside the xml file. As far as I know there isn't a schema definition that can help you with your xml definition so you'll have to do it with the information inside the Help file.
If I am not mistaking it also explains how to attach CUI files who then get loaded in the Plug-in ribbon section of Autocad 2012 products. If I find myself some time I'll tackle this one and post how it's done.

10.Finally launch Autocad!!
The assembly file should be loaded on startup and you should be able to execute the "ALExample" command. Hope it works out well!!

autoloader bundle example download

autoloader c# project download

More information can be found in the Help of Autocad (keyword:PackageContents.xml)

Monday, April 23, 2012

Comparer Project Part 1


Introduction
I started working as CAD-GIS engineer on 2nd of March, and ever since I haven't been posting anything new.

Recent activity
As I try to build a recap on what I have done so far I thought I’d share what’s been realized so far. Although I won’t be sharing the whole project here, I’ll be posting some portions and insights on how I dealt with the given assignment.
Let’s start by explaining what I had to accomplish.

My first small project
Too save you from a long story … In short …
I had to compare the contents of 2 AutoDesk Autocad DWG drawings on a few layers. Two technical drawers started on the same drawing and had to classify some objects on those layers. Because both can classify them differently, I had to compare the differences once they end their classification.
They had to be able to see and localize the differences and fix them in an appropriate manner afterwards.
That’s the project in a nutshell J

Architecture
My goal was to build a Data Access Layer that has the potential to be used in other projects as well. I also integrated some classes I wrote 1-2 years ago to make the application much more stable and flexible. I did the best I could to build a Model-View-ViewModel environment.
Let’s start by sharing a picture of the architecture I used within the project. 


Database Assembly DAL
The Data Access Layer is only the start of what should become a wrapper around the Autocad Libraries. The wrapper allows you to decouple layers and gives you the possibility to Unit-Test your project with sample data without the necessity of having a Autodesk product at hand to test the decoupled layers.
Although this method seems tedious at first, it should result in a gain of speed when developing new applications. 

Objective DAL
Basically you're building a library that gives you access to clean and tested code which reduces bugs and errors in future development.
At the moment, I am only working inside a Map environment, but if adjusted slightly, this setup should allow you to extend the framework to support programming towards other CAD Autodesk products build on AutoDesk AutoCad and expose their API.





Looking at this picture, it is quite obvious that using other products, build on AutoDesk Autocad's basic module, will end up using a AutoDesk Autocad Drawing as well.

Object oriented programming and libraries
Because we program in an object oriented environment it's an ideal opportunity to exploit this and build a reusable library. Although this is a first step to build something flexible and reusable, the path towards a good library won't be without it's pitfalls and setbacks. 

What might be reusable and valid code for your library in one project, might become unusable in certain particular situations. I'll try to prevent that as much as possible but I still have a long way to go to become a better object oriented programmer to exclude that from happening completely. Using the correct methods and pattern to build robust and flexible libraries will be a big challenge.

If you talk about objected oriented design, libraries and flexible code, we can't exclude the use of interfaces. That's why I'll be using those throughout this project because they are very powerful and give you the possibility to program flexible environments.


What's next?
In a next post I'll be explaining what I've done with the DAL and I'll create an example in C# demonstrating what the methods inside the classes do.

Thursday, February 23, 2012

ActionScript 3.0 - How to move an image over the canvas

This will be the first post of a series.
In this post we look at how to move an imported image over the stage.
  1. You'll need an image that will be used to move over the canvas. Could be any image you prefer really. There are plenty to be found on the internet.
  2. Start a new Actionscript 3.0 document in Flash CS5
  3. Import the image into your stage or library. File > Import > Import To Stage or CTRL+R
  4. Right-click the image and convert it to a symbol

A MovieClip will be added to your library and the item is ready to be instantiated using code at runtime.

Let's head over to the actions pane of our stage and write the necessary code to move the icon inside the canvas pressing the arrow keys UP-DOWN-LEFT & RIGHT.

First lines of code :

import flash.display.MovieClip;

//Declare a UserIcon of the type MovieClip
var userIcon:MovieClip;

//Instantiate the MovieClip
userIcon = new UserIcon;

//Add it to the DisplayList.
//On startup the imagelist it's children get added to the stage
stage.addChild(userIcon);

Launch the application. The picture should appear in the left-top corner of the canvas.

Make the image move code :

We need an Eventlistener who will monitor if a keyboard button is pressed.
We need a function who will determine what key is pressed and who acts accordingly.

//First create the Eventlistener which is a KeyboardEvent
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);

//Now we are monitoring keyboard button keydown events but we
//still have to determine what key is pressed and then act accordingly
//We will also need to set the boundary of the stage to make sure the picture
//Doesn't dissapear when we move it out of the canvas boundaries
function keyDown(e: KeyboardEvent):void{

       //Use the keycode of the eventlistener to determine what key got pressed.
       switch(e.keyCode)
       {
             //In case the keyboard button UP is pressed
             case Keyboard.UP:
                    if(userIcon.y > 0)
                           userIcon.y = userIcon.y - 5;
                    break;
             //In case the keyboard button DOWN is pressed
             case Keyboard.DOWN:
                    if(userIcon.y +5 < stage.stageHeight -userIcon.height)
                           userIcon.y = userIcon.y + 5;
                    break;
             //In case the keyboard button LEFT is pressed
             case Keyboard.LEFT:
                    if(userIcon.x > 0)
                           userIcon.x = userIcon.x - 5;
                    break;
             //In case the keyboard button RIGHT is pressed
                    case Keyboard.RIGHT:
                    if(userIcon.x +5 < stage.stageWidth -userIcon.width)
                           userIcon.x = userIcon.x + 5;
                    break;
                    trace(e.keyCode);
       }
}


Next post we'll add more features! 

Thursday, January 26, 2012

Flash CS5 & Learning ActionScript 3.0



Flash CS5 and programming in actionscript is one of the courses have to complete this year at school. I won’t be writing any complex code or examples here as I have to start from scratch myself as well.

This isn’t a Flash CS5 course either and focus will mainly be on how to use action script with Flash CS5.
I’ll be using documentation received at school which explains the basics in Flash CS5 and a “Learning Actionscript 3.0” book from O’Reilly 2nd edition. While completing the chapters I’ll use information from the internet, as reference and guide, as well.

First of all you have to understand that there are 2 ways to execute your Actionscript code inside our Flash document, either by writing code inside the Frame Actions or by creating a class which you tie to the flash document or objects.

Second, we’ll be adding visuals to a to a display list used inside you Flash movie and those will appear on our Canvas if declared, instantiated and configured correctly.

I’ll demonstrate this by using 2 very simple examples.

Example 1 : Writing code inside the Actions Frame.

To access the Actions frame => Window/Actions or press F9.
Inside the Frame write the following code :

//First Application using a timeline script.
//This import should appear automatically
//once you use the TextField Class
import flash.text.TextField;
//Declare and instantiate a new TextField data type.
var txtFld : TextField = new TextField();
//Add the TextField to the Display List.
addChild(txtFld);
//Assign text to the text-property of the TextField using default values.
txtFld.text = "My First Application in Flash CS5";
//Make the TextField wider so we see the complete message.
txtFld.width = 250;

If you run the code CTRL+ENTER you should see the text value, assigned to the TextBlock, appear in the upper-left corner of the scene.

Example 2 : Create a class and assign it to the document.

To create a new class => File/New or CTRL+N and select Actionscript 3.0 Class. Store the class somewhere you’ll find it back easily. Open the properties pane of your flash document and write your class name inside the Class TextBox. Be sure to place both files (flash and class) at the same location.

Because the class is tied to the flash document (which in essence is an object) the default constructor of the class will be executed when you run your flash document.

Inside the class (.as)  write the following code :

package 
{
    //Imports
    import flash.text.TextField;
    import flash.display.MovieClip;
   
    public class ExOne extends MovieClip
    {
        public function ExOne()
        {
            // constructor code
            //Declare and instantiate a string variable
            var str:String = "Flash Actionscript";

            //Generates a random number between 0 and 1 and executes when less then           0.5
            if(Math.random() < 0.5)
            {
                //Declare and instantiate a new TextField
                var txtField:TextField = new TextField();
                //Add the TextField to the list of Visuals
                addChild(txtField);   
                //Fill the text value of our visual with our string variable
                txtField.text = str;
            }
            else
            {
                //For loop. Output your string 2 times
                for(var i:int = 0; i<2;i++)
                {
                    trace(str);
                }
            }
        }
    }
}

First we generate a random number ,using the Actionscript Random() function. Then we check whether the result ,which should be a number between 0 and 1, is greater or less then 0.5.

If it’s smaller  we create a TextField add it to the Flash visual List and change the TextBlock textproperty to "My First Application in Flash CS5". The TextBlock should appear in the left upper corner,on the scene, when you launch your flash document (CTRL+ENTER) displaying the assigned text value.

If it’s greater then 0.5 we trace our string value to our Output Pane 2 times.

The above code uses an If-statement and a For-loop to iterate through the code it contains.

Tuesday, November 29, 2011

XML to HTML Using XSLT and C#

 
I was looking for a way to print my objects in a project and this post should reflect what I've come up with so far. It's without a doubt not the best way to do it but for now it gets the job done.
What I basically do is make an XML file of the objects I am willing to display and then convert them to html. I have created an XSL file, which functions as template, that will generate the html file using the xml data file.
Once the HTML is created we use common Printing provided by our Web browser.
Objects => XML => XML+XSL => HTML => Web Browser Print
You could ask yourself : "why the hell should I go through all this hassle just to make a html file?". Well, I find it very handy to be able to write my objects to xml. It allows you to easily share, sync and validate data with other applications. So once you got your xml exports available on all your objects you can easily convert them to html and use that as your printing environment.

This example only covers the basic idea and should be polished once you descide to use this inside a real/big project. Even the concept of writing your data to an xml file before you generate your html is questionable.

Anyway, I am pretty sure there are many things you could change or even improve to get a simular result.
Following example is made in C# using a console application and reflects the basic principle that is used to accomplish the html result.
Throughout the example I used an Employee class that will represent the objects we are about to export to an HTML file.
1. Create a c# console application
2. Inside the console application create an Employee class
    class Employee
    {
        int id;
        string firstName;
        string lastName;
        int salary;
        public Employee(int id, string firstname, string lastname, int salary)
        {
            this.id = id;
            this.firstName = firstname;
            this.lastName = lastname;
            this.salary = salary;
        }
        public int Id { get { return id; } }
        public string FirstName { get { return firstName; } }
        public string LastName { get { return lastName; } }
        public int Salary { get { return salary; } }
    }

3. The main method of our console application holds the rest of our code used within C#.
static void Main(string[] args)
        {
            //The Array that will hold our Employee objects
            Employee[] employees = new Employee[2];
            //Adding 2 objects to our previously created Array
            employees[0] = new Employee(1, "Robby", "Cattoor", 200);
            employees[1] = new Employee(2, "Bjorn", "Cattoor", 500);

            //We use the using statement to make sure the object is correctly closed            and disposed after use.
            using(XmlWriter writer = XmlWriter.Create(@"d:\employees.xml"))
            {
                //Start the xml document
                writer.WriteStartDocument();
                //Start an element that will hold all employees
                writer.WriteStartElement("Employees");

                foreach(Employee employee in employees)
                {
                    //Start an employee element
                    writer.WriteStartElement("Employee");

                    writer.WriteElementString("Id",employee.Id.ToString());
                    writer.WriteElementString("Firstname",
                    employee.FirstName.ToString());
                    writer.WriteElementString("Lastname",
                    employee.LastName.ToString());
                    writer.WriteElementString("Salary",employee.Salary.ToString());

                    //Close the employee element
                    writer.WriteEndElement();
                }
                //Close the employees element
                writer.WriteEndElement();
                //Close the document
                writer.WriteEndDocument();
            }

            //Declare and create a new XSLT processor object that implements the XSLT           version 1.0 recommendation
            XslCompiledTransform transform = new XslCompiledTransform();
            //Load the XSL we created
            transform.Load(@"d:\employees.xsl");
            //Call the transform method to transform you xml to an xml output
            transform.Transform(@"d:\employees.xml", @"d:\result.html");
        }

Note : Adjust the location of your xml, xsl and html accordingly

4. Leaves us with the definition of our XSL file that will function as our style sheet and template.
<?xml version="1.0" encoding="utf-8"?>
<!--Stylesheet version & namespace reference-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--Template definition-->
<xsl:template match="/">
<!--Html opening tag-->
<html>
<!--Body opening tag-->
<body>
<!--Html title-->
<H2>Testing XSLT on Employees</H2>
<!--Table definition-->
  <table border ="1">
<!--Table first row containing 4 headers-->
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Salary</th>
</tr>
<!--Foreach loop selecting all employees-->
<xsl:for-each select="Employees/Employee">
<!--Each employee will result in a row filling each cell in each column containing our Employee data-->
<tr>
<td><xsl:value-of select="Id"/></td>
<td><xsl:value-of select="Firstname"/></td>
<td><xsl:value-of select="Lastname"/></td>
<td><xsl:value-of select="Salary"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Running the program will result in a xml-file and a html file at the location specified inside your static Main() method. You could open the html file inside your default browser after creation or use a .Net Web Browser control to display your result. Printing can now be done using the built-in web browser printing capabilities. Further styling can be done inside the XSL-file inline or using CSS.
Result Code :