Quantcast
Channel: Autodesk India Community aggregator
Viewing all 1680 articles
Browse latest View live

AutoCAD Customization: .NET: Linetypes : Reload all from .lin file including existing

$
0
0

Another contribution for those looking for help.

 

This one collects together the pieces from a few examples I came across that eventually helped me do what I wanted to do.

 

This code will load all the linetypes from a .lin file.  If the linetype exists, it will force a reload to ensure that the linetype is correctly defined.  This has been important for me as we have been noticing linetypes getting 'corrupted' occassionally with a disconnect between the linetype definition and the shapes being used in the linetype.  A reload has usually fixed it.

 

The 'CheckLinestyleExists' and 'GetLinestyleId' are included in case someone finds them useful.  I've got them as separate methods in case I just need that bit for another purpose.

 

They're all 'static' so that I can be a bit lazy calling them, without having to create an instance of the 'Utilities' class I've got the methods in.  It's working for me, I'm happy. :smileyhappy:

 

Here goes.  I hope someone finds it useful.

 

        /// <summary>
        /// Load all the linetypes contained in the passed in linetype file.
        /// If the linetype exists, a reload will be forced.
        /// </summary>
        /// <param name="LineTypeFile">Fully formed path to .lin file.  This is required for the StreamReader.</param>
        public static void LoadAllLinetypesFromFile(string LineTypeFile)
        {
            // In this case, my CommandFlags are set to 'Session'.
            // Therefore the document needs to be locked.
            DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument();

            using (docLock)
            {
                // Open, read the contents, and let go of the file.
                /* Most linetype files are not large enough to 
                 * generate any processing overheads with this method.
                 */
                StreamReader sr = new StreamReader(LineTypeFile);
                string fileContent = sr.ReadToEnd();
                sr.Close();

                // Split the contents of the file on new line/carriage return and jettison empty lines
                List<string> nameList = fileContent.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                // Trim the list down to linetype name lines only
                for (int i = nameList.Count - 1; i >= 0; i--)
                {
                    if (nameList[i].StartsWith(";")) // If the line starts with ';' it's a comment
                        nameList.RemoveAt(i);
                    else if (nameList[i].StartsWith("A")) // If the line starts with 'A' it's the definition itself.
                        nameList.RemoveAt(i);
                }

                // Process each name in the resulting list
                foreach (string name in nameList)
                {
                    // Regex out the name from the string.  We're not interested in the comment.
                    /* The 'name' line has the following format
                     * - *<Name>,<Description/comment>
                     * We're looking for anything between the '*' and the ','
                     * The Regex pattern is saying
                     * - '^' : from the start of the string
                     * - '\*' : starting with and '*', which needs to be escaped for Regex
                     * - '(?<Name>.*)' : Open a group called 'Name' accepting any character any number of times
                     * - ',' : The pattern is closed when a comma is encountered
                     */
                    string ltName = Regex.Match(name, @"^\*(?<Name>.*),").Groups["Name"].Value;
                    
                    LoadLinetype(LineTypeFile, ltName);
                }
            }
        }

        public static void LoadLinetype(string LineStyleFile, string LineStyle)
        {
            // Connect to the document
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

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

                if (!acLineTypTbl.Has(LineStyle)) // If the linetype doesn't exist.
                    /* A Kean Walmsley example tries to load all linetypes by feeding "*" in as the linetype.
                     * That fails if the linetype exists.  
                     * Although he captures the exceptions, the remaining linetypes don't get loaded.
                     */
                    db.LoadLineTypeFile(LineStyle, LineStyleFile); // Load the requested Linetype.
                else
                    ForceLinetypeReload(LineStyleFile, LineStyle); // Force an update from the file.

                // Commit the changes
                acTrans.Commit();
            }
        }

        public static void ForceLinetypeReload(string LineStyleFile, string LineStyle)
        {
            /* I would like to acknowledge 'Hallex' on the Autodesk discussion forum for parts of this code.
             * I stripped out the bits that did what I needed them to do.
             * 
             * It was also the only post I've ever come across that actually demonstrated
             * how to use InvokeMember for the command sending.  Every other one just said
             * to 'use InvokeMember' without providing any context or requirements.
             * 
             * I salute you Hallex.  Many thanks.
             */
            // Get the current FILEDIA setting for restoration later
            Int16 fileDia = (Int16)Application.GetSystemVariable("FILEDIA");
            // Set FILEDIA to 0, to force a 'command line' interaction with the linetype command
            Application.SetSystemVariable("FILEDIA", 0);
            // Get an instance of the application object
            Object acObj = Application.AcadApplication;
            // Get an instance of the document objecy associated with the application
            object acDoc = acObj.GetType().InvokeMember("ActiveDocument", System.Reflection.BindingFlags.GetProperty, null, acObj, null);
            // Establish an array for the command
            object[] dataArray = new object[1];
            // Build the command string and add to the array
            dataArray[0] = "-linetype Load " + LineStyle + "\n" + LineStyleFile + "\nYes\n ";
            // Send the command to AutoCAD.
            acDoc.GetType().InvokeMember("SendCommand", System.Reflection.BindingFlags.InvokeMethod, null, acDoc, dataArray);
            // Reset the FILEDIA variable.
            Application.SetSystemVariable("FILEDIA", fileDia);
        }

        public static bool CheckLinestyleExists(string LineStyleName)
        {
            // Connect to the document and its database
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            // Transact with the database
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // Get an instance of the line type table
                LinetypeTable ltt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead, true);
                // Test if the linetype exists
                if (ltt.Has(LineStyleName))
                    return true; // If it does return true

                return false; // If it doesn't return false
            }
        }

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

            // Connect to the document and its database
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            // Transact with the database
            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                LinetypeTable ltt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead); // Get an instance of the line type table
                if(ltt.Has(LineStyleName)) // IF the linestyle exists
                    result = ltt[LineStyleName]; // Get the linetype object id
                tr.Commit(); // Finish the transaction
            }

            return result;
        }

 


