Exemple #1
0
        /// <summary>
        /// Creates an instance for the Revit file selected
        /// </summary>
        /// <param name="doc">Document to which the link should be added</param>
        /// <param name="revitFilePath">the full path of the Revit link to be added</param>
        private static void InstanceMaker(Document doc, string revitFilePath)
        {
            try
            {
                using (Transaction tr = new Transaction(doc))
                {
                    tr.Start("Revit files are being linked...");

                    // Cycle through the list
                    // Set the standard options and behavior for the links
                    FilePath         fp  = new FilePath(revitFilePath);
                    RevitLinkOptions rlo = new RevitLinkOptions(false);

                    // Create new revit link and store the path to the file as either absolute or relative
                    RevitLinkLoadResult result = RevitLinkType.Create(doc, fp, rlo);
                    ElementId           linkId = result.ElementId;

                    // Create the Revit Link Instance (this also automatically sets the link Origin-to-Origin)
                    // Pin the Revit link as well
                    RevitLinkInstance linkInstance = RevitLinkInstance.Create(doc, linkId);
                    linkInstance.Pinned = true;

                    tr.Commit();
                }
            }

            catch (Exception)
            {
                // not sure what exceptions may occur
                // make sure that whatever happens is logged for future troubleshooting
            }
        }
Exemple #2
0
        public ElementId CreateRevitLink(Document doc, string pathName)
        {
            FilePath         path    = new FilePath(pathName);
            RevitLinkOptions options = new RevitLinkOptions(false);

            // Create new revit link storing absolute path to a file
            RevitLinkLoadResult result = RevitLinkType.Create(doc, path, options);

            return(result.ElementId);
        }
