.NET

Reply
Contributor
JONTHEPOPE
Posts: 20
Registered: ‎12-03-2009
Message 1 of 9 (177 Views)
Accepted Solution

add linetypes to layers

177 Views, 8 Replies
07-17-2014 07:45 AM

How do I add linetype to an array of layers

 

//line types are loaded but how do I assign them to a certain name

        '' Open the Layer table for read
        Dim acLyrTbl As LayerTable
        acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, _
                                     OpenMode.ForRead)

        '' Define an array of layer names
        Dim sLayerNames(2) As String
        sLayerNames(0) = "ACIRed"
        sLayerNames(1) = "TrueBlue"
        sLayerNames(2) = "ColorBookYellow"

        '' Define an array of colors for the layers
        Dim acColors(2) As Color
        acColors(0) = Color.FromColorIndex(ColorMethod.ByAci, 1)
        acColors(1) = Color.FromRgb(23, 54, 232)
        acColors(2) = Color.FromNames("PANTONE Yellow 0131 C", _
                                      "PANTONE(R) pastel coated")

        Dim nCnt As Integer = 0

        '' Add or change each layer in the drawing
        For Each sLayerName As String In sLayerNames

            If acLyrTbl.Has(sLayerName) = False Then
                Using acLyrTblRec As LayerTableRecord = New LayerTableRecord()

                    '' Assign the layer a name
                    acLyrTblRec.Name = sLayerName

                    '' Upgrade the Layer table for write
                    If acLyrTbl.IsWriteEnabled = False Then acLyrTbl.UpgradeOpen()

                    '' Append the new layer to the Layer table and the transaction
                    acLyrTbl.Add(acLyrTblRec)
                    acTrans.AddNewlyCreatedDBObject(acLyrTblRec, True)

                    '' Set the color of the layer
                    acLyrTblRec.Color = acColors(nCnt)
                End Using
            Else
                '' Open the layer if it already exists for write
                Dim acLyrTblRec As LayerTableRecord = acTrans.GetObject(acLyrTbl(sLayerName), _
                                                                        OpenMode.ForWrite)

                '' Set the color of the layer
                acLyrTblRec.Color = acColors(nCnt)
            End If

            nCnt = nCnt + 1
        Next

        '' Save the changes and dispose of the transaction
        acTrans.Commit()
    End Using
End Sub

 

 

 

Well, not seeing your whole code and not knowing the drawing you use to test your code, it is not easier to go through your partial code to identify what is wrong, than just write some code to show you how it works.

 

Have you step through your code in debugging, which should lead you easily to where the exception occurs and you can usually find out what is the reason.

 