AutoCAD Customization: .NET: How to collect all dimension line Arrow heads?

$
0
0

Hi this is my issue i have to collect all the Dimension arrowheads(usually close filled type) present in the modelspace ,and change the type to DOT..I have no idea about this .Im using COM APi..Thanks

AutoCAD Customization: .NET: Assembly Load problem

$
0
0

Hi all,

 

I am writing an EXE .net application and I need to, somehow, use NETLOAD and load a dll file. As far as I understood from here, following line would be the key for me.

 

Assembly.LoadFrom( <...full path to my DLL file...> )

I run the code and I get no error - AutoCAD has been set to be Visible since I am still debuging my code.

Meanwhile the subroutine's meta data is not recognised at all - as if the DLL file has not been loaded in AutoCAD.

 

Any idea what that might be for?

 

 

Thanks

AutoCAD Customization: .NET: .NET C# Ribbon tab

$
0
0

Hello, I am new in the autodesk customization, I have autocad 2013 and visual studio 2010

 

I am interested in make a custom ribbon tab, where I can put a button.

 

I have found some (incomplete) samples to implement a custom ribbon tab, but I dont know how to "insert" my tab into autocad 2013, and how must I load my tab? with a command?  or it can load automatically?

 

Can someone show me an example?

 

Thank you very much.

 

AutoCAD Customization: Visual LISP, AutoLISP and General Customization: DXF Codes

$
0
0

I am creating a lisp routine to take a detail file and standardize it for insertion into multiple plan sets. One of the things i'm not sure of is if you can change the contents of a DXF code number or not. If so, how would I go about changing that data across a selection set? Sorry if this sounds LISP-noobish.

AutoCAD Customization: .NET: DIMSCALE problem

$
0
0

Hi, I am having problems with dimension after changing the dimscale.  The user wants to change the dimscale.  The program prompts for the selection of a dimension entity and also for the new dimscale.  The dimscale property of the dimension entity is set to the new dimscale.  The problem is that the entity is not updated on the screen, even after calling the entity draw method.  In VBA there was an Update method, but I can find anything like that in the .NET dimension entity.  Can someone help me with this situation? I will really appreciate your help.

AutoCAD Customization: Visual LISP, AutoLISP and General Customization: Align Block problem

$
0
0

Hello,

 

I am trying to write a program to align a block with two selected destination points. 
- first the user is prompted to select a lwpolyline of a block entity
- then he is prompted to pick two destination points

I face problem with the sub-routine SegmentPts. It is supposed to return the coordinates of two vertexes on both sides of the picked point on a lwpolyline using entsel. But here in my program, when i am picking a point using entsel on a lwpolyline inside a block entity, it is not returning the two vertexes on both sides of the picked point. In stead, it returns some other points of the selected LWPOLYLINE. Why it is doing so? Where is the problem in my program?

