.NET
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Save as problem - pls help

5 REPLIES 5
Reply
Message 1 of 6
nklong
462 Views, 5 Replies

Save as problem - pls help

I have some files path store in a string[] variable. I want open each file and send string to execute, like as draw a line in drawing. Then save, close drawing and continue to another file. This is my code:

 

        [CommandMethod("send")]

        public static void test()

        {

            string Command = "(Command \".Line\" '(0 0) '(0 10) \"\") ";

            string[] Files = new string[3];

            Files[0] = "C:\\test1.dwg";

            Files[1] = "C:\\test2.dwg";

            Files[2] = "C:\\test3.dwg";

            foreach (string fil in Files)

            {

                if (System.IO.File.Exists(fil) == true)

                {

                    DocumentCollection acDocMgr = Application.DocumentManager;

                    Document acDoc = acDocMgr.MdiActiveDocument;

                    try

                    {

                        acDoc = acDocMgr.Open(fil, false);

                        using (DocumentLock DcLck = acDoc.LockDocument())

                        {

                            using (Transaction acTrans = acDoc.Database.TransactionManager.StartTransaction())

                            {

                                acDoc.SendStringToExecute(Command, true, false, false);

                                acDoc.Database.SaveAs(acDoc.Name, true, DwgVersion.Current, acDoc.Database.SecurityParameters);

                                acTrans.Commit();

                            }

                        }

                        acDoc.CloseAndSave(fil);

                    }

                    catch (Autodesk.AutoCAD.Runtime.Exception ex)

                    {

                        acDoc.Editor.WriteMessage("Error: " + ex.ToString());

                    }

                }

            }

        }

 

But it had error at Save as line. Please help!

5 REPLIES 5
Message 2 of 6
amanero
in reply to: nklong

The problem that you are having is that "SendStringToExecute" is an Asynchronous command, so you are trying to save and close your document while the comand is being executed.

 

Time ago, I found a class from caddzone.com that envolves the synchronous "acedCmd" command.

 

Here you have the code, try to use it instead the "SendStringToExecute".

 

// CommandLine.cs Copyright (c) 2006 www.caddzone.com

//

// Original source location:

//

// http://www.caddzone.com/CommandLine.cs

//

// LICENSE:

//

// This software may not be published or reproduced in any

// form, without the express written consent of CADDZONE.COM

//

// Fair use:

//

// Permission to use this software in object code form, for

// private software development purposes, and without fee is

// hereby granted, provided that the above copyright notice

// appears in all copies and that both that copyright notice

// and limited warranty and restricted rights notice below

// appear in all supporting documentation.

//

// CADDZONE.COM PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.

// CADDZONE.COM SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF

// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. CADDZONE.COM

// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE

// UNINTERRUPTED OR ERROR FREE.

//

// Use, duplication, or disclosure by the U.S. Government is subject to

// restrictions set forth in FAR 52.227-19 (Commercial Computer

// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)

// (Rights in Technical Data and Computer Software), as applicable.

using

System;

using

System.Security;

using

System.Runtime.InteropServices;

using

Autodesk.AutoCAD.ApplicationServices;

using

Autodesk.AutoCAD.Runtime;

using

System.Collections;

using

Autodesk.AutoCAD.Geometry;

using

Autodesk.AutoCAD.DatabaseServices;

using

Autodesk.AutoCAD.EditorInput;

using

AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;

using

System.Collections.Generic;

namespace

CADFuncs

{

[

SuppressUnmanagedCodeSecurity]

 

publicstaticclassCommandLine

{

conststring ACAD_EXE = "acad.exe";

 

constshortRTSTR = 5005;

 

constshortRTNORM = 5100;

 

constshortRTNONE = 5000;

 

constshortRTREAL = 5001;

 

constshortRT3DPOINT = 5009;

 

constshortRTLONG = 5010;

 

constshortRTSHORT = 5003;

 

constshortRTENAME = 5006;

 

constshort RTPOINT = 5002; /*2D point X and Y only */staticDictionary<Type, short> resTypes = newDictionary<Type, short>();

 

staticCommandLine()

{

resTypes[

typeof(string)] = RTSTR;

resTypes[

typeof(double)] = RTREAL;

resTypes[

typeof(Point3d)] = RT3DPOINT;

resTypes[

typeof(ObjectId)] = RTENAME;

resTypes[

typeof(Int32)] = RTLONG;

resTypes[

typeof(Int16)] = RTSHORT;

resTypes[

typeof(Point2d)] = RTPOINT;

}

staticTypedValue TypedValueFromObject(Objectval)

{

if (val == null)

 

thrownewArgumentException("null not permitted as command argument");

 

shortcode = -1;

 

if (resTypes.TryGetValue(val.GetType(), outcode) && code > 0)

 

returnnewTypedValue(code, val);

 

thrownewInvalidOperationException("Unsupported type in Command() method");

}

publicstaticint Command(paramsobject[] args)

{

if (AcadApp.DocumentManager.IsApplicationContext)

 

thrownewInvalidCastException("Invalid execution context");

 

intstat = 0;

 

intcnt = 0;

 

using (ResultBuffer buffer = newResultBuffer())

{

foreach (object o inargs)

{

buffer.Add(TypedValueFromObject(o));

++cnt;

}

if(cnt > 0)

{

stat = acedCmd(buffer.UnmanagedObject);

}

}

returnstat;

}

[

DllImport("acad.exe", CallingConvention = CallingConvention.Cdecl)]

 

externstaticint acedCmd(IntPtrresbuf);

}

/*public class Examples

{

// Sample member functions that use the Command() method.

public static int ZoomExtents()

{

return CommandLine.Command("._ZOOM", "_E");

}

public static int ZoomCenter(Point3d center, double height)

{

return CommandLine.Command("._ZOOM", "_C", center, height);

}

public static int ZoomWindow(Point3d corner1, Point3d corner2)

{

return CommandLine.Command("._ZOOM", "_W", corner1, corner2);

}

}*/

}

 

 

Luis Alberto Manero, Geograma.com
Message 3 of 6
nklong
in reply to: amanero

Thank you so much. I will try.

 

Best regard,

nklong

Message 4 of 6
Alexander.Rivilis
in reply to: amanero

This code does not work with the latest versions of AutoCAD. Also you have to use Insert Code button in order to code can be readable:
01-03-2013 15-59-28.png

 

You can use: http://forums.autodesk.com/t5/NET/synchronicity-friends-amp-acedcommand/m-p/3424691#M28398 or http://forums.autodesk.com/t5/NET/Send-Command-Executes-after-exiting-command-method/m-p/3882952#M34...

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 5 of 6
DiningPhilosopher
in reply to: nklong

The other suggestions regarding using acedCmd() or RunCommand() via wrappers will not work from the application context, which is where your code is running.

 

To solve the problem, you need to define a custom command and invoke it using SendStringToExecute().   From within your custom command, you can then use acedCmd() or RunCommand(). You can set a flag that can be checked from the Application's Idle event that tells your application context code when the command has finished, and it can then invoke the command again to process the next file.

Message 6 of 6
Dx_Happy
in reply to: amanero

if you use documentcollection open method, then autocad will atuomatic change its status to applicationcontext,then if (AcadApp.DocumentManager.IsApplicationContext)

thrownewInvalidCastException("Invalid execution context");
these lines will work
so it will not work correctly

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report

”Boost