Author Topic: looping drawings to import block/reference.  (Read 2618 times)

0 Members and 1 Guest are viewing this topic.

BillZndl

  • Guest
looping drawings to import block/reference.
« on: June 18, 2014, 04:52:09 PM »
Acad2012 vs 2010

I tried using Fixo's code to insert a remote .dwg into the current drawing.
Works fine so I tried to loop through multiple drawings and insert the same block.
Does the first drawing fine then it runs away after the first drawing.
I've tried promptPointResults and other methods to get the insertion point before the code can run but it just runs away, importing the block,
inserting the reference at Point3d origin, saving the dwg, then goes to the next drawing. Ignoring the delegate prompts.
Is it possible to loop through drawings from a list like this and run code? or am I trying the impossible?

Code: [Select]
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;
using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;

namespace AddDeptTag
{   
    public class FindTEXT
    {
        /// <summary>
        /// AddDeptTag, opens drawings listed.
        /// Inserts dept tag into drawing.
        /// </summary>
        ///
        private string filePath = "G:\\AutoCAD2012Support\\LispText\\";                           //path.
        private string blockFile = "G:\\AutoCAD2012Support\\LispBlocks\\WBAY.dwg";       

        [CommandMethod("AddDept", CommandFlags.Session)]

        public void AddDeptTagToDrawings()
        {
            if (MessageBox.Show("This program reads PartsList.txt, opens each part drawing in list and inserts\n" +
                                "Department Tage into drawing.\n" +
                                "Please check the text file so it is currently what you want to add tag to.\n" +
                                "If you are uncertain to what this program does, Exit Now!\n" +
                                "To continue, hit Yes, to Cancel, hit No.", "Replace Text", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {               
                string filename = filePath + "PartsList.txt";                            //list of aluminum parts.               
                string blkName;
                Point3d ptLoc = Point3d.Origin;
               
                if (File.Exists(filename))
                {
                    try
                    {
                       
                        string[] lines = File.ReadAllLines(filename);    //array of filename strings.               
                       
                        for (int i = 0; i < lines.Length; i++)
                        {
                            string str = lines[i];

                            Document docToInsert = AcadApp.DocumentManager.Open(str, false);

                            Document document = AcadApp.DocumentManager.MdiActiveDocument;
                            Editor editor = document.Editor;
                            Database db = document.Database;                           

                            //db.UpdateExt(true);
                            Point3d DwgExtMin = db.Extmin;
                            Point3d DwgExtMax = db.Extmax;

                            using (docToInsert.LockDocument())
                            {
                                using (Transaction transaction = docToInsert.TransactionManager.StartTransaction())
                                {
                                    BlockTable table = (BlockTable)transaction.GetObject(db.BlockTableId, OpenMode.ForWrite);
                                    BlockTableRecord btr = (BlockTableRecord)transaction.GetObject(table[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                                    Point3d extMin;
                                    Point3d extMax;
                                    Matrix3d scaleMat = new Matrix3d();

                                    using (Database database = new Database(false, false))
                                    {
                                        blkName = Path.GetFileNameWithoutExtension(blockFile);
                                        database.ReadDwgFile(blockFile, System.IO.FileShare.ReadWrite, false, "");
                                        database.UpdateExt(true);
                                        extMin = database.Extmin;
                                        extMax = database.Extmax;
                                        db.Insert(blkName, database, true);
                                    }

                                    if (table.Has(blkName))
                                    {
                                        /*if (DwgExtMin.DistanceTo(DwgExtMax) > extMin.DistanceTo(extMax))
                                        {
                                            scaleMat = Matrix3d.Scaling(DwgExtMin.DistanceTo(DwgExtMax) / extMin.DistanceTo(extMax) * 0.125, Point3d.Origin);
                                        }*/                                                                         
                                            BlockReference bref = new BlockReference(Point3d.Origin, table[blkName]);                                       
                                            btr.AppendEntity(bref);
                                            transaction.AddNewlyCreatedDBObject(bref, true);
                                            //bref.TransformBy(scaleMat);
                                            //Extents3d ext = bref.GeometricExtents;
                                       
                                            PromptSelectionResult psr = editor.SelectLast();
                                            SelectionSet ssLast = psr.Value;                                       
                                           
                                            if (psr.Status == PromptStatus.OK)
                                            {
                                                PromptPointResult ppr = editor.Drag( ssLast,"\nPick point to insert block " + blkName + " : ",
                                                    delegate(Point3d pt, ref Matrix3d mat)
                                                    {
                                                        if (ptLoc == pt)
                                                            return SamplerStatus.NoChange;
                                                        else
                                                        {
                                                            mat = Matrix3d.Displacement(ptLoc.GetVectorTo(pt));
                                                        }
                                                        return SamplerStatus.OK;
                                                    }
                                                  );

                                                if (ppr.Status == PromptStatus.OK)
                                                {

                                                    Matrix3d mat = Matrix3d.Displacement(ptLoc.GetVectorTo(ppr.Value));
                                                    bref.TransformBy(mat * scaleMat);
                                                    transaction.TransactionManager.QueueForGraphicsFlush();
                                                }                                           
                                             }
                                         }                                   

                                    transaction.Commit();
                                }
                            }
                            docToInsert.CloseAndSave(str);
                        }                                            //foreach file in list of files.                         
                    }                                                //try block
                    catch (System.Exception exception)
                    {
                        MessageBox.Show("\nError: " + exception);
                    }                   
                }                                                  //if file exist.
                else
                {
                    MessageBox.Show("\nCheck if all files exist.\n");
                }
            }
        }            //dialog box yes/no to start program.
    }       
}
/* PromptPointOptions ppo = new PromptPointOptions("\nPick insertion point.");
                                                              ppo.AllowNone = false;
                                                              ppo.BasePoint = ptLoc;
                                                              ppo.UseBasePoint = true;
                                                              ppo.UseDashedLine = true;
                                                              ppo.Message = "\nPick a point to insert Block: " + blkName + " : ";

                                           PromptPointResult ppr = editor.GetPoint(ppo);

                                        if (ppr.Status == PromptStatus.OK)
                                        {*/
« Last Edit: June 18, 2014, 04:59:47 PM by BillZndl »

BillZndl

  • Guest
Re: looping drawings to import block/reference.
« Reply #1 on: June 19, 2014, 08:13:46 AM »
ok,
I've come to the conclusion that * I can * loop through documents and run code, according to this thread: http://www.theswamp.org/index.php?topic=47223.msg522508#msg522508

Why my program is ignoring the -> PromptPointResult ppr = editor.Drag(ssLast, "\nPick point to insert block " + blkName + " : ",
could mean that sampler status is somehow retained and used again in the next document.
So, I will have to work on this.
Any ideas or comments welcome.
TIA

n.yuan

  • Bull Frog
  • Posts: 348
Re: looping drawings to import block/reference.
« Reply #2 on: June 19, 2014, 09:20:17 AM »
You could try to set MdiActiveDocument after a drawing file is opened:


Code: [Select]
for (int i = 0; i < lines.Length; i++)
{
    string str = lines[i];
    Document docToInsert = AcadApp.DocumentManager.Open(str, false);

    [b]AcadDocumentManager.MidActiveDocument=docToInsert;[/b]

    Document document = AcadApp.DocumentManager.MdiActiveDocument;
    Editor editor = document.Editor;
    ...
    ...
}

I know the commandMethod has "Session" flag. Normally with "Session" flag, the newly opened drawing should become current document after opening. But maybe, it could be so if there is not code executing right after the opening? This may be the explanation the Editor could still point to the first drawing's Editor, not the newly opened document's Editor?

BillZndl

  • Guest
Re: looping drawings to import block/reference.
« Reply #3 on: June 19, 2014, 10:11:23 AM »
Thanks Norman!

But I tried that earlier with same results.
I tried:
Document document = docToInsert;
Editor editor = document.Editor;
Same thing.

Everything does as it should. Imports dwg, inserts block,
But after the first document is closed/saved, the program continues to run without pausing for the PromptPointResult ppr = editor.Drag(

I filtered the selection set to make sure I was getting the correct item but it still hiccups.

TypedValue[] acTV = new TypedValue[2];
                    acTV.SetValue(new TypedValue(0, "INSERT"), 0);
                    acTV.SetValue(new TypedValue(2, "WBAY"), 1);
                                 
                   SelectionFilter Filter = new SelectionFilter(acTV);
                   PromptSelectionResult psr = editor.SelectAll(Filter);
                //PromptSelectionResult psr = editor.SelectLast();
                   SelectionSet ssLast = psr.Value;

if (psr.Status == PromptStatus.OK && ssLast.Count == 1)
                                        {
                                           
                                            PromptPointResult ppr = editor.Drag(


BillZndl

  • Guest
Re: looping drawings to import block/reference.
« Reply #4 on: June 19, 2014, 01:10:37 PM »
sorry.

needs to be:

SDI = 0;


n.yuan

  • Bull Frog
  • Posts: 348
Re: looping drawings to import block/reference.
« Reply #5 on: June 19, 2014, 02:08:39 PM »
OK, in this case, I was correct that the "Session" flag does make newly opened document MdiActiveDocument automatically and

Application.DocumantManager.MdiActiveDocument=docToInsert

is not necessary.

Your problem of block not being moved is actually, well, like always, a code bug of yours:

bref.TransformBy(mat * scaleMat);

where "scaleMat" is an empty Matrix3d, which effectively nullified the transform matrix. Removing it or making it a valid Matrix3d, your code will work.

BillZndl

  • Guest
Re: looping drawings to import block/reference.
« Reply #6 on: June 19, 2014, 02:29:35 PM »
Your problem of block not being moved is actually, well, like always, a code bug of yours:

bref.TransformBy(mat * scaleMat);

where "scaleMat" is an empty Matrix3d, which effectively nullified the transform matrix. Removing it or making it a valid Matrix3d, your code will work.

Thanks,
i was giving scaleMat some values but I removed it during debug and forgot to remove it in the formula also.
The biggest problem was the program wasn't giving me a chance to pick a new point to move to.
Problems now solved, I'll work on the scaling.
We have a ton of drawings we need to add the dept label to so this will save much time.
Thanks again!
« Last Edit: June 19, 2014, 02:47:39 PM by BillZndl »

Bryco

  • Water Moccasin
  • Posts: 1883

BillZndl

  • Guest
Re: looping drawings to import block/reference.
« Reply #8 on: June 23, 2014, 12:09:39 PM »
Fiberworld?
http://www.theswamp.org/index.php?topic=45176.msg506745#msg506745

On my computer, Nextfiberworld = 1

I think confusion came in with SDI =1, the program opened the first drawing and executed it perfectly
but then would close the drawing and AutoCAD, then had to restart AutoCAD to open the next drawing.
Don't know if that had anything to do with the session context or not but the prompt for pick point/drag never paused the loop.
The program would simply loop through the drawing list, insert the dwg, close/save and go to the next drawing without asking for a point.

When I switched it to SDI = 0, AutoCAD opened and close/save the drawings, in the same session and the hiccup disappeared.

The scale matrix that Norman pointed out was, I think, just a side glitch I had overlooked.
I hadn't noticed it because I never got to the point where things were looping correctly.
Once I got things looping correctly, then I noticed the block position and size wasn't being modified.

Again, sorry for the confusion, I am not a "professional programmer" but that doesn't stop me from trying.  :angel: