Author Topic: Making Layers with Particular Linetypes  (Read 2280 times)

0 Members and 1 Guest are viewing this topic.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10818
  • class keyThumper<T>:ILazy<T>
Making Layers with Particular Linetypes
« on: December 04, 2005, 05:25:00 pm »
Posted code  is extracted from my rework of Lab03.

This post deals particularly with making Layers with color and LineType.

I've tried to handle
Metric or English Linetypes
Invalid Layer Name
Invalid Color numbers
Invalid and unavailable LineType Names

There is more code posted than need be. < I left in the Library stuff>
built with VSC#2005Express for AC2006
Any Comments ? ?

Code - C#: [Select]
  1.  
  2. #region System using declarations
  3. using System;
  4. using System.Diagnostics;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7.  
  8. using System.Text;
  9. using System.Drawing;
  10. using System.Reflection;
  11. using System.Windows.Forms;
  12. using System.ComponentModel;
  13. using System.Text.RegularExpressions;
  14. #endregion
  15.  
  16. #region AutoCAD COM Interop using declarations
  17. //// COM Interop References
  18. //// AutoCAD 2006 Type Library
  19. using Autodesk.AutoCAD.Interop;
  20.  
  21. //// AXDBLib AutoCAD/ObjectDBX Common 16.0 Type Library
  22. using Autodesk.AutoCAD.Interop.Common;
  23.  
  24. #endregion
  25.  
  26. #region AutoCAD Managed Wrappers using declarations
  27. //// Assembly acdbmgd .. ObjectDBX.NET Managed Wrapper
  28. //// Assembly acmgd .. Autocad.NET Managed Wrapper
  29. using Autodesk.AutoCAD.ApplicationServices;
  30. using Autodesk.AutoCAD.DatabaseServices;
  31. using Autodesk.AutoCAD.EditorInput;
  32. using Autodesk.AutoCAD.Geometry;
  33. using Autodesk.AutoCAD.Runtime;
  34. using Autodesk.AutoCAD.Colors;
  35. #endregion
  36.  
  37. #region Alias using declarations
  38. using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;
  39. #endregion
  40.  
  41. [assembly: ExtensionApplication(typeof(ClassLibraryLab03.kwbLab03StartApp))]
  42. [assembly: CommandClass(typeof(ClassLibraryLab03.Commands))]
  43.  
  44. namespace ClassLibraryLab03
  45. {
  46.    #region CommandClass
  47.    //-------------------------------------------------------------------------------
  48.    public class
  49.    Commands
  50.    {
  51.        [CommandMethod("Lab03Help", CommandFlags.Modal)]
  52.        static public void
  53.        Lab03Help()
  54.        {
  55.            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  56.  
  57.            ed.WriteMessage("\n  Testing Assembly kwbLab03 [kwb v:20051204]");
  58.            ed.WriteMessage("\n  Commands : LX1, LX2, LX3, LX4, LX5");
  59.        }
  60.  
  61.        //----------------------------
  62.        [CommandMethod("LX1", CommandFlags.Modal)]
  63.        public static void AssertLayerLX1()
  64.        {
  65.            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  66.            try
  67.            {
  68.                ObjectId layerId = LibTools.CreateLayer("TestX1", 3, "HIDDEN");
  69.                ed.WriteMessage("\n  layerId : " + layerId.ToString());
  70.            }
  71.            catch (Autodesk.AutoCAD.Runtime.Exception acEx)
  72.            {
  73.                ed.WriteMessage("\nError: " + acEx.Message);
  74.                return;
  75.            }
  76.        }
  77.        //----------------------------
  78.        [CommandMethod("LX2", CommandFlags.Modal)]
  79.        public static void AssertLayerLX2()
  80.        {
  81.            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  82.            try
  83.            {
  84.                ObjectId layerId = LibTools.CreateLayer(" ", 113, "CONTINUOUS");
  85.                ed.WriteMessage("\n  layerId : " + layerId.ToString());
  86.            }
  87.            catch (Autodesk.AutoCAD.Runtime.Exception acEx)
  88.            {
  89.                ed.WriteMessage("\nError: " + acEx.Message);
  90.                return;
  91.            }
  92.        }
  93.        //----------------------------
  94.        [CommandMethod("LX3", CommandFlags.Modal)]
  95.        public static void AssertLayerLX3()
  96.        {
  97.            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  98.            try
  99.            {
  100.                ObjectId layerId = LibTools.CreateLayer("TestX3", 13, "NONE");
  101.                ed.WriteMessage("\n  layerId : " + layerId.ToString());
  102.            }
  103.            catch (Autodesk.AutoCAD.Runtime.Exception acEx)
  104.            {
  105.                ed.WriteMessage("\nError: " + acEx.Message);
  106.                return;
  107.            }
  108.        }
  109.        //----------------------------
  110.        [CommandMethod("LX4", CommandFlags.Modal)]
  111.        public static void AssertLayerLX4()
  112.        {
  113.            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  114.            try
  115.            {
  116.                ObjectId layerId = LibTools.CreateLayer("Test X4", 230, "DOT");
  117.                ed.WriteMessage("\n  layerId : " + layerId.ToString());
  118.            }
  119.            catch (Autodesk.AutoCAD.Runtime.Exception acEx)
  120.            {
  121.                ed.WriteMessage("\nError: " + acEx.Message);
  122.                return;
  123.            }
  124.        }
  125.        //----------------------------
  126.        [CommandMethod("LX5", CommandFlags.Modal)]
  127.        public static void AssertLayerLX5()
  128.        {
  129.            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  130.            try
  131.            {
  132.                ObjectId layerId = LibTools.CreateLayer("TestX5", 30000, "");
  133.                ed.WriteMessage("\n  layerId : " + layerId.ToString());
  134.            }
  135.            catch (Autodesk.AutoCAD.Runtime.Exception acEx)
  136.            {
  137.                ed.WriteMessage("\nError: " + acEx.Message);
  138.                return;
  139.            }
  140.        }
  141.        //----------------------------
  142.    }
  143.    #endregion
  144.  
  145.  
  146.  
  147.    #region MainApp core
  148.    //-------------------------------------------------------------------------------
  149.    //public class Class1
  150.    //{
  151.    //}
  152.    #endregion
  153.  
  154.  
  155.    #region LibraryTools
  156.    //-------------------------------------------------------------------------------
  157.    public class LibTools
  158.    {
  159.        //----------------------------
  160.        public static ObjectId CreateLayer(string layerName, short layerColor, string linetypeName)
  161.        {
  162.            ObjectId layerId;
  163.            Database  db = HostApplicationServices.WorkingDatabase;
  164.            using (Transaction tr = db.TransactionManager.StartTransaction())
  165.            {
  166.                LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForWrite);
  167.  
  168.                if (lt.Has(layerName))
  169.                {
  170.                    layerId = lt[layerName];
  171.                    if (layerId.IsErased)
  172.                    {
  173.                        LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForWrite, true);
  174.                        ltr.Erase(false);
  175.                    }
  176.                }
  177.                else // create the layer here.
  178.                {
  179.                    if (layerColor > 255)
  180.                    {
  181.                        LibTools.PrintToCmdLine(string.Format(
  182.                            "\n ERROR: Could not use LayerColor \"{0}\", using O instead.", layerColor));
  183.                        layerColor = 0;
  184.                    }
  185.  
  186.                    LayerTableRecord ltr = new LayerTableRecord();
  187.                    ltr.Name = layerName;
  188.                    ltr.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, layerColor);
  189.                    ltr.LinetypeObjectId = GetOrLoadLinetypeId(linetypeName, db);
  190.                    layerId = lt.Add(ltr);
  191.                    tr.AddNewlyCreatedDBObject(ltr, true);
  192.                }
  193.                tr.Commit();
  194.            }
  195.            return layerId;
  196.        }
  197.        //----------------------------
  198.        public static ObjectId
  199.        GetOrLoadLinetypeId(string linetypeName, Database db)
  200.        {
  201.            ObjectId ltypeId = GetSymbolTableRecId(typeof(LinetypeTableRecord), linetypeName, db);
  202.            if (ltypeId.IsNull)
  203.            {
  204.                string[] ltypeFiles;
  205.                ltypeFiles = new string[3];
  206.                if (db.Measurement == MeasurementValue.Metric)
  207.                {
  208.                    LibTools.PrintToCmdLine(" \n Using Metric Linetypes");
  209.                    ltypeFiles[0] = "acadiso.lin";
  210.                    ltypeFiles[1] = "acad.lin";
  211.                    ltypeFiles[2] = "ltypeshp.lin";
  212.                }
  213.                else
  214.                {
  215.                    LibTools.PrintToCmdLine(" \n Using English Linetypes");
  216.                    ltypeFiles[0] = "acad.lin";
  217.                    ltypeFiles[1] = "acadiso.lin";
  218.                    ltypeFiles[2] = "ltypeshp.lin";
  219.                }
  220.                //---------------
  221.                int len = ltypeFiles.Length;
  222.                for (int i = 0; i < len; i++)
  223.                {
  224.                    try
  225.                    {
  226.                        // try to load the linetype from the external file
  227.                        db.LoadLineTypeFile(linetypeName, ltypeFiles[i]);
  228.  
  229.                        ltypeId = GetSymbolTableRecId(typeof(LinetypeTableRecord), linetypeName, db);
  230.                        if (ltypeId.IsNull == false)
  231.                            return ltypeId;
  232.                    }
  233.                    catch (Autodesk.AutoCAD.Runtime.Exception acEx)
  234.                    {
  235.                        if (acEx.Message == "eUndefinedLineType")
  236.                        {
  237.                            LibTools.PrintToCmdLine(string.Format(
  238.                                    "\n ERROR: Could not load linetype \"{0}\", using CONTINUOUS instead.",
  239.                                    linetypeName));
  240.                            ltypeId = db.ContinuousLinetype;
  241.                            return ltypeId;
  242.                        }
  243.                        else
  244.                        {
  245.                            LibTools.PrintToCmdLine(string.Format(
  246.                                "\n ERROR: in 'LibTools.GetOrLoadLinetypeId' loading linetype \"{0}\".",
  247.                                linetypeName));
  248.                            throw acEx;
  249.                        }
  250.                    }
  251.                }
  252.            }
  253.            return ltypeId;
  254.        }
  255.        //---------------------------- awej MgdDbg rev.
  256.        public static ObjectId
  257.        GetSymbolTableRecId(System.Type classType, string symName, Database db)
  258.        {
  259.            ObjectId tblId = GetSymbolTableId(classType, db);
  260.            ObjectId recId = new ObjectId();
  261.  
  262.            using (Transaction tr = db.TransactionManager.StartTransaction())
  263.            {
  264.                SymbolTable tbl = (SymbolTable)tr.GetObject(tblId, OpenMode.ForRead);
  265.                if (tbl.Has(symName))   // TBD: should indexer return ObjectId.null instead of throwing exception
  266.                    recId = tbl[symName];
  267.                tr.Commit();
  268.            }
  269.            return recId;
  270.        }
  271.        //---------------------------- awej MgdDbg rev.
  272.        public static ObjectId
  273.         GetSymbolTableId(System.Type classType, Database db)
  274.        {
  275.            Debug.Assert(classType != null);
  276.            Debug.Assert(db != null);
  277.  
  278.            if (classType == typeof(BlockTableRecord))
  279.                return db.BlockTableId;
  280.            else if (classType == typeof(DimStyleTableRecord))
  281.                return db.DimStyleTableId;
  282.            else if (classType == typeof(LayerTableRecord))
  283.                return db.LayerTableId;
  284.            else if (classType == typeof(LinetypeTableRecord))
  285.                return db.LinetypeTableId;
  286.            else if (classType == typeof(TextStyleTableRecord))
  287.                return db.TextStyleTableId;
  288.            else if (classType == typeof(RegAppTableRecord))
  289.                return db.RegAppTableId;
  290.            else if (classType == typeof(UcsTableRecord))
  291.                return db.UcsTableId;
  292.            else if (classType == typeof(ViewTableRecord))
  293.                return db.ViewTableId;
  294.            else if (classType == typeof(ViewportTableRecord))
  295.                return db.ViewportTableId;
  296.            else
  297.            {
  298.                Debug.Assert(false);
  299.                ObjectId nullObj = new ObjectId();
  300.                return nullObj;
  301.            }
  302.        }
  303.        //----------------------------
  304.        public static void
  305.        PrintToCmdLine(string str)
  306.        {
  307.            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  308.            ed.WriteMessage(str);
  309.        }
  310.        //----------------------------
  311.    }
  312.    #endregion
  313.  
  314.  
  315.    #region Public class StartApp
  316.    //-------------------------------------------------------------------------------
  317.    /// <summary>
  318.    /// The entry point for AutoCAD.
  319.    /// </summary>
  320.    public class
  321.    kwbLab03StartApp : IExtensionApplication
  322.    {
  323.        public void
  324.        Initialize()
  325.        {
  326.            Editor  ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  327.  
  328.            Commands.Lab03Help();
  329.            ed.WriteMessage("\n  Type 'Lab03Help' at the Command Line for assistance ...");
  330.        }
  331.        public void
  332.        Terminate()
  333.        {
  334.            // Does Nothing ... can't unload NET assembly ...
  335.        }
  336.    }
  337.    #endregion
  338. }
  339.  
  340.  