It works fine with my other programs where i pick on a LWPOLYLINE entity.
In this particular case, the LWPOLYLINE is inside a Block entity and the program is not returning correct points.

Any help in thisregard will be highly appreciated.

 

Thanks

 

Please check my my Lisp Program below:

 

(defun C:alb()
(setq ent1 (entsel "\nPick on one side of LWLINE ofa Block:" ))
(setq ent (nentselp (cadr ent1)))
(setq ins_pt (cdr (assoc 10 (entget (car ent1)))))
(setq pt_d1 (getpoint "\nSpecify first destination point:"))
(setq pt_d2 (getpoint "\nSpecify Second destination point:" pt_d1))
(setq pt_l (SegmentPts ent))
(setq pt_a (car pt_l) pt_b (cadr pt_l))
(command "align" (car ent1) "" (setq a (translate pt_a ins_pt)) pt_d1 (setq b (translate pt_b ins_pt)) pt_d2 "" "N")
)

;;;;;;;;;;;;;;;;;;;;;;;
(defun translate (pt pin /)
(mapcar '+ pt pin)
)

 ;;;;;;;;;;;;;;;;;;;;;;;


(defun SegmentPts (ent / e pnt vobj Name param1 param2 p1 p2 SegPts)
(vl-load-com)
(and
(setq e (car ent))
(= (type e) 'ENAME)
(setq pnt (cadr ent))
(listp pnt)
(not (atom (cdr pnt)))
(vl-every (function (lambda (x) (= (type x) 'REAL))) pnt)
(setq vobj (vlax-ename->vla-object (car ent)))
(setq pnt (trans (cadr ent) 1 0))
(setq pnt (vlax-curve-getClosestPointTo vobj pnt))
(setq Name (vla-get-ObjectName vobj))
(cond
((vl-position Name '("AcDbArc" "AcDbLine"))
(setq p1 (vlax-curve-getStartPoint vobj))
(setq p2 (vlax-curve-getEndPoint vobj))
)
((wcmatch (strcase Name) "*POLYLINE")
(setq param1 (vlax-curve-getParamAtPoint vobj pnt))
(setq param1 (fix param1))
(setq param2 (1+ param1))
(if (equal param1 (vlax-curve-getStartParam vobj) 1e-10)
(setq p1 (vlax-curve-getStartPoint vobj))
(setq p1 (vlax-curve-getPointAtParam vobj param1))
)
(if (equal param2 (vlax-curve-getEndParam vobj) 1e-10)
(setq p2 (vlax-curve-getEndPoint vobj))
(setq p2 (vlax-curve-getPointAtParam vobj param2))
)
) ;pline cond
(T
(prompt (strcat "\nHaven't figured out a(n) " Name " yet."))
)
) ;conditions
p1
p2
(setq SegPts (list p1 p2))
) ;and
SegPts
) ;end



 

AutoCAD Customization: .NET: Turn on/off Viewport Error

$
0
0

Hi All,

 

Please let me know this error:

 

1.png

 

When I try the code:

 

Public Sub HVP()
        Dim doc As Document = Application.DocumentManager.MdiActiveDocument
        Dim ed As Editor = doc.Editor
        Dim db As Database = HostApplicationServices.WorkingDatabase
        Using DocLock As DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument()
            Using tr As Transaction = db.TransactionManager.StartTransaction()
                Try
                    Dim layoutdict As DBDictionary = TryCast(tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead, False, True), DBDictionary)
                    For Each entry As DBDictionaryEntry In layoutdict
                        If entry.Key <> "Model" Then
                            Dim lay As Layout = TryCast(tr.GetObject(entry.Value, OpenMode.ForRead, False, True), Layout)
                            For Each vpid As ObjectId In lay.GetViewports()
                                Dim vp As Autodesk.AutoCAD.DatabaseServices.Viewport = TryCast(tr.GetObject(vpid, OpenMode.ForWrite, True, True), Autodesk.AutoCAD.DatabaseServices.Viewport)

                                    vp.On = False

                            Next
                        End If
                    Next
                Catch ex As Exception
                    MsgBox(ex.Message & ex.StackTrace & ex.ErrorStatus)
                End Try
                tr.Commit()
            End Using
        End Using

 

Thanks for any help.


AutoCAD Customization: Visual LISP, AutoLISP and General Customization: Lisp Request

$
0
0
Dear Friends, I have several donuts and blocks with id points. (SEE THE ATTACHED DRG) I need to change all donuts size together and ID point should be the same. similarly the text also to be changed globally with same ID. can anyone send me a lisp for this operation. thanks a lot ( see the attached Drg for your reference) ALSO nee to insert new DONUT or similar blocks at purticulat coordinates. thanks & appreciate

AutoCAD Customization: .NET: Public and use the big structure body

$
0
0
Thank you.
IdeclarePublicanduse the bigstructurebody.
AutoCADis terminated abnormallywithone of two timesofprobabilitywhenIexecute the command.
SowhenNETLOADdoesDLLwhichbuilt the sourcewhichdeclaredPublicvariableinVB.NET,
 Developmenttomemory
 Clearof the memory
Isitperformedin whichtiming?
In addition,mustInotuse the Publicdeclaration?
Iwantyoutotellme.
Thanking you in advance.

AutoCAD Customization: .NET: Autocad 2012 and 2013

$
0
0

Hi All,

 

Autocad 2012 and 2013 both run under NET FRAMEWORK 4.0. So, is there a way to build *.dll file for them?

 

Thanks,

AutoCAD Customization: .NET: How to find the section view names from the drawing

$
0
0

Hi all, I need to change the section view name height..I can able to collect all the text and also able to change the height.

But only for the view names i need to change the height.Im using COM API...here is my code.Thanks in advance

 

//why i used 3 here is ,because section view name strings  will be like" A-A"

//im also try to assign color for the view name
                   if (acadText.EntityName.Length.Equals(3))
                   {
                      
                       acadText.Height = 6.0;
                       AcadAcCmColor sectionViewTextColor = acadText.TrueColor;
                       sectionViewTextColor.ColorIndex = AcColor.acMagenta;
                       acadText.TrueColor = sectionViewTextColor;
                       acadText.update();

                   }

I dont know how to use split command,what are the arguments to pass for that
 

AutoCAD Customization: Autodesk ObjectARX: Contextual tab selector rules - available triggers?

$
0
0

HI,

 

I'm looking for a list of all available triggers for Contextual Tab Selector rules (describing here). In the file AcContextualTabSelectorRules.xaml I noticed that only two triggers are used:

  • Selection
  • SystemVariable

Is there trigger for command? In this case, what is the right syntax to use?

 

Regards,

Jonathan

 

AutoCAD Customization: Visual LISP, AutoLISP and General Customization: Missing "Ribbon Combo Box - Workspace"

$
0
0

I am unable to find the "Ribbon Combo Box - Workspace" to our 2013 MEP or ACA CUI. It is visible in vanilla AutoCAD 2013, but it isn't listed in the Command List (under Ribbon Control Elements). I am unable to transfer it from AutoCAD's cuix either. We typically have this control in our Quick Access Toolbar, but I am unable to create this same environment in the 2013 verticals.

 

I am unable to see it even using one of the default profiles, like "AutoCAD Architecture (US Imperial)".

 

Any assistance would be appreciated.

 

AutoCAD Customization: .NET: How do I get if I run autocad vanilla or autocad civil3D

$
0
0

I created 2 dll's

One for autocad  the other one for civil

I created another dll that loads using

Reflection.Assembly.LoadFrom("file")

the dlls into autocad at startup

I want to be able to detect if the productID is civil to be able to load the civil3d dll.

Can somebody tell me how to detect this?

Thanks


AutoCAD Customization: .NET: Hatch pattern listed

$
0
0

Hi,

 

I have a bit of code that I use to create hatches (many thanks to those who helped me), but the names are just coded inside (like "BRICK" or "CLAY"); I would like to list all available patterns for the curent drawing(on a form, using a combobox, etc), which is the best way to go?

 

Thank you very much,

 

e.g.

AutoCAD Customization: Visual LISP, AutoLISP and General Customization: Cannot load custom Acad2014.lsp & Acad2014doc.lsp from custom directory

$
0
0

I upgraded from Acad Electrical 2011 to 2014. I added a custom directory to the “Support File Search Path” and the “Trusted Locations”. The custom directory has a customized Acad2014.lsp & Acad2014doc.lsp, but my programs are not available. I have done this since Acad Release  2.1. I’m running on Win 7 64bit station.

 

Thanks,

Dave

AutoCAD Customization: Visual LISP, AutoLISP and General Customization: AE12 Component User Post Lisp Modification

$
0
0

What I'm looking to do has essentially already been written in the wirefrm2.lsp user post routine by filtering INST attributes which only displays the desired outputs on the report.

 

What I would like to do is use the same concept of this sorting routine on sort FAMILY attributes in the COMPONENT schematic report. Below are screen shots to walk through the steps of how far I've gotten. I will also post my code along with the issues I've confronted.

 

 

Step 1: This is what I'm trying to accomplish with the component report.

Comp1.png 

 

Step 2: Sorting on these attributes, click user post.

Comp2.png

 

Step 3: Modified the comp.dcl file to add menu selection 

Comp3.png

 

Step 4:  The routine finds the family codes in the report displayed on this selection window. 

Comp4.png

 

Step 5: Once it returns to the report it appears as though the attributes aren't released from the array?  Stuck here!

Comp5.png

 

Here is the code I have been working on.  I think the issue is somewhere in the very last loop.  Does anyone have any imput on this sort of modification to a lisp routine?  Thank you and I appreciate any input!

 

; ---------  C O M P . L S P  -----------------------------
; Post-process schematic component report. 
;
; This routine is called from AutoCAD Electrical's "User post" button on the
; schem component report dialog display. Report data is passed to this
; routine in AutoLISP variable called "wd_rdata". This utility can
; then operate on this report data, reformat it into a new list of
; report data "rtrn" and then pass it back to AutoCAD Electrical's report dialog 
; through a call to (c:wd_rtrn_2wd rtrn) shown at the end of this file.
;

; Each item in the first list (the "(car wd_rdata)" part of the data) is itself a 
  ; sublist with the following elements:
  ; nth 0=ITEM
  ; nth 1=TAGNAME
  ; nth 2=CNT
  ; nth 3=UNITS 
  ; nth 4=SUBQTY (*n)
  ; nth 5=MFG
  ; nth 6=CAT
  ; nth 7=DESC1
  ; nth 8=DESC2
  ; nth 9=DESC3
  ; nth 10=REF
  ; nth 11=INST
  ; nth 12=LOC
  ; nth 13=RATING1
  ; nth 14=RATING2
  ; nth 15=RATING3
  ; nth 16=RATING4
  ; nth 17=RATING5
  ; nth 18=RATING6
  ; nth 19=RATING7
  ; nth 20=RATING8
  ; nth 21=RATING9
  ; nth 22=RATING10
  ; nth 23=RATING11
  ; nth 24=RATING12
  ; nth 25=catalog DESC
  ; nth 26=catalog QUERY2 field
  ; nth 27=catalog QUERY3 field
  ; nth 28=catalog MISC1 field
  ; nth 29=catalog MISC2 field
  ; nth 30=catalog USER1 field
  ; nth 31=catalog USER2 field
  ; nth 32=catalog USER3 field
  ; nth 33=1=Parent, 2=child
  ; nth 34=WDBLKNAM
  ; nth 35=BLKNAM
  ; nth 36=HDL
  ; nth 37=CATEGORY
  ; nth 38=ASSYCODE
  ; nth 39=SHEET (%S)
  ; nth 40=SHDWGNAM (%D)
  ; nth 41=SEC
  ; nth 42=SUBSEC
  ; nth 43=FAMILY
  ; nth 44=WDTAGALT
  ; nth 45=WDTYPE
  ; nth 46=

; -- main program execution begins here --
(defun _wd_post_main ( / rtrn dclnam dcl_id user_1 user_2 user_3 cancel xx wlay1
                         lay_map_lst data wd_make_dcl wd_nth_subst rtrn_part2
                         desc newval newdatalst newlst n ix slen str val
                         str2 x word wordlst param_lst fam fam_lst fam1 picked
			 picked_fam_lst lst op_lst)
                         
  ; -- internal subroutines

  (defun wd_nth_subst ( n val lst / newlst ix slen x )
    ; Substitute the nth member of a list "lst" with new value "val"
    ; If "n" is past end of existing list then blank positions "nil" padded
    (if (not lst)
      (setq slen 0)
      (setq slen (length lst))
    )
    (cond
      ((minusp n)  ) ; rtrn orig list if pos is neg number
      ((zerop n) (setq lst (cons val (cdr lst)))) ; n=0, replace 1st item
      ((= n slen) (setq lst (append lst (list val)))) ; new last item
      ((< n slen) ; Insert item somewhere else in list
        (setq ix 0)
        (setq newlst '())
        (foreach x lst
          (if (/= ix n)
            (setq newlst (cons x newlst)) ; reuse existing
            (setq newlst (cons val newlst)) ; substitute new
          )
          (setq ix (1+ ix))
        )
        (setq lst (reverse newlst))
        (setq newlst nil)
      )
      ((> n slen) ; lengthen list, add "nil" pads as req'd
        (setq lst (reverse lst))
        (while (< slen n)
          (setq lst (cons nil lst))  ; add pads
          (setq slen (1+ slen))
        )
        (setq lst (reverse (cons val lst))) ; tack new item on end
    ) )
   lst ; <-- this is needed 
  )     
  ; --
  (defun flip_upper_and_lower_case ( str / wordlst str2 word)
    ; Process character string "str" and flip to upper/lower case. First char
    ; of each word to upper case, rest lower case.
    (setq str2 "")
    ; break passed "str" character string into a list of words
    (setq wordlst (c:wd_delim_str_to_lst str " ")) 
    (foreach word wordlst
      ; process each word
      (if (/= str2 "")(setq str2 (strcat str2 " ")))
      ; Flip first or only character in next word to upper case
      (setq str2 (strcat str2 (strcase (substr word 1 1))))
      ; Flip 2nd+ characters of this word to lower case
      (if (> (strlen word) 1) ; word more than a single character
        (setq str2 (strcat str2 (strcase (substr word 2) T))) ; flip to lower case
      )
    )
    str2 ; return the revised character string
  )  
                      
  ; -- main routine --

  (setq rtrn nil)
  ; AutoCAD Electrical passes the report displayed data as a list of lists of lists in variable
  ; called wd_rdata. The first element of this list is the list of lists of
  ; report data. The 2nd element is used to track which lines are main and which
  ; are "subassembly" lines related to the main entry above. See detailed description below.
  (if (AND wd_rdata (car wd_rdata) (listp (car wd_rdata)))
     

    (progn ; Data comes across as two parallel lists. The first                  
           ; list (car wd_data) carries a sublist of data for each line of the 
           ; report. The parallel list (cadr wd_data) carries a flag for each
           ; line in the first list. A '1' means that the line in the first list
           ; represents the first or only line of data for a given component.
           ; A '2" means that this line of data is a "subassy" line of data and
           ; goes with the previous '1" entry. For example, a component that has
           ; one main line and three subassy lines of data would have parallel
           ; flags in the 2nd list of ...1 2 2 2.... If you insert extra lines
           ; into the first list or remove lines from the first list, you need
           ; to add or remove corresponding entries from the 2nd list to keep
           ; the two lists synchronized. 
      (setq rtrn (car wd_rdata)) ; this is the 1st list, the data sublist list
      (setq rtrn_part2 (cadr wd_rdata)) ; this is the "flag" list of 1's and 2's
  )                                                                               
 )     
  
  ; Look for dcl file of same name, open if found.
  (setq cancel nil)
  ; see if running as pre-process or auto report. won't work for those below that require selection from dialog
  (if GBL_wd_postprocess
    (progn
      (if (listp GBL_wd_postprocess)
        (progn
          (if (> (length GBL_wd_postprocess) 1)
            (setq param_lst (cadr GBL_wd_postprocess)) ; optional 
            (setq param_lst nil)
          )
          (setq GBL_wd_postprocess (car GBL_wd_postprocess)) ; should be which one to run  
      ) )    
      (if (= (type GBL_wd_postprocess) 'INT) (setq GBL_wd_postprocess (itoa GBL_wd_postprocess)))
      (cond
        ((= GBL_wd_postprocess "1") (setq user_1 "1")) 
        ((= GBL_wd_postprocess "2") (setq user_2 "1")) 
        ((= GBL_wd_postprocess "3") (setq user_3 "1"))
        (T (setq cancel 1)) ; not a valid value
      )
  ) )      
  ; Look for dcl file of same name, open if found.
  (if (AND (not GBL_wd_postprocess) ; otherwise bypass dialog
      (setq dclnam (c:ace_find_file "comp.dcl" 16))) ; 16=display error dialog if file not found
    (progn
      (setq dcl_id (load_dialog dclnam))                
      (if (new_dialog "main_select" dcl_id)
        (progn
          (setq user_1 "0") ; default to 1st user entry toggled on
	  (setq user_2 "0")
          (setq user_3 "0")      
          (set_tile "user1" user_1) ; preset toggle ON
	  (set_tile "user2" user_2)
	  (set_tile "user3" user_3)
          (action_tile "user1" "(setq user_1 $value)")
          (action_tile "user2" "(setq user_2 $value)")
          (action_tile "user3" "(setq user_3 $value)")
          (action_tile "cancel" "(setq cancel 1)")
          (start_dialog)
          (unload_dialog dcl_id)
  ) ) ) )

  (if (AND rtrn (not cancel)) 
    (progn ; user didn't cancel out of dialog, okay to continue  
      (if (= user_1 "1")
        (progn ; Example function - flip DESC1-3 text to upper/lower case strings
          (setq newdatalst nil) ; <-- last change made     
	  (foreach lst rtrn 
            ; process each "lst" report row consisting of a list of 50+ data fields
	    (setq desc (nth 7 lst)) ; get DESC1 value for this row
               (if (AND desc (/= desc ""))
                  (progn
                    (setq newval (flip_upper_and_lower_case desc))
                     ; substitute new DESC1 value into "lst" row data                    
		     (setq lst (wd_nth_subst 7 newval lst))
                  )
	       )
	    (setq desc (nth 8 lst)) ; get DESC2 value for this row
               (if (AND desc (/= desc ""))
                  (progn
                     (setq newval (flip_upper_and_lower_case desc))                    
                     ; substitute new DESC2 value into "lst" row data                    
                     (setq lst (wd_nth_subst 8 newval lst))
                  )
	       )
	    (setq desc (nth 9 lst)) ; get DESC3 value for this row
               (if (AND desc (/= desc ""))
                  (progn
                     (setq newval (flip_upper_and_lower_case desc))                    
                     ; substitute new DESC3 value into "lst" row data                   
		     (setq lst (wd_nth_subst 9 newval lst))
                  )
	       )
	    (setq newdatalst (cons lst newdatalst)) ; build up new list of report data
           )
	  (setq rtrn (reverse newdatalst)) ; put back in original order
        )
      )	

      (if (= user_2 "1")
        (progn
          ; Go through data and create a list of FAMILY values
          (setq fam_lst nil)
          (foreach lst rtrn
            (setq fam1 (nth 43 lst))
            (if (= fam1 "")(setq fam1 "(??)"))
            (if (not (member fam1 fam_lst))
              ; This fam1 not in list, add it now
              (setq fam_lst (cons fam1 fam_lst)))
          )
          (if (AND fam_lst (> (length fam_lst) 1) (OR dclnam (setq dclnam (c:ace_find_file "comp.dcl" 16))))
            (progn ; two or more family values, display in a multi-select pick list dialog
              (setq dcl_id (load_dialog dclnam))                
              (if (not (new_dialog "fam_select" dcl_id))
                ; Could not find definition for this family list dialog
                (alert (strcat (c:wd_msg "GEN075" (list "fam_select") "%1 not found") "\n(" dclnam ")"))
              ; ELSE
                (progn ; display family list in pick-list dialog
                  (setq cancel nil)
                  ; Sort the list alphabetically
                  (setq fam_lst (acad_strlsort fam_lst))
                  ; Now display in pick list dialog
                  (start_list "famlst")
                  (mapcar 'add_list fam_lst)
                  (end_list)
                  ; Define action for pick list dialog
                  (action_tile "famlst" "(setq picked $value)")
                  ; Define action for "Cancel" button
                  (action_tile "cancel" "(setq cancel 1)")
                  (start_dialog)
                  (unload_dialog dcl_id)
                  ; Return from dialog as it is dismissed
                  (if (AND (not cancel) picked)
                    (progn ; user picked one or more family codes. Index numbers returned
                           ; in string "picked", space delimited. Break this down and
                           ; assemble a list of the picked family values.
                      (setq lst (c:wd_delim_str_to_lst picked " "))
                      (setq picked_fam_lst nil)
                      (foreach lst lst
                        (setq fam (nth (atoi lst) fam_lst)) ; retrieve actual family text value
                        (if (= fam "(??)") (setq fam "")) ; flip the blank flag to actual blank
                        (setq picked_fam_lst (cons fam picked_fam_lst))
                      )
                      ; Now have list of valid family values in "picked_fam_lst". Go 
                      ; through the family data and filter out all entries that do NOT
                      ; have a fam1 that shows up in the picked fam list.
                      (setq rtrn nil) ;----
                      (foreach lst rtrn
                      (if (OR (member (nth 43 lst) picked_fam_lst)
			      (member (nth 43 lst) picked_fam_lst))
                                (progn ; OK, this from/to entry includes one of the target INST values
                                  (setq rtrn (cons lst rtrn)) ; save it in the output list
                      ) ) )
                      (setq rtrn (reverse rtrn)) ; put back into original order
                      (setq rtrn rtrn) ; fresh copy for possible further processing
                ) ) )                 
          ) ) ) 
      ) ) 


    ) ; <-- Keep
 ) ; <-- Keep 

        (c:wd_rtrn_2wd (list rtrn rtrn_part2)) ; paste two lists back together and return                                  
        ; back to AutoCAD Electrical's report dialog
)

; -- the following AUTO-STARTS when this file is "loaded" from within AutoCAD Electrical (i.e.
;    user hits the "User post" button on a report display dialog)
(_wd_post_main) ; run the above program
(princ)

 

AutoCAD Customization: Visual LISP, AutoLISP and General Customization: BREAK LINES HORIZONTALLY OR VERTICALLY

$
0
0

Just wondering if anyone can help me with a routine that has the option to break vertical or break horizontal, depending on the option, the lines that cross either the horizontal or vertical (again, depending on the option) a specified distance (say .05) on either side of the line you wanted to keep.  So if I choose BREAKH, the vertical lines that I choose would break any horizontal lines that cross them.  Same applies to BREAKV.  Hopefully I communicated clearly enough.  Thanks in advance!

AutoCAD Customization: .NET: How to remove the 'user interaction' part from a code?

$
0
0

Hi all,

I have got this code by KEAN WALMSLEY.

His code will ask user to select a block and then list all of selected block's attributes. However, I need to tweak his code a little bit and instead of user interaction, the block has to be selected by its name and through my code.

Here is his code (with slight changes to suit my purpose):

 

rivate Sub ListAttributes()
            Dim ed As Editor = Application.DocumentManager.MdiActiveDocument.Editor
            Dim db As Database = HostApplicationServices.WorkingDatabase
            Dim tr As Transaction = db.TransactionManager.StartTransaction()
            Try
                Dim filList As TypedValue() = New TypedValue(0) {New TypedValue(CInt(DxfCode.Start), "INSERT")}
                Dim filter As New SelectionFilter(filList)
                Dim opts As New PromptSelectionOptions()
                opts.MessageForAdding = "Select block references: "
                Dim res As PromptSelectionResult = ed.GetSelection(opts, filter)
                If res.Status <> PromptStatus.OK Then
                    Return
                End If
                Dim selSet As SelectionSet = res.Value
                Dim idArray As ObjectId() = selSet.GetObjectIds()
                For Each blkId As ObjectId In idArray
                    Dim blkRef As BlockReference = DirectCast(tr.GetObject(blkId, OpenMode.ForRead), BlockReference)

                    Dim btr As BlockTableRecord = DirectCast(tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead), BlockTableRecord)
                    ed.WriteMessage(vbLf & "Block: " + btr.Name)
                    btr.Dispose()
                    Dim attCol As AttributeCollection = blkRef.AttributeCollection
                    For Each attId As ObjectId In attCol
                        Dim attRef As AttributeReference = DirectCast(tr.GetObject(attId, OpenMode.ForRead), AttributeReference)
                        Dim str As String = (vbLf & attRef.Tag + "    " & attRef.TextString)
                        ed.WriteMessage(str)
                    Next
                Next
                tr.Commit()
            Catch ex As Autodesk.AutoCAD.Runtime.Exception
                ed.WriteMessage(("Exception: " + ex.Message))
            Finally
                tr.Dispose()
            End Try
        End Sub

 Now, I need to change this Sub to a Function as below:

Private Function ListAttributes (blockName As String) As Boolean

 The aim is to list all block attributes if the 'blockName' exists in drawing and return True afterwards. Oppositely it should return me False and print nothing to Editor if blockName does not exist.

Can anyone help me please?

Cheers

 

 

 

Viewing all 1680 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>