Anyway, here is some simple code that set linetype of a layer ("Layer1", if not exists, create it; and its linetype is "Continuous" by default) from to "Hidden" (assume this linetype has already been loaded into the current drawing database):

 

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
[assembly: CommandClass(typeof(SetLayerLineType.MyCadCommands))]
namespace SetLayerLineType
{
public class MyCadCommands
{
[CommandMethod("SetLT")]
public void SetLayerLineType()
{
Document dwg = CadApp.DocumentManager.MdiActiveDocument;
if (dwg == null) return;
Editor ed = dwg.Editor;
try
{
SetLayerLineType(dwg, "layer1", "Hidden");
}
catch (System.Exception ex)
{
ed.WriteMessage(
"\nError: {0}\n{1}", ex.Message, ex.StackTrace);
}
finally
{
Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
}
}
private void SetLayerLineType(
Document dwg, string layerName, string lineTypeName)
{
using (Transaction tran =
dwg.Database.TransactionManager.StartTransaction())
{
LayerTable layerTable = (LayerTable)tran.GetObject(
dwg.Database.LayerTableId, OpenMode.ForRead);
LinetypeTable lineTable = (LinetypeTable)tran.GetObject(
dwg.Database.LinetypeTableId, OpenMode.ForRead);
ObjectId lineTypeId = ObjectId.Null;
if (lineTable.Has(lineTypeName))
{
lineTypeId = lineTable[lineTypeName];
}
LayerTableRecord layer;
if (layerTable.Has(layerName))
{
layer = (LayerTableRecord)tran.GetObject(
layerTable[layerName], OpenMode.ForRead);
LinetypeTableRecord lineType=(LinetypeTableRecord)
tran.GetObject(lineTypeId,OpenMode.ForRead);
dwg.Editor.WriteMessage(
"\nLine type of existing layer \"{0}\" is {1}",
layer.Name, lineType.Name);
//set to desired linetype
if (!lineTypeId.IsNull)
{
layer.UpgradeOpen();
layer.LinetypeObjectId = lineTypeId;
}
}
else
{
layer = new LayerTableRecord();
layer.Name = layerName;
layerTable.UpgradeOpen();
layerTable.Add(layer);
tran.AddNewlyCreatedDBObject(layer, true);
//Before a new layer is commited in the transaction,
//its LineTypeObjectId is Null, unless being assigned explicitly
//However, if no linetypeObjectId is assigned, the new layer would
//get "Continuous" line type upon transaction committing
dwg.Editor.WriteMessage(
"\nnewly created layer \"{0}\" with linetypeID->{1}",
layerName,
layer.LinetypeObjectId.ToString());
//Set to desired linetype
if (!lineTypeId.IsNull)
{
layer.LinetypeObjectId = lineTypeId;
}
}
//Prove linetype has been set to the layer
if (!lineTypeId.IsNull)
{
LinetypeTableRecord lt = (LinetypeTableRecord)tran.GetObject(
layer.LinetypeObjectId, OpenMode.ForRead);
dwg.Editor.WriteMessage(
"\nLineType has been set to {0}", lt.Name);
}
tran.Commit();
}
}
}
}

 

*Expert Elite*
norman.yuan
Posts: 1,063
Registered: ‎04-27-2009
Message 2 of 9 (165 Views)

Re: add linetypes to layers

07-17-2014 09:35 AM in reply to: JONTHEPOPE

Just like how you set layer's color, you set layer's linetype by assign LayerTableRecord.LineTypeObjectId property a valid ObjectId that points a LineTypeTableRecord.

 

Database.LineTypeTableId -> LineTypeTable -> LineTypeTable[line type name]

 

 

Contributor
JONTHEPOPE
Posts: 20
Registered: ‎12-03-2009
Message 3 of 9 (162 Views)

Re: add linetypes to layers

07-17-2014 09:58 AM in reply to: norman.yuan

I'm confused can I set a line type to a layer?

I don't really know how to put my linetype on to my layer.

I tried your example but I don't understand fully how to get it to work.

 

 

// Save the changes and dispose of the transaction
                            acTrans.Commit();
          }
              // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
               
                // Open the Layer table for read
        LayerTable acLyrTbl;
        acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                        OpenMode.ForRead) as LayerTable;

            string getnewline = "M-ANNO-TEXT-NEWW";
            LayerTableRecord acLyrTblRec;
                
                if (acLyrTbl.Has(getnewline) == true) 
                {
                    acLyrTblRec = acTrans.GetObject(acLyrTbl[getnewline], OpenMode.ForRead) as LayerTableRecord;
                }

                // Open the Layer table for read 
                
                LinetypeTable acLinTbl; 
                acLinTbl = acTrans.GetObject(acCurDb.LinetypeTableId,                                    
                                            OpenMode.ForRead) as LinetypeTable; 
                
                if (acLinTbl.Has("RETURN") == true) 
                {

                    // Upgrade the Layer Table Record for write           
                    acLyrTblRec.UpgradeOpen(); 
                    // Set the linetype for the layer           
                    acLyrTblRec.LinetypeObjectId = acLinTbl["RETURN"]; } 
                // Save the changes and dispose of the transaction 
                
                acTrans.Commit(); } } 

                        }
                    }
                
            

 

*Expert Elite*
norman.yuan
Posts: 1,063
Registered: ‎04-27-2009
Message 4 of 9 (155 Views)

Re: add linetypes to layers

07-17-2014 10:09 AM in reply to: JONTHEPOPE