Exemple #3
0
        /// <summary>
        /// Link in the new created document to parent document.
        /// </summary>
        /// <param name="baseFileName">The full path to the IFC file.</param>
        /// <param name="ifcDocument">The newly imported IFC file document.</param>
        /// <param name="originalDocument">The document to contain the IFC link.</param>
        /// <param name="useExistingType">True if the RevitLinkType already exists.</param>
        /// <param name="doSave">True if we should save the document.  This should only be false if we are reusing a cached document.</param>
        /// <returns>The element id of the RevitLinkType for this link operation.</returns>
        public static ElementId LinkInFile(string baseFileName, Document ifcDocument, Document originalDocument, bool useExistingType, bool doSave)
        {
            bool   saveSucceded = true;
            string fileName     = GenerateRevitFileName(baseFileName);

            if (doSave)
            {
                SaveAsOptions saveAsOptions = new SaveAsOptions();
                saveAsOptions.OverwriteExistingFile = true;

                try
                {
                    ifcDocument.SaveAs(fileName, saveAsOptions);
                }
                catch (Exception ex)
                {
                    // We still want to close the document to prevent having a corrupt model in memory.
                    Importer.TheLog.LogError(-1, ex.Message, false);
                    saveSucceded = false;
                }
            }

            if (!ifcDocument.IsLinked)
            {
                ifcDocument.Close(false);
            }

            ElementId revitLinkTypeId = ElementId.InvalidElementId;

            if (!saveSucceded)
            {
                return(revitLinkTypeId);
            }

            bool doReloadFrom = useExistingType && !Importer.TheOptions.CreateLinkInstanceOnly;

            if (Importer.TheOptions.RevitLinkFileName != null)
            {
                FilePath originalRevitFilePath = new FilePath(Importer.TheOptions.RevitLinkFileName);
                revitLinkTypeId = RevitLinkType.GetTopLevelLink(originalDocument, originalRevitFilePath);
            }

            if (!doReloadFrom)
            {
                Transaction linkTransaction = new Transaction(originalDocument);
                linkTransaction.Start(Resources.IFCLinkFile);

                try
                {
                    if (revitLinkTypeId == ElementId.InvalidElementId)
                    {
                        RevitLinkOptions    options    = new RevitLinkOptions(true);
                        RevitLinkLoadResult loadResult = RevitLinkType.CreateFromIFC(originalDocument, baseFileName, fileName, false, options);
                        if ((loadResult != null) && (loadResult.ElementId != ElementId.InvalidElementId))
                        {
                            revitLinkTypeId = loadResult.ElementId;
                        }
                    }

                    if (revitLinkTypeId != ElementId.InvalidElementId)
                    {
                        RevitLinkInstance.Create(originalDocument, revitLinkTypeId);
                    }

                    Importer.PostDelayedLinkErrors(originalDocument);
                    linkTransaction.Commit();
                }
                catch (Exception ex)
                {
                    linkTransaction.RollBack();
                    throw ex;
                }
            }
            else // reload from
            {
                // For the reload from case, we expect the transaction to have been created in the UI.
                if (revitLinkTypeId != ElementId.InvalidElementId)
                {
                    RevitLinkType existingRevitLinkType = originalDocument.GetElement(revitLinkTypeId) as RevitLinkType;
                    if (existingRevitLinkType != null)
                    {
                        existingRevitLinkType.UpdateFromIFC(originalDocument, baseFileName, fileName, false);
                    }
                }
            }

            return(revitLinkTypeId);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Debug.Listeners.Clear();
            Debug.Listeners.Add(new RbsLogger.Logger("BatchPrint"));
            Debug.WriteLine("Print started");

            App.assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            Selection sel     = commandData.Application.ActiveUIDocument.Selection;
            Document  mainDoc = commandData.Application.ActiveUIDocument.Document;

            string mainDocTitle = SheetSupport.GetDocTitleWithoutRvt(mainDoc.Title);

            YayPrintSettings printSettings = YayPrintSettings.GetSavedPrintSettings();

            printSettings.dwgProfiles = DwgSupport.GetAllDwgExportSettingsNames(mainDoc);


            //листы из всех открытых файлов, ключ - имя файла, значение - список листов
            Dictionary <string, List <MySheet> > allSheets = SheetSupport.GetAllSheets(commandData, printSettings);

            //получаю выбранные листы в диспетчере проекта
            List <ElementId> selIds = sel.GetElementIds().ToList();
            //List<MySheet> mSheets0 = new List<MySheet>();
            bool sheetsIsChecked = false;

            foreach (ElementId id in selIds)
            {
                Element   elem  = mainDoc.GetElement(id);
                ViewSheet sheet = elem as ViewSheet;
                if (sheet == null)
                {
                    continue;
                }
                sheetsIsChecked = true;

                MySheet sheetInBase = allSheets[mainDocTitle].Where(i => i.sheet.Id.IntegerValue == sheet.Id.IntegerValue).First();
                sheetInBase.IsPrintable = true;

                //mSheets0.Add(new MySheet(sheet));
            }
            if (!sheetsIsChecked)
            {
                message = "Не выбраны листы. Выберите листы в Диспетчере проекта через Shift.";
                Debug.WriteLine("Печать остановлена, не выбраны листы");
                return(Result.Failed);
            }


            //запись статистики по файлу
            //ProjectRating.Worker.Execute(commandData);

            //очистка старых Schema при необходимости

            /*try
             * {
             *  Autodesk.Revit.DB.ExtensibleStorage.Schema sch =
             *       Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(new Guid("414447EA-4228-4B87-A97C-612462722AD4"));
             *  Autodesk.Revit.DB.ExtensibleStorage.Schema.EraseSchemaAndAllEntities(sch, true);
             *
             *  Autodesk.Revit.DB.ExtensibleStorage.Schema sch2 =
             *       Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(new Guid("414447EA-4228-4B87-A97C-612462722AD5"));
             *  Autodesk.Revit.DB.ExtensibleStorage.Schema.EraseSchemaAndAllEntities(sch2, true);
             *  Debug.WriteLine("Schema очищены");
             * }
             * catch
             * {
             *  Debug.WriteLine("Не удалось очистить Schema");
             * }
             */

            FormPrint form = new FormPrint(allSheets, printSettings);

            form.ShowDialog();

            if (form.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }
            Debug.WriteLine("В окне печати нажат ОК, переход к печати");
            printSettings = form.printSettings;

            string printerName = printSettings.printerName;

            allSheets = form.sheetsSelected;
            Debug.WriteLine("Выбранные для печати листы");
            foreach (var kvp in allSheets)
            {
                Debug.WriteLine(" Файл " + kvp.Key);
                foreach (MySheet ms in kvp.Value)
                {
                    Debug.WriteLine("  Лист " + ms.sheet.Name);
                }
            }

            string outputFolderCommon = printSettings.outputFolder;

            YayPrintSettings.SaveSettings(printSettings);
            Debug.WriteLine("Настройки печати сохранены");

            //Дополнительные возможности работают только с PDFCreator
            if (printerName != "PDFCreator")
            {
                if (printSettings.colorsType == ColorType.MonochromeWithExcludes || printSettings.mergePdfs || printSettings.useOrientation)
                {
                    string errmsg = "Объединение PDF и печать \"Штампа\" в цвете поддерживаются только  для PDFCreator.";
                    errmsg += "\nВо избежание ошибок эти настройки будут отключены.";
                    TaskDialog.Show("Предупреждение", errmsg);
                    printSettings.mergePdfs      = false;
                    printSettings.excludeColors  = new List <PdfColor>();
                    printSettings.useOrientation = false;
                    Debug.WriteLine("Выбранные настройки несовместимы с принтером " + printerName);
                }
            }
            else
            {
                if (!printSettings.useOrientation)
                {
                    SupportRegistry.SetOrientationForPdfCreator(OrientationType.Automatic);
                    Debug.WriteLine("Установлена ориентация листа Automatic");
                }
            }
            bool   printToFile  = form.printToFile;
            string outputFolder = "";

            if (printToFile)
            {
                outputFolder = PrintSupport.CreateFolderToPrint(mainDoc, printerName, outputFolderCommon);
                Debug.WriteLine("Создана папка для печати: " + outputFolder);
            }
            //List<string> pfdFileNames = new List<string>();

            //печатаю листы из каждого выбранного revit-файла
            List <MySheet> printedSheets = new List <MySheet>();

            foreach (string docTitle in allSheets.Keys)
            {
                Document openedDoc = null;
                Debug.WriteLine("Печать листов из файла " + docTitle);

                RevitLinkType rlt = null;

                //проверяю, текущий это документ или полученный через ссылку
                if (docTitle == mainDocTitle)
                {
                    openedDoc = mainDoc;
                    Debug.WriteLine("Это не ссылочный документ");
                }
                else
                {
                    List <RevitLinkType> linkTypes = new FilteredElementCollector(mainDoc)
                                                     .OfClass(typeof(RevitLinkType))
                                                     .Cast <RevitLinkType>()
                                                     .Where(i => SheetSupport.GetDocTitleWithoutRvt(i.Name) == docTitle)
                                                     .ToList();
                    if (linkTypes.Count == 0)
                    {
                        throw new Exception("Cant find opened link file " + docTitle);
                    }
                    rlt = linkTypes.First();

                    //проверю, не открыт ли уже документ, который пытаемся печатать
                    foreach (Document testOpenedDoc in commandData.Application.Application.Documents)
                    {
                        if (testOpenedDoc.IsLinked)
                        {
                            continue;
                        }
                        if (testOpenedDoc.Title == docTitle || testOpenedDoc.Title.StartsWith(docTitle) || docTitle.StartsWith(testOpenedDoc.Title))
                        {
                            openedDoc = testOpenedDoc;
                            Debug.WriteLine("Это открытый ссылочный документ");
                        }
                    }

                    //иначе придется открывать документ через ссылку
                    if (openedDoc == null)
                    {
                        Debug.WriteLine("Это закрытый ссылочный документ, пытаюсь его открыть");
                        List <Document> linkDocs = new FilteredElementCollector(mainDoc)
                                                   .OfClass(typeof(RevitLinkInstance))
                                                   .Cast <RevitLinkInstance>()
                                                   .Select(i => i.GetLinkDocument())
                                                   .Where(i => i != null)
                                                   .Where(i => SheetSupport.GetDocTitleWithoutRvt(i.Title) == docTitle)
                                                   .ToList();
                        if (linkDocs.Count == 0)
                        {
                            throw new Exception("Cant find link file " + docTitle);
                        }
                        Document linkDoc = linkDocs.First();

                        if (linkDoc.IsWorkshared)
                        {
                            Debug.WriteLine("Это файл совместной работы, открываю с отсоединением");
                            ModelPath   mpath = linkDoc.GetWorksharingCentralModelPath();
                            OpenOptions oo    = new OpenOptions();
                            oo.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
                            WorksetConfiguration wc = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets);
                            oo.SetOpenWorksetsConfiguration(wc);
                            rlt.Unload(new SaveCoordinates());
                            openedDoc = commandData.Application.Application.OpenDocumentFile(mpath, oo);
                        }
                        else
                        {
                            Debug.WriteLine("Это однопользательский файл");
                            string docPath = linkDoc.PathName;
                            rlt.Unload(new SaveCoordinates());
                            openedDoc = commandData.Application.Application.OpenDocumentFile(docPath);
                        }
                    }
                    Debug.WriteLine("Файл-ссылка успешно открыт");
                } //


                List <MySheet> mSheets = allSheets[docTitle];

                if (docTitle != mainDocTitle)
                {
                    List <ViewSheet> linkSheets = new FilteredElementCollector(openedDoc)
                                                  .OfClass(typeof(ViewSheet))
                                                  .Cast <ViewSheet>()
                                                  .ToList();
                    List <MySheet> tempSheets = new List <MySheet>();
                    foreach (MySheet ms in mSheets)
                    {
                        foreach (ViewSheet vs in linkSheets)
                        {
                            if (ms.SheetId == vs.Id.IntegerValue)
                            {
                                MySheet newMs = new MySheet(vs, printSettings.alwaysColorParamName);
                                tempSheets.Add(newMs);
                            }
                        }
                    }
                    mSheets = tempSheets;
                }
                Debug.WriteLine("Листов для печати найдено в данном файле: " + mSheets.Count.ToString());

                Debug.WriteLine(": " + mSheets.Count.ToString());
                PrintManager pManager = openedDoc.PrintManager;
                Debug.WriteLine("Текущий выбранный принтер: " + pManager.PrinterName);
                Debug.WriteLine("Попытка назначить принтер: " + printerName);
                pManager.SelectNewPrintDriver(printerName);
                pManager            = openedDoc.PrintManager;
                pManager.PrintRange = PrintRange.Current;
                pManager.Apply();
                Debug.WriteLine("Настройки менеджера печати успешно применены");


                //список основных надписей нужен потому, что размеры листа хранятся в них
                //могут быть примечания, сделанные Основной надписью, надо их отфильровать, поэтому >0.6
                List <FamilyInstance> titleBlocks = new FilteredElementCollector(openedDoc)
                                                    .WhereElementIsNotElementType()
                                                    .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                                    .Cast <FamilyInstance>()
                                                    .Where(t => t.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble() > 0.6)
                                                    .ToList();
                Debug.WriteLine("Найдено основных надписей: " + titleBlocks.Count.ToString());


                //получаю имя формата и проверяю, настроены ли размеры бумаги в Сервере печати
                string formatsCheckinMessage = PrintSupport.PrintFormatsCheckIn(openedDoc, printerName, titleBlocks, ref mSheets);
                if (formatsCheckinMessage != "")
                {
                    message = formatsCheckinMessage;
                    Debug.WriteLine("Проверка форматов листов неудачна: " + message);
                    return(Result.Failed);
                }
                Debug.WriteLine("Проверка форматов листов выполнена успешно, переход к печати");

                //если включен экспорт dwg - нахожу параметры экспорта по имени
                DWGExportOptions dwgOptions = null;
                if (printSettings.exportToDwg)
                {
                    List <ExportDWGSettings> curDwgSettings = DwgSupport.GetAllDwgExportSettingsNames(openedDoc)
                                                              .Where(i => i.Name == printSettings.selectedDwgExportProfileName)
                                                              .ToList();
                    if (curDwgSettings.Count == 0)
                    {
                        TaskDialog.Show("Ошибка", "В файле " + openedDoc.Title + " не найден dwg профиль " + printSettings.selectedDwgExportProfileName);
                        dwgOptions = DwgSupport.GetAllDwgExportSettingsNames(openedDoc).First().GetDWGExportOptions();
                    }
                    else
                    {
                        dwgOptions = curDwgSettings.First().GetDWGExportOptions();
                    }
                }

                //печатаю каждый лист
                foreach (MySheet msheet in mSheets)
                {
                    Debug.WriteLine(" ");
                    Debug.WriteLine("Печатается лист: " + msheet.sheet.Name);
                    if (printSettings.refreshSchedules)
                    {
                        SchedulesRefresh.Start(openedDoc, msheet.sheet);
                        Debug.WriteLine("Спецификации обновлены успешно");
                    }


                    using (Transaction t = new Transaction(openedDoc))
                    {
                        t.Start("Профили печати");

                        string fileName0 = "";
                        if (printSettings.mergePdfs)
                        {
                            string guid = Guid.NewGuid().ToString();
                            fileName0 = msheet.sheet.SheetNumber + "_" + guid + ".pdf";
                        }
                        else
                        {
                            fileName0 = msheet.NameByConstructor(printSettings.nameConstructor);
                        }
                        string fileName = SheetSupport.ClearIllegalCharacters(fileName0);
                        if (fileName.Length > 128)
                        {
                            Debug.WriteLine("Имя листа длиннее 128 символов, будет урезано");
                            string cutname = fileName.Substring(0, 63);
                            cutname += fileName.Substring(fileName.Length - 64);
                            fileName = cutname;
                        }

                        if (printerName == "PDFCreator" && printSettings.useOrientation)
                        {
                            if (msheet.IsVertical)
                            {
                                SupportRegistry.SetOrientationForPdfCreator(OrientationType.Portrait);
                                Debug.WriteLine("Принудительно установлена Portrait ориентация");
                            }
                            if (!msheet.IsVertical)
                            {
                                SupportRegistry.SetOrientationForPdfCreator(OrientationType.Landscape);
                                Debug.WriteLine("Принудительно установлена Landscape ориентация");
                            }
                        }

                        for (int i = 0; i < msheet.titleBlocks.Count; i++)
                        {
                            string tempFilename = "";
                            if (msheet.titleBlocks.Count > 1)
                            {
                                Debug.WriteLine("На листе более 1 основной надписи! Печать части №" + i.ToString());
                                tempFilename = fileName.Replace(".pdf", "_" + i.ToString() + ".pdf");
                            }
                            else
                            {
                                Debug.WriteLine("На листе 1 основная надпись Id " + msheet.titleBlocks.First().Id.IntegerValue.ToString());
                                tempFilename = fileName;
                            }

                            string fullFilename = System.IO.Path.Combine(outputFolder, tempFilename);
                            Debug.WriteLine("Полное имя файла: " + fullFilename);

                            if (fullFilename.Length > 256)
                            {
                                throw new Exception("Слишком длинное имя файла " + fullFilename);
                            }

                            //смещаю область для печати многолистовых спецификаций
                            double offsetX = -i * msheet.widthMm / 25.4; //смещение задается в дюймах!
                            Debug.WriteLine("Смещение печати по X: " + offsetX.ToString("F3"));

                            PrintSetting ps = PrintSupport.CreatePrintSetting(openedDoc, pManager, msheet, printSettings, offsetX, 0);

                            pManager.PrintSetup.CurrentPrintSetting = ps;
                            Debug.WriteLine("Настройки печати применены, " + ps.Name);


                            PrintSupport.PrintView(msheet.sheet, pManager, ps, tempFilename);
                            Debug.WriteLine("Лист успешно отправлен на принтер");
                            msheet.PdfFileName = fullFilename;
                            printedSheets.Add(new MySheet(msheet));
                        }

                        if (printerName == "PDFCreator" && printSettings.useOrientation)
                        {
                            System.Threading.Thread.Sleep(5000);
                        }

                        t.RollBack();
                    }

                    //если включен dwg - то ещё экспортирую этот лист
                    if (printSettings.exportToDwg)
                    {
                        List <ElementId> sheetsIds = new List <ElementId> {
                            msheet.sheet.Id
                        };
                        string sheetname = msheet.NameByConstructor(printSettings.dwgNameConstructor);
                        openedDoc.Export(outputFolder, sheetname, sheetsIds, dwgOptions);
                    }
                }

                if (rlt != null)
                {
                    openedDoc.Close(false);
#if R2017
                    RevitLinkLoadResult LoadResult = rlt.Reload();
#else
                    LinkLoadResult loadResult = rlt.Reload();
#endif
                    Debug.WriteLine("Ссылочный документ закрыт");
                }
            }
            int printedSheetsCount = printedSheets.Count;
            printedSheets.Sort();

            //если требуется постобработка файлов - ждем, пока они напечатаются
            if (printSettings.colorsType == ColorType.MonochromeWithExcludes || printSettings.mergePdfs)
            {
                Debug.WriteLine("Включена постобработка файлов; ожидание окончания печати. Требуемое число файлов " + printedSheetsCount.ToString());
                int watchTimer = 0;
                while (printToFile)
                {
                    int filescount = System.IO.Directory.GetFiles(outputFolder, "*.pdf").Length;
                    Debug.WriteLine("Итерация №" + watchTimer + ", файлов напечатано " + filescount);
                    if (filescount >= printedSheetsCount)
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(500);
                    watchTimer++;


                    if (watchTimer > 100)
                    {
                        BalloonTip.Show("Обнаружены неполадки", "Печать PDF заняла продолжительное время или произошел сбой. Дождитесь окончания печати.");
                        Debug.WriteLine("Не удалось дождаться окончания печати");
                        return(Result.Failed);
                    }
                }
            }


            List <string> pdfFileNames = printedSheets.Select(i => i.PdfFileName).ToList();
            Debug.WriteLine("PDF файлы которые должны быть напечатаны:");
            foreach (string pdfname in pdfFileNames)
            {
                Debug.WriteLine("  " + pdfname);
            }
            Debug.WriteLine("PDF файлы напечатанные по факту:");
            foreach (string pdfnameOut in System.IO.Directory.GetFiles(outputFolder, "*.pdf"))
            {
                Debug.WriteLine("  " + pdfnameOut);
            }

            //преобразую файл в черно-белый при необходимости
            if (printSettings.colorsType == ColorType.MonochromeWithExcludes)
            {
                Debug.WriteLine("Преобразование PDF файла в черно-белый");
                foreach (MySheet msheet in printedSheets)
                {
                    if (msheet.ForceColored)
                    {
                        Debug.WriteLine("Лист не преобразовывается в черно-белый: " + msheet.sheet.Name);
                        continue;
                    }

                    string file    = msheet.PdfFileName;
                    string outFile = file.Replace(".pdf", "_OUT.pdf");
                    Debug.WriteLine("Файл будет преобразован из " + file + " в " + outFile);

                    pdf.PdfWorker.SetExcludeColors(printSettings.excludeColors);
                    pdf.PdfWorker.ConvertToGrayScale(file, outFile);

                    //GrayscaleConvertTools.ConvertPdf(file, outFile, ColorType.Grayscale, new List<ExcludeRectangle> { rect, rect2 });

                    System.IO.File.Delete(file);
                    System.IO.File.Move(outFile, file);
                    Debug.WriteLine("Лист успешно преобразован");
                }
            }



            //объединяю файлы при необходимости
            if (printSettings.mergePdfs)
            {
                Debug.WriteLine(" ");
                Debug.WriteLine("\nОбъединение PDF файлов");
                System.Threading.Thread.Sleep(500);
                string combinedFile = System.IO.Path.Combine(outputFolder, mainDoc.Title + ".pdf");

                BatchPrintYay.pdf.PdfWorker.CombineMultiplyPDFs(pdfFileNames, combinedFile);

                foreach (string file in pdfFileNames)
                {
                    System.IO.File.Delete(file);
                    Debug.WriteLine("Удален файл " + file);
                }
                Debug.WriteLine("Объединено успешно");
            }

            if (printToFile)
            {
                System.Diagnostics.Process.Start(outputFolder);
                Debug.WriteLine("Открыта папка " + outputFolder);
            }

            //восстанавливаю настройки PDFCreator
            //if(printerName == "PDFCreator")
            //{
            //    SupportRegistry.RestoreSettingsForPDFCreator();
            //}


            string msg = "Напечатано листов: " + printedSheetsCount;
            BalloonTip.Show("Печать завершена!", msg);
            Debug.WriteLine("Печать успешно завершена, напечатано листов " + printedSheetsCount);
            return(Result.Succeeded);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document    mainDoc  = commandData.Application.ActiveUIDocument.Document;
            Application revitApp = commandData.Application.Application;

            //открываю окно выбора параметров, которые буду заполняться
            FormSelectParams formSelectParams = new FormSelectParams();

            formSelectParams.ShowDialog();
            if (formSelectParams.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }


            RebarDocumentWorker mainWorker = new RebarDocumentWorker();
            List <Element>      mainDocConcreteElements = new List <Element>();



            string mainWorkerMessage = mainWorker.Start(mainDoc, revitApp, Transform.Identity, out mainDocConcreteElements);

            if (!string.IsNullOrEmpty(mainWorkerMessage))
            {
                message = mainWorkerMessage + ". Документ " + mainDoc.Title;
                return(Result.Failed);
            }

            if (Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.NoLinks)
            {
                return(Result.Succeeded);
            }

            List <RevitLinkInstance> linksAll = new FilteredElementCollector(mainDoc)
                                                .OfClass(typeof(RevitLinkInstance))
                                                .Cast <RevitLinkInstance>()
                                                .ToList();

            List <RevitLinkInstance> linksLib = linksAll
                                                .Where(i => i.Name.Contains(".lib"))
                                                .ToList();

            // имя ссылки lib и список конструкций, которые она пересекает
            Dictionary <string, List <Element> > hostElemsForLibLinks = new Dictionary <string, List <Element> >();

            foreach (RevitLinkInstance rli in linksLib)
            {
                string  linkInstanceTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli);
                Element hostElem          = LinksSupport.GetConcreteElementIsHostForLibLinkFile(mainDoc, ViewSupport.GetDefaultView(mainDoc), mainDocConcreteElements, rli);
                if (hostElem == null)
                {
                    continue;
                }
                if (hostElemsForLibLinks.ContainsKey(linkInstanceTitle))
                {
                    hostElemsForLibLinks[linkInstanceTitle].Add(hostElem);
                }
                else
                {
                    hostElemsForLibLinks.Add(linkInstanceTitle, new List <Element> {
                        hostElem
                    });
                }
            }
            List <RevitLinkInstance> linksWithoutDuplicates = LinksSupport.DeleteDuplicates(linksAll);

            foreach (RevitLinkInstance rli in linksWithoutDuplicates)
            {
                RevitLinkType rlt     = mainDoc.GetElement(rli.GetTypeId()) as RevitLinkType;
                Document      linkDoc = rli.GetLinkDocument();
                if (linkDoc == null)
                {
                    continue;
                }

                string linkDocTitle = LinksSupport.GetDocumentTitleFromLinkInstance(rli);
                if (!linkDocTitle.Contains("-КР-"))
                {
                    continue;
                }
                if (!linkDocTitle.Contains("lib") && Settings.LinkFilesSetting == Settings.ProcessedLinkFiles.OnlyLibs)
                {
                    continue;
                }



                ModelPath mPath = linkDoc.GetWorksharingCentralModelPath();

                rlt.Unload(new SaveCoordinates());

                OpenOptions oo = new OpenOptions();

                linkDoc = revitApp.OpenDocumentFile(mPath, oo);


                RebarDocumentWorker linkWorker = new RebarDocumentWorker();
                if (linkDocTitle.Contains("lib"))
                {
                    if (hostElemsForLibLinks.ContainsKey(linkDocTitle))
                    {
                        List <Element> mainElemsForLib = hostElemsForLibLinks[linkDocTitle];
                        if (mainElemsForLib.Count > 0)
                        {
                            linkWorker.MainElementsForLibFile = mainElemsForLib;
                        }
                    }
                }
                Transform      linkTransform        = rli.GetTransform();
                List <Element> linkConcreteElements = new List <Element>();
                string         linkWorkerMessage    = linkWorker.Start(linkDoc, revitApp, linkTransform, out linkConcreteElements);
                if (!string.IsNullOrEmpty(linkWorkerMessage))
                {
                    message = linkWorkerMessage + ". Связь " + linkDoc.Title;
                    return(Result.Failed);
                }



                TransactWithCentralOptions    transOpt = new TransactWithCentralOptions();
                SynchronizeWithCentralOptions syncOpt  = new SynchronizeWithCentralOptions();

                RelinquishOptions relOpt = new RelinquishOptions(true);
                syncOpt.SetRelinquishOptions(relOpt);

                linkDoc.SynchronizeWithCentral(transOpt, syncOpt);

                linkDoc.Close();
#if R2017
                RevitLinkLoadResult rllr = rlt.Reload();
#else
                LinkLoadResult llr = rlt.Reload();
#endif
            }

            return(Result.Succeeded);
        }
        void MiroReloadLinks(IList <RevitLinkType> fecLinkTypes)
        {
            // Loop all RVT Links

            foreach (RevitLinkType typeLink in fecLinkTypes)
            {
                // ...

                // Skip1 - not IsFromRevitServer

                if (!typeLink.IsFromRevitServer())
                {
                    //…
                    continue;
                }

                // Skip2 - not ExternalFileReference
                // 99% it would already skip above as
                // RevitServer MUST be ExternalFileReference,
                // but leave just in case...

                ExternalFileReference er = typeLink.GetExternalFileReference();

                if (er == null)
                {
                    // ...

                    continue;
                }

                // If here, we can cache ModelPath related
                // info and show to user regardless if we skip
                // on next checks or not....

                ModelPath mp = er.GetPath();

                string userVisiblePath = ModelPathUtils
                                         .ConvertModelPathToUserVisiblePath(mp);

                // Skip3 - if ModelPath is NOT Server Path
                // 99% redundant as we already checked raw
                // RevitLinkType for this, but keep
                // just in case...

                if (!mp.ServerPath)
                {
                    // ...

                    continue;
                }

                // Skip4 - if NOT "NOT Found" problematic one
                // there is nothing to fix

                if (er.GetLinkedFileStatus()
                    != LinkedFileStatus.NotFound)
                {
                    // ...

                    continue;
                }

                // Skip5 - if Nested Link (can’t (re)load these!)

                if (typeLink.IsNestedLink)
                {
                    // ...

                    continue;
                }

                // If here, we MUST offer user to "Reload from..."

                // ...

                RevitLinkLoadResult res = null;

                try
                {
                    // This fails for problematic Server files
                    // since it also fails on "Reload" button in
                    // UI (due to the GUID issue in the answer)

                    //res = typeLink.Reload();

                    // This fails same as above :-(!

                    //res = typeLink.Load();

                    // This WORKS!
                    // Basically, this is the equivalent of UI
                    // "Reload from..." + browsing to the *same*
                    // Saved path showing in the manage Links
                    // dialogue.
                    // ToDo: Check if we need to do anything
                    // special with WorksetConfiguration?
                    // In tests, it works fine with the
                    // default c-tor.

                    ModelPath mpForReload = ModelPathUtils
                                            .ConvertUserVisiblePathToModelPath(
                        userVisiblePath);

                    res = typeLink.LoadFrom(mpForReload,
                                            new WorksetConfiguration());

                    Util.InfoMsg(string.Format(
                                     "Result = {0}", res.LoadResult));
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.Message);
                }
            } // foreach typeLink
        }
