.NET

.NET

Reply
Member
bjmallon
Posts: 5
Registered: ‎11-18-2009
Message 1 of 1 (889 Views)

DIMSTYLES : Creating, Modifying and Setting Current

889 Views, 0 Replies
05-09-2013 10:20 PM

OK.  This is not so much a cry for help as a post that might help someone else.

 

I was trying to find concise code that would let me create a dimension style (if it didn't exist), or modify a dimension style (if it did), that complied with our particular drafting standards.

 

I also wanted code that would enable me to set the dimstyle current.

 

Well, below is what I arrived at with the help of about 20 different blog and forum posts that gave me different components of the whole.  Google's wonderful until you're snowed with irrelevant results.

 

My code looks a bit inflexible because it's meant to be.  I don't want someone deciding that their 'standard' is better than the one they're supposed to use.  If you take this on board, I would suggest creating a class for holding all the Dimstyle settings and feeding that into the CreateModifyDimStyle method.

 

The main things I arrived at were :

-> The default DIMBLK, DIMBLK1, DIMBLK2 and DIMLDRBLK values ("." or "" when set using the DIMBLK command in Autocad) can be set using ObjectId.Null.

- > When you modify an existing dimension style and it is the current dimstyle, checking whether the modified style has the same ObjectId as the 'current' style will force an override to be created on that style.  This process was in an example I found.  See the comments in the 'SetDimStyleCurrent' code.

 

The main code blocks below are:

- CheckDimStyleExists  // Kind of redundant to my code now, but might be useful in the future

CreateModifyDimStyle

SetDimStyleCurrent

 

Some supporting methods used in those methods 

- GetLinestyleID

- CheckTextStyle

- CreateTextStyle

 

Just in case you are looking to get the Id of a linestyle other than "Continuous" (which can't be purged), there are a couple of methods that will check for its existence and load it from the nominated linetype file:

- CheckLineStyleExists

- LoadLineTypes

 

For those looking to get the ObjectId of arrow types other that the default (e.g. "_DOT", "_CLOSED", etc), the GetArrowObjectId pilferred from Kean Walmsley's blog will help out. Look up DIMBLK in the AutoCAD help for the appropriate values to pass it.

 

Anyway, I hope that this proves useful to someone and gives you something to work from.

 

Here's the code blocks.

 

BTW: I'm using 'static' to be a bit lazy and avoid creating an instance of the 'Utilities' class that contains the methods.  i.e. I simply need a reference to the containing dll (and namespace) and then I can use Utilities.<Method>.

 

The 'usings' at the top of my Utilities class are.  Some are relevant to these methods, some not.  Delete until something errors during compile.  Usually works for me  :smileytongue::

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Autodesk.AutoCAD;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.LayerManager;

        

        public static bool CheckDimStyleExists(string DimStyleName)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                DimStyleTableRecord dstr = new DimStyleTableRecord();
                DimStyleTable dst = (DimStyleTable)tr.GetObject(db.DimStyleTableId, OpenMode.ForRead, true);
                if (dst.Has(DimStyleName))
                    return true;

                return false;
            }
        }

 

        public static void CreateModifyDimStyle(string DimStyleName, out string message)
        {
            // Initialise the message value that gets returned by an exception (or not!)
            message = string.Empty;
            try
            {
                using (Transaction tr = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
                {
                    Database db = Application.DocumentManager.MdiActiveDocument.Database;
                    DimStyleTable dst = (DimStyleTable)tr.GetObject(db.DimStyleTableId, OpenMode.ForWrite, true);

                    // Initialise a DimStyleTableRecord
                    DimStyleTableRecord dstr = null;
                    // If the required dimension style exists
                    if(dst.Has(DimStyleName))
                    {
                        // get the dimension style table record open for writing
                        dstr = (DimStyleTableRecord)tr.GetObject(dst[DimStyleName], OpenMode.ForWrite);
                    }
                    else
                        // Initialise as a new dimension style table record
                        dstr = new DimStyleTableRecord();

                    // Set all the available dimension style properties
                    // Most/all of these match the variables in AutoCAD.
                    dstr.Name = DimStyleName;
                    dstr.Annotative = AnnotativeStates.True;
                    dstr.Dimadec = 2;
                    dstr.Dimalt = false;
                    dstr.Dimaltd = 2;
                    dstr.Dimaltf = 25.4;
                    dstr.Dimaltrnd = 0;
                    dstr.Dimalttd = 2;
                    dstr.Dimalttz = 0;
                    dstr.Dimaltu = 2;
                    dstr.Dimaltz = 0;
                    dstr.Dimapost = "";
                    dstr.Dimarcsym = 0;
                    dstr.Dimasz = 3.5;
                    dstr.Dimatfit = 3;
                    dstr.Dimaunit = 0;
                    dstr.Dimazin = 2;
                    dstr.Dimblk = ObjectId.Null;
                    dstr.Dimblk1 = ObjectId.Null;
                    dstr.Dimblk2 = ObjectId.Null;
                    dstr.Dimcen = 0.09;
                    dstr.Dimclrd = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 7);
                    dstr.Dimclre = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 7); ;
                    dstr.Dimclrt = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 2); ;
                    dstr.Dimdec = 2;
                    dstr.Dimdle = 0;
                    dstr.Dimdli = 7;
                    dstr.Dimdsep = Convert.ToChar(".");
                    dstr.Dimexe = 1;
                    dstr.Dimexo = 2;
                    dstr.Dimfrac = 0;
                    dstr.Dimfxlen = 0.18;
                    dstr.DimfxlenOn = false;
                    dstr.Dimgap = 1;
                    dstr.Dimjogang = 0;
                    dstr.Dimjust = 0;
                    dstr.Dimldrblk = ObjectId.Null;
                    dstr.Dimlfac = 1;
                    dstr.Dimlim = false;
                    
                    ObjectId ltId = GetLinestyleID("Continuous");
                    dstr.Dimltex1 = ltId;
                    dstr.Dimltex2 = ltId;
                    dstr.Dimltype = ltId;
                    
                    dstr.Dimlunit = 2;
                    dstr.Dimlwd = LineWeight.LineWeight025;
                    dstr.Dimlwe = LineWeight.LineWeight025;
                    dstr.Dimpost = "";
                    dstr.Dimrnd = 0;
                    dstr.Dimsah = false;
                    dstr.Dimscale = 1;
                    dstr.Dimsd1 = false;
                    dstr.Dimsd2 = false;
                    dstr.Dimse1 = false;
                    dstr.Dimse2 = false;
                    dstr.Dimsoxd = false;
                    dstr.Dimtad = 2;
                    dstr.Dimtdec = 2;
                    dstr.Dimtfac = 1;
                    dstr.Dimtfill = 0;
                    dstr.Dimtfillclr = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 0);
                    dstr.Dimtih = false;
                    dstr.Dimtix = false;
                    dstr.Dimtm = 0;
                    dstr.Dimtmove = 0;
                    dstr.Dimtofl = false;
                    dstr.Dimtoh = false;
                    dstr.Dimtol = false;
                    dstr.Dimtolj = 1;
                    dstr.Dimtp = 0;
                    dstr.Dimtsz = 0;
                    dstr.Dimtvp = 0;

                    // Test for the text style to be used
                    ObjectId tsId = ObjectId.Null;
                    // If it doesn't exist
                    if(!CheckTextStyle("MR_ROMANS"))
                    {
                        // Create the required text style
                        CreateTextStyle("MR_ROMANS", "romans.shx", 0);
                        tsId = GetTextStyleId("MR_ROMANS");
                    }
                    else
                        // Get the ObjectId of the text style
                        tsId = GetTextStyleId("MR_ROMANS");

                    dstr.Dimtxsty = tsId;
                    dstr.Dimtxt = 3.5;
                    dstr.Dimtxtdirection = false;
                    dstr.Dimtzin = 0;
                    dstr.Dimupt = false;
                    dstr.Dimzin = 0;

                    // If the dimension style doesn't exist
                    if (!dst.Has(DimStyleName))
                    {
                        // Add it to the dimension style table and collect its Id
                        Object dsId = dst.Add(dstr);
                        // Add the new dimension style table record to the document
                        tr.AddNewlyCreatedDBObject(dstr, true);
                    }

                    // Commit the changes.
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                message = e.Message.ToString();
            }
        }

 

        public static void SetDimStyleCurrent(string DimStyleName)
        {
            // Establish connections to the document and its database
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            // Establish a transaction
            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                DimStyleTable dst = (DimStyleTable)tr.GetObject(db.DimStyleTableId, OpenMode.ForRead);
                ObjectId dimId = ObjectId.Null;

                string message = string.Empty;
                if (!dst.Has(DimStyleName))
                {
                    CreateModifyDimStyle(DimStyleName, out message);
                    dimId = dst[DimStyleName];
                }
                else
                    dimId = dst[DimStyleName];

                DimStyleTableRecord dstr = (DimStyleTableRecord)tr.GetObject(dimId, OpenMode.ForRead);
                
                /* NOTE:
                 * If this code is used, and the updated style is current,
                 * an override is created for that style.
                 * This is not what I wanted.
                 */ 
                    //if (dstr.ObjectId != db.Dimstyle)
                    //{
                    //    db.Dimstyle = dstr.ObjectId;
                    //    db.SetDimstyleData(dstr);
                    //}

                /* Simply by running these two lines all the time, any overrides to updated dimstyles get 
                 * cleared away as happens when you select the parent dimstyle in AutoCAD.
                 */
                db.Dimstyle = dstr.ObjectId;
                db.SetDimstyleData(dstr);                

                tr.Commit();
            }
        }

 

        public static ObjectId GetLinestyleID(string LineStyleName)
        {
            ObjectId result = ObjectId.Null;

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                LinetypeTable ltt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead);
                result = ltt[LineStyleName];
                tr.Commit();
            }

            return result;
        }

 

        public static bool CheckTextStyle(string TextStyleName)
        {
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acDb = acDoc.Database;

            // Ensure that the MR_ROMANS text style exists
            using (Transaction AcTrans = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
            {
                TextStyleTableRecord tstr = new TextStyleTableRecord();
                TextStyleTable tst = (TextStyleTable)AcTrans.GetObject(acDb.TextStyleTableId, OpenMode.ForRead, true, true);

                if(tst.Has(TextStyleName) == true)
                //if (tst.Has(tst[TextStyleName]) == true)
                    return true;
                return false;
                }
        }

 

        public static void CreateTextStyle(string TextStyleName, string FontName, double ObliqueAng, out string message)
        {
            try
            {
                using (Transaction transaction = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
                {
                    Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
                    TextStyleTable tst1 = (TextStyleTable)transaction.GetObject(db.TextStyleTableId, OpenMode.ForWrite, true, true);
                    TextStyleTableRecord tstr1 = new TextStyleTableRecord();
                    tstr1.Name = TextStyleName;
                    tstr1.FileName = FontName;
                    tstr1.XScale = 0.8;
                    tstr1.ObliquingAngle = Deg2Rad(ObliqueAng);
                    tstr1.Annotative = AnnotativeStates.True;
                    tst1.Add(tstr1);
                    transaction.TransactionManager.AddNewlyCreatedDBObject(tstr1, true);
                    transaction.Commit();
                    //RmTSid = tstr1.ObjectId;
                    //return true;
                    message = string.Empty;
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                message = e.Message.ToString();
            }
        }

 

        public static bool CheckLinestyleExists(string LineStyleName)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                //LinetypeTableRecord lttr = new LinetypeTableRecord();
                LinetypeTable ltt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead, true);
                if (ltt.Has(LineStyleName))
                    return true;

                return false;
            }
        }

 

        public static void LoadLinetypes(string LinFile, string LinType)
        {
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Linetype table for read
                LinetypeTable acLineTypTbl;
                acLineTypTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
                    OpenMode.ForRead) as LinetypeTable;

                if (acLineTypTbl.Has(LinType) == false)
                {
                    // Load the requested Linetype
                    acCurDb.LoadLineTypeFile(LinType, LinFile);
                }

                // Save the changes and dispose of the transaction
                acTrans.Commit();
            }
        }

 

        static ObjectId GetArrowObjectId(string newArrowName)
        {
            ObjectId result = ObjectId.Null;

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            string oldArrowName = Application.GetSystemVariable("DIMBLK").ToString();
            Application.SetSystemVariable("DIMBLK", newArrowName);
            if (oldArrowName.Length != 0)
                Application.SetSystemVariable("DIMBLK", oldArrowName);

            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                result = bt[newArrowName];
                tr.Commit();
            }

            return result;
        }

 

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.