Author Topic: First C# Autocad App  (Read 4319 times)

0 Members and 1 Guest are viewing this topic.

quamper

  • Guest
First C# Autocad App
« on: December 04, 2007, 10:10:12 AM »
I've been creating stuff for a little while now in Autocad using the managed .net api using VB.Net, however I've been pretty well convinced that I might as well go ahead and make the switch to C# so this is my first real Autocad program in C#, before I tackle something more ambitious. It's a little bit of cheating since I had recently written this same app in VB.Net a couple weeks back, but I figured it was a good start and in the process I cleaned it up alot and made some modifications I had been wanting to make to it. And it's a fairly basic program anyways.

That said, I'd love some feedback/criticism(constructive or otherwise).

The application is designed export part with little fuss. Our CNC Router Nesting software works with DWG files (not dxf's surprisingly), but each part has to be it's own file hence this application. The only thing quirky I can think of is that I don't check to see if a file with the name already exists because I don't really care in this situation.

Code: [Select]
// Necessary Imports
using System;
using System.Windows.Forms;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.ApplicationServices;

// Main Class
public class ExportClass
    {

    // Variables used for settings
    static string FolderName;
    static string LayerName = "label";
   
    // Define Autocad Command "PartExport"
    [CommandMethod("PartExport")]
    public static void PartExport()
    {
        // Checking to see if settings have already been established
        if (FolderName == null)
            ExportOptions();

        ExportPart();       
    }

    // Define Autocad Command "PartExOption"
    [CommandMethod("ExportOptions")]
    public static void PartExOption()
    {
        // If user wants to change options directly.       
            ExportOptions();
    }

    // Sets up folder path + name of layer to use for Part Labeling
    public static void ExportOptions()
    {
        FolderBrowserDialog FolderDialog = new FolderBrowserDialog();
        FolderDialog.Description = "Select Directory for Part Export";
        if (FolderName == null)
            FolderDialog.SelectedPath = "C:\\";
        else
            FolderDialog.SelectedPath = FolderName;
       
        DialogResult FolderResult = FolderDialog.ShowDialog();
            if (FolderResult == DialogResult.OK)
                FolderName = FolderDialog.SelectedPath;

        Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

        PromptResult LayerOption = ed.GetString(string.Format("Layer Name of Label? [{0}] : ", LayerName));

        if (LayerOption.StringResult != "")
            LayerName = LayerOption.StringResult;

    }

    // Main Part Exporting Method
    static void ExportPart()
    {
        Database db = HostApplicationServices.WorkingDatabase;
       
        // Start transaction for Open Drawing
        using (Transaction trans = db.TransactionManager.StartTransaction())
        {

            string MyFileName = null;
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            PromptSelectionResult SelectedItems = ed.GetSelection();

            if (SelectedItems.Value != null)
            {
                SelectionSet MySS = SelectedItems.Value;
                ObjectIdCollection MyObjIds = new ObjectIdCollection(MySS.GetObjectIds());

                // Find the label based on the previously specified layer name in the selection set to use as the part name.
                for (int i = 0; i < MySS.Count; i++)
                {
                    Entity MyEnt = (Entity)MySS[i].ObjectId.GetObject(OpenMode.ForRead);
                    if (MyEnt.Layer == "label"){
                        DBText Label = new DBText();
                        Label = (DBText)trans.GetObject(MyEnt.ObjectId, OpenMode.ForRead);
                        MyFileName = Label.TextString + ".dwg";                       
                    }
                }

                // If no label is found we don't want to create the new file.
                if (MyFileName == null)
                    MessageBox.Show("No Label Currently Selected or Set for Current Part");
                else
                {
                    // Create the new DWG file and Start Transaction with my Selection Set items.
                    Database NewDrawing = new Database(true, true);
                    using (Transaction NewTrans = NewDrawing.TransactionManager.StartTransaction())
                    {
                        BlockTable NewDwgBT = (BlockTable)NewTrans.GetObject(NewDrawing.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord NewDwgBTR = (BlockTableRecord)NewTrans.GetObject(NewDwgBT[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                        IdMapping myMap = new IdMapping();
                        NewDrawing.WblockCloneObjects(MyObjIds, NewDwgBTR.ObjectId, myMap, DuplicateRecordCloning.Replace, false);
                        NewTrans.Commit();
                        // Saving to version 2000 for legacy purposes.
                        NewDrawing.SaveAs(FolderName + "\\" + MyFileName, DwgVersion.AC1015);
                        NewDrawing.Dispose();
                    }
                }
            }
       }
    }

    }



Glenn R

  • Guest
Re: First C# Autocad App
« Reply #1 on: December 04, 2007, 03:43:22 PM »
Some things leap out at me:

1. Wrap your FolderBrowserDialog in a 'using' statement, or better yet, a try - catch - finally construct.
2. Always and I mean ALWAYS, check the return value of things, especially the promptresult type calls.

eg. PromptResult LayerOption - blahblah.
You should then check if the Promptresult was OK.

Other than that, welcome to the land of curly braces, semi-colons and case sensitivity  :-D

Cheers,
Glenn.

quamper

  • Guest
Re: First C# Autocad App
« Reply #2 on: December 04, 2007, 03:50:11 PM »
curly braces, semi-colons and case sensitivity

I've done alot of PHP development so that's nothing new. In fact I'm liking C# more than VB if for no other reason than that.

joseguia

  • Guest
Re: First C# Autocad App
« Reply #3 on: December 04, 2007, 10:42:01 PM »
Quamper,
 Just out of curiosity, what version of Visual Studio are you using?

quamper

  • Guest
Re: First C# Autocad App
« Reply #4 on: December 05, 2007, 08:40:07 AM »
I've been using 2008 Express but I use SharpDevelop as well somewhat.