Exemple #7
0
        /// <summary>
        /// Reports the results of loads from the DB server (SampleExternalResourceServer).
        /// This method should be implemented to provide UI to communicate success or failure
        /// of a particular external resource load operation to the user.
        /// </summary>
        /// <param name="doc">The Revit model into which the External Resource was loaded.
        /// </param>
        /// <param name="loadDataList">Contains a list of ExternalResourceLoadData with results
        /// for all external resources loaded by the DB server.  It is possible for the DB server
        /// to have loaded more than one resource (for example, loading several linked files
        /// when a host file is opened by the user).
        /// </param>
        public void HandleLoadResourceResults(Document doc, IList <ExternalResourceLoadData> loadDataList)
        {
            foreach (ExternalResourceLoadData data in loadDataList)
            {
                ExternalResourceType resourceType = data.ExternalResourceType;

                // This message will be posted in a dialog box at the end of this method.
                String myMessage = String.Empty;

                ExternalResourceLoadContext loadContext        = data.GetLoadContext();
                ExternalResourceReference   desiredRef         = data.GetExternalResourceReference();
                ExternalResourceReference   currentlyLoadedRef = loadContext.GetCurrentlyLoadedReference();

                LoadOperationType loadType = loadContext.LoadOperationType;

                switch (loadType)
                {
                case LoadOperationType.Automatic:
                    myMessage = "This is an Automatic load operation. ";
                    break;

                case LoadOperationType.Explicit:
                    myMessage = "This is an Explicit load operation. ";
                    break;

                default:
                    myMessage = "There is no load type information!! ";
                    break;
                }


                bool bUnrecognizedStatus = false;
                if (data.LoadStatus == ExternalResourceLoadStatus.ResourceAlreadyCurrent)
                {
                    if (data.GetLoadContext().LoadOperationType == LoadOperationType.Explicit)
                    {
                        string resourcePath = currentlyLoadedRef.InSessionPath;
                        myMessage += "\n No new changes to load for link: " + resourcePath;
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (data.LoadStatus == ExternalResourceLoadStatus.Uninitialized)
                {
                    myMessage += "\n The load status is uninitialized - this generally shouldn't happen";
                }
                else if (data.LoadStatus == ExternalResourceLoadStatus.Failure)
                {
                    myMessage += "\n The load failed and the reason is unknown.";
                }
                else if (data.LoadStatus == ExternalResourceLoadStatus.Success)
                {
                    if (resourceType == ExternalResourceTypes.BuiltInExternalResourceTypes.KeynoteTable)
                    {
                        string resourcePath = data.GetExternalResourceReference().InSessionPath;
                        myMessage += "\n Version " + data.GetLoadContent().Version + " of keynote data \'" + resourcePath + "\' has been loaded successfully";
                    }
                    else if (resourceType == ExternalResourceTypes.BuiltInExternalResourceTypes.RevitLink)
                    {
                        string          resourcePath    = data.GetExternalResourceReference().InSessionPath;
                        LinkLoadContent ldrlc           = (LinkLoadContent)(data.GetLoadContent());
                        string          destinationPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(ldrlc.GetLinkDataPath());
                        myMessage += "\n Version " + data.GetLoadContent().Version +
                                     " of the file: " + resourcePath +
                                     " has been downloaded into the cached folder: " + destinationPath +
                                     " for this Revit Link.";
                    }
                }
                else
                {
                    myMessage          += "Unrecognized external resource load status.";
                    bUnrecognizedStatus = true;
                }


                if (!bUnrecognizedStatus && resourceType == ExternalResourceTypes.BuiltInExternalResourceTypes.RevitLink)
                {
                    // For Revit links, the UI server can also obtain a RevitLinkLoadResult which contains detailed
                    // information about the status of the attempt to load the local copy of the link into Revit.
                    LinkLoadContent     ldrlc      = (LinkLoadContent)(data.GetLoadContent());
                    RevitLinkLoadResult loadResult = ldrlc.GetLinkLoadResult();
                    if (loadResult != null)
                    {
                        myMessage += "\n LinkLoadResultType: " + loadResult.LoadResult.ToString("g");
                    }
                }
                System.Windows.Forms.MessageBox.Show(myMessage, "UI Server for SDK Sample External Resource Server");
            }
        }