You code looks OK to me and it should change the linetype of layer "M-ANNO-TEXT-NEWW" to a linetype called "RETURN", if the "RETURN" line type has been loaded into the drawing previously. Have you tried to run this small piece code to see the result?

Contributor
JONTHEPOPE
Posts: 20
Registered: ‎12-03-2009
Message 5 of 9 (151 Views)

Re: add linetypes to layers

07-17-2014 12:15 PM in reply to: norman.yuan

the line type is loaded and I ran the code

 

1 error message 

Use of unassigned loacl variable 'acLyrTblRec'

 

 

 

*Expert Elite*
norman.yuan
Posts: 1,063
Registered: ‎04-27-2009
Message 6 of 9 (144 Views)

Re: add linetypes to layers

07-17-2014 12:42 PM in reply to: JONTHEPOPE

If you look at your code carefully, you should realize that the drawing where you were trying your code does not have a layer called "M-ANNO-TEXT-NEWW". That is, int this line of code:

 

                if (acLyrTbl.Has(getnewline) == true)
                {
                    acLyrTblRec = acTrans.GetObject(acLyrTbl[getnewline], OpenMode.ForRead) as LayerTableRecord;
                }

 

the line inside the {...} is not executed, thus, acLyrTblRec is "unassigned". The code following this "if...." should have been placed inside this "if...." statement, so the exception can be avoided.

 

Contributor
JONTHEPOPE
Posts: 20
Registered: ‎12-03-2009
Message 7 of 9 (109 Views)

Re: add linetypes to layers

07-18-2014 11:21 AM in reply to: norman.yuan

here's my progress so far still doesn't work

 

 */ 

        string[] sLayerNames = new string[3];
        sLayerNames[0] = "ACIRed";
        sLayerNames[1] = "TrueBlue";
        sLayerNames[2] = "ColorBookYellow";


        Color[] acColors = new Color[3];
        acColors[0] = Color.FromColorIndex(ColorMethod.ByAci, 1);
        acColors[1] = Color.FromRgb(23, 54, 232);
        acColors[2] = Color.FromNames("PANTONE Yellow 0131 C",
                                        "PANTONE(R) pastel coated");

        int nCnt = 0;

        foreach (string sLayerName in sLayerNames)
        {
            if (acLyrTbl.Has(sLayerName) == false)
            {
                using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
                {
  
                    acLyrTblRec.Name = sLayerName;

                    if (acLyrTbl.IsWriteEnabled == false) acLyrTbl.UpgradeOpen();

                    acLyrTbl.Add(acLyrTblRec);
                    acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    LinetypeTable acLinTbl;
                    acLinTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
                                                    OpenMode.ForRead) as LinetypeTable;

                    if (acLinTbl.Has("Center") == true)
                    {
                        acLyrTblRec.UpgradeOpen();

                        acLyrTblRec.LinetypeObjectId = acLinTbl["Center"];
                    }

                    acLyrTblRec.Color = acColors[nCnt];
                }
            }
            else
            {

                LayerTableRecord acLyrTblRec = acTrans.GetObject(acLyrTbl[sLayerName],
                                                                 OpenMode.ForWrite) as LayerTableRecord;
                
                
                LinetypeTable acLinTbl;
                acLinTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
                                                OpenMode.ForRead) as LinetypeTable;



                if (acLinTbl.Has("Center") == true)
                {
                    acLyrTblRec.UpgradeOpen();

                    acLyrTblRec.LinetypeObjectId = acLinTbl["Center"];
                }


                acLyrTblRec.Color = acColors[nCnt];
            }

            nCnt = nCnt + 1;
        }


        acTrans.Commit();
    }
}

 

*Expert Elite*
norman.yuan
Posts: 1,063
Registered: ‎04-27-2009
Message 8 of 9 (100 Views)

Re: add linetypes to layers

07-18-2014 12:47 PM in reply to: JONTHEPOPE

Well, not seeing your whole code and not knowing the drawing you use to test your code, it is not easier to go through your partial code to identify what is wrong, than just write some code to show you how it works.

 