edit:kdub code formatting =csharp

« Last Edit: March 10, 2012, 06:02:04 pm by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

MP

  • Seagull
  • Posts: 16269
  • Warning: I may be trolling.
Re: Making Layers with Particular Linetypes
« Reply #1 on: December 04, 2005, 06:01:54 pm »
While I'm not currently coding in C# posts like this will be very helpful if/when I do -- thank you Kerry.
\|// Set goal. Experiment tirelessly until
|oo| practice has become expertise.  Loop.
|- | Dropbox | O'Reilly School | UltraEdit

MickD

  • Gator
  • Posts: 2588
  • I don't need a job, I need Money!!
Re: Making Layers with Particular Linetypes
« Reply #2 on: December 04, 2005, 07:34:10 pm »
Yep, there's some handy code there, nice work Kerry!

Just for an exersice, how about trying an enumerator for the GetSymbolTable function? I haven't used them much myself and you have to wonder in a case like this whether it's worth the extra code but if they were used in many methods they would be handy for a quick 'switch' instead of the 'if else' 's. Swings and Roundabouts I suppose ??...
"Typing is easy, maintenance is hard." - unknown

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10818
  • class keyThumper<T>:ILazy<T>
Re: Making Layers with Particular Linetypes
« Reply #3 on: December 04, 2005, 08:19:29 pm »
Hi Mick, may be worth a look at, If I understand what you mean .. I'll have a look when the crocodiles stop nipping .. :-)




Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

