не валидируется Validate

Автор Тема: не валидируется Validate  (Прочитано 6957 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн Дамир МихайловичАвтор темы

  • ADN OPEN
  • Сообщений: 11
  • Карма: 0
Re: не валидируется Validate
« Ответ #15 : 13-08-2018, 10:05:25 »
Если я правильно понял, то
Код - C# [Выбрать]
  1. SetCurrentLayoutId
в строке 82 присутствует в ObjectARX начиная с версии 2016.
В autocad старше 2016 такое не скомпилируется?
У меня autocad 2015 и ObjectARX 2015. При отладке даже пошагово не запускается. Сразу появляется ошибка:

System.MissingMethodException: Метод не найден:
"Void Autodesk.AutoCAD.DatabaseServices.LayoutManager.SetCurrentLayoutId(Autodesk.AutoCAD.DatabaseServices.ObjectId)".
 
Разработка этого плагина главным образом нацелена на версии autocad 2013-2015.

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Re: не валидируется Validate
« Ответ #16 : 13-08-2018, 10:42:27 »
Дамир Михайлович,
Замени на:
Код - C# [Выбрать]
  1. LayoutManager.Current.CurrentLayout = lo.LayoutName;
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Оффлайн Дамир МихайловичАвтор темы

  • ADN OPEN
  • Сообщений: 11
  • Карма: 0
Re: не валидируется Validate
« Ответ #17 : 13-08-2018, 10:51:34 »
Поменял. Та же ошибка на Validate:


Autodesk.AutoCAD.Runtime.Exception
  HResult=0x80131500
  Сообщение = eLayoutNotCurrent
  Источник = accoremgd
  Трассировка стека:
   at Autodesk.AutoCAD.PlottingServices.PlotInfoValidator.Validate(PlotInfo info)
   at Plot1.Commands.PlotPDF() in D:\VS projects\example 8\Class1.cs:line 127
   at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorker(MethodInfo mi, Object commandObject, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorkerWithExceptionFilter(MethodInfo mi, Object commandObject, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.PerDocumentCommandClass.Invoke(MethodInfo mi, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.CommandClass.CommandThunk.Invoke()


Отмечено как Решение Дамир Михайлович 14-08-2018, 07:59:28

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Re: не валидируется Validate
« Ответ #18 : 13-08-2018, 11:33:51 »
Вот этот код я проверил с AutoCAD 2013, 2015, 2019 - везде работает:
Код - C# [Выбрать]
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.DatabaseServices;
  3. using Autodesk.AutoCAD.PlottingServices;
  4. using Autodesk.AutoCAD.Runtime;
  5. using System;
  6. using System.Runtime.InteropServices;
  7. using System.Windows.Forms;
  8. using System.Collections.Generic;
  9.  
  10. namespace Plot1
  11. {
  12.  
  13.   public class Commands : IExtensionApplication
  14.   {
  15.  
  16.     [DllImport("accore.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedTrans")]
  17.     static extern int acedTrans13(double[] point, IntPtr fromRb, IntPtr toRb, int disp, double[] result);
  18.     [DllImport("acad.exe", CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedTrans")]
  19.     static extern int acedTrans12(double[] point, IntPtr fromRb, IntPtr toRb, int disp, double[] result);
  20.     static int acedTrans(double[] point, IntPtr fromRb, IntPtr toRb, int disp, double[] result)
  21.     {
  22.       return Autodesk.AutoCAD.ApplicationServices.Application.Version.Major > 12 ?
  23.         acedTrans13(point, fromRb, toRb, disp, result) :
  24.         acedTrans12(point, fromRb, toRb, disp, result);
  25.     }
  26.  
  27.     [CommandMethod("PlotPDF", CommandFlags.Session)]
  28.     public void PlotPDF()
  29.     {
  30.  
  31.       string line = @"D:\autocad\qq.dwg";
  32.       short bgp = (short)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("BACKGROUNDPLOT");
  33.       Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);
  34.       Document curDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
  35.  
  36.       Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.Open(line, false);
  37.  
  38.       if (curDoc != doc)
  39.       {
  40.         Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument = doc;
  41.       }
  42.  
  43.       using (DocumentLock docLock = doc.LockDocument())
  44.       {
  45.  
  46.         Database db = doc.Database;
  47.         // A PlotEngine does the actual plotting
  48.         // (can also create one for Preview)
  49.         if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
  50.         {
  51.           PlotEngine pe = PlotFactory.CreatePublishEngine();
  52.           using (pe)
  53.           {
  54.             using (Transaction tr = doc.TransactionManager.StartTransaction())
  55.             {
  56.               BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
  57.               // Collect all the paperspace layouts
  58.               // for plotting
  59.               ObjectIdCollection layoutsToPlot = new ObjectIdCollection();
  60.               foreach (ObjectId btrId in bt)
  61.               {
  62.                 BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead);
  63.                 if ((btr.IsLayout && btr.Name.ToUpper() != BlockTableRecord.ModelSpace.ToUpper()) || (btr.IsLayout && btr.Name.ToUpper() == BlockTableRecord.ModelSpace.ToUpper()))
  64.                 {
  65.                   layoutsToPlot.Add(btr.LayoutId);
  66.                 }
  67.               }
  68.               SortWithTabOrder(ref layoutsToPlot);
  69.               // Create a Progress Dialog to provide info
  70.               // and allow the user to cancel                        
  71.               PlotProgressDialog ppd = new PlotProgressDialog(false, layoutsToPlot.Count, true);
  72.               using (ppd)
  73.               {
  74.                 int numSheet = 1;
  75.                 foreach (ObjectId layoutId in layoutsToPlot)
  76.                 {
  77.                   PlotInfo pi = new PlotInfo();
  78.                   PlotInfoValidator piv = new PlotInfoValidator();
  79.                   piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
  80.                   Layout lo = (Layout)tr.GetObject(layoutId, OpenMode.ForRead);
  81.                   // Make the layout we're plotting current
  82.                   LayoutManager.Current.CurrentLayout = lo.LayoutName;
  83.  
  84.                   // We need a PlotSettings object
  85.                   // based on the layout settings
  86.                   // which we then customize
  87.                   PlotSettings ps = new PlotSettings(lo.ModelType);
  88.  
  89.                   ps.CopyFrom(lo);
  90.  
  91.                   // The PlotSettingsValidator helps
  92.                   // create a valid PlotSettings object
  93.  
  94.                   PlotSettingsValidator psv = PlotSettingsValidator.Current;//текущий доk
  95.  
  96.                   // We'll plot the extents, centered and
  97.                   // scaled to fit
  98.  
  99.                   psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
  100.                   psv.SetUseStandardScale(ps, true);
  101.                   psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);
  102.                   psv.SetPlotCentered(ps, true);
  103.  
  104.                   PlotRotation Rot = PlotRotation.Degrees000;
  105.  
  106.                   if ((lo.Limits.MaxPoint.X < lo.Limits.MaxPoint.Y))
  107.                   {
  108.                     Rot = PlotRotation.Degrees090;
  109.                   }
  110.                   psv.SetPlotRotation(ps, Rot);
  111.  
  112.                   // We'll use the standard DWFx PC3, as
  113.                   // this supports multiple sheets
  114.  
  115.                   psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", null);
  116.  
  117.                   psv.RefreshLists(ps);
  118.  
  119.  
  120.                   // We need a PlotInfo object
  121.                   // linked to the layout                                
  122.                   pi.Layout = lo.Id;
  123.  
  124.                   // We need to link the PlotInfo to the
  125.                   // PlotSettings and then validate it
  126.                   pi.OverrideSettings = ps;
  127.  
  128.                   piv.Validate(pi);
  129.  
  130.  
  131.                   if (numSheet == 1)
  132.                   {
  133.                     ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Обработка документа");
  134.                     ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Отмена");
  135.                     ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Отмена листа");
  136.                     ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Обработка слоёв");
  137.                     ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Обработка листа");
  138.                     ppd.LowerPlotProgressRange = 0;
  139.                     ppd.UpperPlotProgressRange = 100;
  140.                     ppd.PlotProgressPos = 0;
  141.                     // Let's start the plot, at last
  142.                     ppd.OnBeginPlot();
  143.                     ppd.IsVisible = true;
  144.                     pe.BeginPlot(ppd, null);
  145.                     // We'll be plotting a single document                                    
  146.                     pe.BeginDocument(pi, doc.Name, null, 1, true, "d:\\test-multi-sheet");
  147.                   }
  148.                   // Which may contain multiple sheets
  149.                   ppd.StatusMsgString = "Обработка " + doc.Name.Substring(doc.Name.LastIndexOf("\\") + 1) + " - страница " + numSheet.ToString() + " из " + layoutsToPlot.Count.ToString();
  150.                   ppd.OnBeginSheet();
  151.                   ppd.LowerSheetProgressRange = 0;
  152.                   ppd.UpperSheetProgressRange = 100;
  153.                   ppd.SheetProgressPos = 0;
  154.                   PlotPageInfo ppi = new PlotPageInfo();
  155.                   pe.BeginPage(ppi, pi, (numSheet == layoutsToPlot.Count), null);
  156.                   pe.BeginGenerateGraphics(null);
  157.                   ppd.SheetProgressPos = 50;
  158.                   pe.EndGenerateGraphics(null);
  159.                   // Finish the sheet
  160.                   pe.EndPage(null);
  161.                   ppd.SheetProgressPos = 100;
  162.                   ppd.OnEndSheet();
  163.                   numSheet++;
  164.                 }
  165.  
  166.                 // Finish the document
  167.                 pe.EndDocument(null);
  168.                 // And finish the plot
  169.                 ppd.PlotProgressPos = 100;
  170.                 ppd.OnEndPlot();
  171.                 pe.EndPlot(null);
  172.               }
  173.               tr.Commit();
  174.             }
  175.           }
  176.         }
  177.         else
  178.         {
  179.           MessageBox.Show("Принтер занят");
  180.         }
  181.       }
  182.       Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
  183.       if (curDoc != doc)
  184.       {
  185.         Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument = curDoc;
  186.         doc.CloseAndDiscard();
  187.       }
  188.     }
  189.     /// <summary>
  190.     /// Сортируем листы в том порядке, в котором они в AutoCAD
  191.     /// </summary>
  192.     /// <param name="ids"></param>
  193.     void SortWithTabOrder(ref ObjectIdCollection ids)
  194.     {
  195.       if (ids.Count == 0) return;
  196.       SortedDictionary<int, ObjectId> tab = new SortedDictionary<int, ObjectId>();
  197.       using (Transaction tr = ids[0].Database.TransactionManager.StartTransaction())
  198.       {
  199.         foreach (ObjectId id in ids)
  200.         {
  201.           Layout layout = tr.GetObject(id, OpenMode.ForRead) as Layout;
  202.           tab[layout.TabOrder] = id;
  203.         }
  204.         tr.Commit();
  205.       }
  206.       ids.Clear();
  207.       foreach (KeyValuePair<int, ObjectId> pair in tab)
  208.       {
  209.         ids.Add(pair.Value);
  210.       }
  211.     }
  212.  
  213.     public void Initialize() { }
  214.  
  215.     public void Terminate()  { }
  216.   }
  217. }

Прикладываю готовый проект.
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Re: не валидируется Validate
« Ответ #19 : 13-08-2018, 11:53:43 »
Проверка с AutoCAD 2015:

Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Оффлайн Дамир МихайловичАвтор темы

  • ADN OPEN
  • Сообщений: 11
  • Карма: 0
Re: не валидируется Validate
« Ответ #20 : 14-08-2018, 07:59:23 »
Протестировал.
Всё отлично работает!
Спасибо!

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Re: не валидируется Validate
« Ответ #21 : 14-08-2018, 12:23:43 »
Протестировал.
Всё отлично работает!
Спасибо!
Так что было в прошлый раз не так? Этот код - это код из #14 и замена из #16.
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Оффлайн Дамир МихайловичАвтор темы

  • ADN OPEN
  • Сообщений: 11
  • Карма: 0
Re: не валидируется Validate
« Ответ #22 : 14-08-2018, 12:29:13 »
После ответа #16 я исправил код так же, как в сообщении #18, но ошибка не пропала.
Некоторое время спустя запустил и уже не было ошибки.
Все разы запускал в отладке пошагово.
Сейчас всё работает отлично.