Have you step through your code in debugging, which should lead you easily to where the exception occurs and you can usually find out what is the reason.

 

Anyway, here is some simple code that set linetype of a layer ("Layer1", if not exists, create it; and its linetype is "Continuous" by default) from to "Hidden" (assume this linetype has already been loaded into the current drawing database):

 

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;

[assembly: CommandClass(typeof(SetLayerLineType.MyCadCommands))]

namespace SetLayerLineType
{
    public class MyCadCommands
    {
        [CommandMethod("SetLT")]
        public void SetLayerLineType()
        {
            Document dwg = CadApp.DocumentManager.MdiActiveDocument;
            if (dwg == null) return;
            Editor ed = dwg.Editor;

            try
            {
                SetLayerLineType(dwg, "layer1", "Hidden");
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage(
                    "\nError: {0}\n{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
            }
        }

        private void SetLayerLineType(
            Document dwg, string layerName, string lineTypeName)
        {
            using (Transaction tran =
                dwg.Database.TransactionManager.StartTransaction())
            {
                LayerTable layerTable = (LayerTable)tran.GetObject(
                    dwg.Database.LayerTableId, OpenMode.ForRead);

                LinetypeTable lineTable = (LinetypeTable)tran.GetObject(
                    dwg.Database.LinetypeTableId, OpenMode.ForRead);

                ObjectId lineTypeId = ObjectId.Null;
                if (lineTable.Has(lineTypeName))
                {
                    lineTypeId = lineTable[lineTypeName];
                }

                LayerTableRecord layer;
                if (layerTable.Has(layerName))
                {
                    layer = (LayerTableRecord)tran.GetObject(
                        layerTable[layerName], OpenMode.ForRead);

                    LinetypeTableRecord lineType=(LinetypeTableRecord)
                        tran.GetObject(lineTypeId,OpenMode.ForRead);

                    dwg.Editor.WriteMessage(
                        "\nLine type of existing layer \"{0}\" is {1}",
                        layer.Name, lineType.Name);

                    //set to desired linetype
                    if (!lineTypeId.IsNull)
                    {
                        layer.UpgradeOpen();
                        layer.LinetypeObjectId = lineTypeId;
                    }
                }
                else
                {
                    layer = new LayerTableRecord();
                    layer.Name = layerName;

                    layerTable.UpgradeOpen();
                    layerTable.Add(layer);
                    tran.AddNewlyCreatedDBObject(layer, true);

                    //Before a new layer is commited in the transaction,
                    //its LineTypeObjectId is Null, unless being assigned explicitly
                    //However, if no linetypeObjectId is assigned, the new layer would
                    //get "Continuous" line type upon transaction committing
                    dwg.Editor.WriteMessage(
                        "\nnewly created layer \"{0}\" with linetypeID->{1}", 
                        layerName, 
                        layer.LinetypeObjectId.ToString());

                    //Set to desired linetype
                    if (!lineTypeId.IsNull)
                    {
                        layer.LinetypeObjectId = lineTypeId;
                    }
                }

                //Prove linetype has been set to the layer
                if (!lineTypeId.IsNull)
                {
                    LinetypeTableRecord lt = (LinetypeTableRecord)tran.GetObject(
                        layer.LinetypeObjectId, OpenMode.ForRead);

                    dwg.Editor.WriteMessage(
                        "\nLineType has been set to {0}", lt.Name);
                }

                tran.Commit();
            }
           
        }
    }
}

 

Contributor
JONTHEPOPE
Posts: 20
Registered: ‎12-03-2009
Message 9 of 9 (94 Views)

Re: add linetypes to layers

07-18-2014 01:38 PM in reply to: norman.yuan

Thanks for your help Norman I see the error in my ways it works now!:smileyhappy:

Post to the Community

Have questions about Autodesk products? Ask the community.

New Post
Announcements
Do you have 60 seconds to spare? The Autodesk Community Team is revamping our site ranking system and we want your feedback! Please click here to launch the 5 question survey. As always your input is greatly appreciated.