CmdrDuh

  • Automatic Duh Generator
  • King Gator
  • Posts: 4021
Re: Making Layers with Particular Linetypes
« Reply #4 on: December 05, 2005, 08:24:46 am »
Cool! Nice work Kerry.
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's pretty close

CmdrDuh

  • Automatic Duh Generator
  • King Gator
  • Posts: 4021
Re: Making Layers with Particular Linetypes
« Reply #5 on: December 06, 2005, 09:32:31 am »
Kerry, did you preload your template with all the using statements or do you type those every time?  Reason I ask, I was going to preload mine, but I cant find where it is installed to open it.
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's pretty close

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10818
  • class keyThumper<T>:ILazy<T>
Re: Making Layers with Particular Linetypes
« Reply #6 on: December 06, 2005, 09:40:41 am »
Hi David,
I have built a couple of AutoCAD templates.

Set it up with the using statements and References, then select Export Template from the File Menu
I then use that template to start a new Project.
Seems to work OK.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10818
  • class keyThumper<T>:ILazy<T>
Re: Making Layers with Particular Linetypes
« Reply #7 on: December 06, 2005, 09:47:44 am »
It seems the Templates are kept in a zip file ? ?

Mine are in
C:\Documents and Settings\ .... .... \My Documents\Visual Studio 2005\Templates\ProjectTemplates
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10818
  • class keyThumper<T>:ILazy<T>
Re: Making Layers with Particular Linetypes
« Reply #8 on: December 06, 2005, 09:53:44 am »
Yep, that IS the case. ...

I moved a zip and the associated project wasn't available  ,,  ;-)



Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--