public static object OpenDocumentFile(string filePath, bool audit = false, bool detachFromCentral = false, bool preserveWorksets = true, bool closeAllWorksets = false)
        {
            var uiapp = DocumentManager.Instance.CurrentUIApplication;
            var app   = uiapp.Application;
            //instantiate open options for user to pick to audit or not
            OpenOptions openOpts = new OpenOptions
            {
                Audit = audit,
                DetachFromCentralOption = detachFromCentral == false ? DetachFromCentralOption.DoNotDetach :
                                          preserveWorksets == true ? DetachFromCentralOption.DetachAndPreserveWorksets :
                                          DetachFromCentralOption.DetachAndDiscardWorksets
            };
            //TransmittedModelOptions tOpt = TransmittedModelOptions.SaveAsNewCentral;
            //option to close all worksets
            WorksetConfiguration worksetConfiguration = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets);

            if (closeAllWorksets)
            {
                worksetConfiguration = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
            }
            openOpts.SetOpenWorksetsConfiguration(worksetConfiguration);

            //convert string to model path for open
            ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);

            var document = app.OpenDocumentFile(modelPath, openOpts);

            return(document);
        }
Exemple #2
0
//    public void app_ClosingLinks(object sender, ProgressChangedEventArgs e)
//    {
//      if (RevitUpdater.Globals.data != null)
//      {
//        var openingLinksNames = new List<string>();
//        foreach (ModelPath modelPath in RevitUpdater.Globals.data)
//        {
//          var filePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(modelPath);
//          openingLinksNames.Add(Path.GetFileNameWithoutExtension(filePath));
//        }
//        // get document from event args
//        if (openingLinksNames.Any(file => e.Caption.Contains(file)) && e.LowerRange == e.Position)
//        {
//          if (e.Cancellable)
//          {
//            Debug.Write(e.Caption);
//
//            e.Cancel();
//          }
//        }
//      }
//    }


        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;

//            uiapp.Application.ProgressChanged += new EventHandler<ProgressChangedEventArgs>(app_ClosingLinks);
//            uiapp.Application.DocumentOpening += new EventHandler<DocumentOpeningEventArgs>(app_DocumentOpening);


            var modelPaths = GetModelPaths();

            if (modelPaths == null)
            {
                return(Result.Cancelled);
            }

            // Set open configuration all-in
            var openOpts = new OpenOptions();

            openOpts.SetOpenWorksetsConfiguration(new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets));

            var preDocument = uidoc;

            foreach (var modelPath in modelPaths)
            {
                app_ListOfLinks(modelPath);
                // ver 2 opendactivedocument
//            var openingUI = uiapp.OpenAndActivateDocument(modelPath, openOpts, false);
//            var openedDoc = openingUI.Document;
//
//            if (preDocument != null)
//            {
//              preDocument = openingUI;
//            }


                // ver 1 opendocumentfile
//            var openedDoc = app.OpenDocumentFile(modelPath, openOpts);
//            var trans = new Transaction(openedDoc, "kek");
//            trans.Start();
//            openedDoc.Regenerate();
//            trans.Commit();

//            SyncWithCentral(openedDoc);
//            openedDoc.Close(false);
            }

            //            CloseModelLinks(testModel);
            // Open and sync model
            //            var openedDoc = app.OpenDocumentFile(testModel, openOpts);

//                uiapp.Application.ProgressChanged -= app_ClosingLinks;
//      uiapp.Application.DocumentOpening -= app_DocumentOpening;

            return(Result.Succeeded);
        }
Exemple #3
0
        // In the example below, a document is opened with two worksets specified to be opened.
        // Note that the WorksharingUtils.GetUserWorksetInfo() method can be used to access workset
        // information from a closed Revit document.

        Document OpenDocumentWithWorksets(ModelPath projectPath)
        {
            Document doc = null;

            try {
                // Get info on all the user worksets in the project prior to opening
                IList <WorksetPreview> worksets   = WorksharingUtils.GetUserWorksetInfo(projectPath);
                IList <WorksetId>      worksetIds = new List <WorksetId>();
                // Find two predetermined worksets
                foreach (WorksetPreview worksetPrev in worksets)
                {
                    if (worksetPrev.Name.CompareTo("Workset1") == 0 ||
                        worksetPrev.Name.CompareTo("Workset2") == 0)
                    {
                        worksetIds.Add(worksetPrev.Id);
                    }
                }

                OpenOptions openOptions = new OpenOptions();
                // Setup config to close all worksets by default
                WorksetConfiguration openConfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
                // Set list of worksets for opening
                openConfig.Open(worksetIds);
                openOptions.SetOpenWorksetsConfiguration(openConfig);
                doc = _app.OpenDocumentFile(projectPath, openOptions);
            } catch (Exception e) {
                TaskDialog.Show("Open File Failed", e.Message);
            }

            return(doc);
        }
Exemple #4
0
        public UIDocument DoOpenNewLocalFromModelPath(ModelPath centralPath, ModelPath localPath)
        {
            List <WorksetId> worksetsToOpen = new List <WorksetId>();
            // First set to close all worksets
            WorksetConfiguration worksetConfig  = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
            OpenOptions          theOpenOptions = new OpenOptions();

            try {
                // Create the new local at the given path
                WorksharingUtils.CreateNewLocal(centralPath, localPath);
                // Select specific worksets to open
                // Get a list of worksets from the unopened document
                IList <WorksetPreview> worksets = WorksharingUtils.GetUserWorksetInfo(localPath);
                foreach (WorksetPreview preview in worksets)
                {
                    bool Include = true;
                    ////// The inverse list is the inverse of the worksets checked. In other
                    ////// words an exclusion list.
                    //////foreach (string ws in InverseWorksetList) {
                    //////    if (ws == "") { continue; }
                    //////    if (preview.Name.StartsWith(ws)) {
                    //////        Include = false;
                    //////        continue;
                    //////    } else {
                    //////    }
                    //////}
                    if (Include)
                    {
                        worksetsToOpen.Add(preview.Id);
                    }
                    else
                    {
                        //System.Windows.MessageBox.Show("Excluding " + preview.Name);
                    }
                }
                // Setup option to open the target worksets
                // then set specific ones to open
                worksetConfig.Open(worksetsToOpen);
                theOpenOptions.SetOpenWorksetsConfiguration(worksetConfig);
                // Now open the new local
                UIDocument openedDoc = _uiApp.OpenAndActivateDocument(localPath, theOpenOptions, false);
                return(openedDoc);
            } catch (Exception ex) {
                System.Windows.MessageBox.Show("Opening the file from its location.\n\n" + ex.Message, "This Is Not A Workshared File");
            }
            // If here then not a workshared file.
            string     fname      = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralPath);
            UIDocument openedDocN = _uiApp.OpenAndActivateDocument(fname);

            return(openedDocN);
        }
Exemple #5
0
        //Another option is to open the document while just opening the last viewed worksets.

        public Document OpenLastViewed()
        {
            // Setup options
            OpenOptions options1 = new OpenOptions();

            // Default config opens all.  Close all first, then open last viewed to get the correct settings.
            WorksetConfiguration worksetConfig = new WorksetConfiguration(WorksetConfigurationOption.OpenLastViewed);

            options1.SetOpenWorksetsConfiguration(worksetConfig);

            // Open the document
            Document openedDoc = _app.OpenDocumentFile(GetWSAPIModelPath("WorkaredFileSample.rvt"), options1);

            return(openedDoc);
        }
        public static void SetDocumentOpenOptions()
        {
            #region DocumentOptions (look into making this a separate item)
            // set options for typical document opening
            WorksetConfiguration wrkcon = new WorksetConfiguration();
            wrkcon.Close(
                new FilteredWorksetCollector(
                    _uiApplication.ActiveUIDocument.Document)
                .ToWorksetIds()
                .ToList());


            Document doc = _uiApplication.ActiveUIDocument.Document;
            //var list_elems = from
            //var worksetlist = doc.GetWorksetId()


            _openOptions.Audit = true;
            _openOptions.DetachFromCentralOption = DetachFromCentralOption.ClearTransmittedSaveAsNewCentral;
            _openOptions.SetOpenWorksetsConfiguration(wrkcon);
            #endregion
        }
Exemple #7
0
        public static Dictionary <string, object> openDocumentOption(bool audit = false, int detachFromCentralOption = 3)
        {
            string      message = "";
            OpenOptions openOpt = new OpenOptions();

            //Document doc = DocumentManager.Instance.CurrentDBDocument;
            //Document openedDoc = null;
            //UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
            //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            //UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument;

            //ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);
            try
            {
                openOpt.Audit = false;
                WorksetConfiguration workConf = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets);
                openOpt.SetOpenWorksetsConfiguration(workConf);
                switch (detachFromCentralOption)
                {
                case 0: openOpt.DetachFromCentralOption = DetachFromCentralOption.ClearTransmittedSaveAsNewCentral; break;

                case 1: openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets; break;

                case 2: openOpt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets; break;

                case 3: openOpt.DetachFromCentralOption = DetachFromCentralOption.DoNotDetach; break;
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return(new Dictionary <string, object>
            {
                { "openOption", openOpt },
            });
        }
        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);
        }
Exemple #9
0
        private void ProcessSelection(string selectedFilePathName)
        {
            string runningMsg;

            if (selectedFilePathName != null)
            {
                if ((bool)chkInfoOnly.IsChecked)
                {
                    try {
                        RevitFileSniffer rfs = new RevitFileSniffer(selectedFilePathName);
                        rfs.ReportRevitInfo();
                    } catch (Exception ex) {
                        string ms = "\n\nDo you must have this file open? The sniffer cannot snif if it's open.";
                        System.Windows.MessageBox.Show(ex.Message + ms, "Error At RevitFileSniffer");
                    }
                    return;
                }
                Hide();
                FormMsgWPF HUD        = new FormMsgWPF();
                string     FileToOpen = selectedFilePathName;
                try {
                    OpenOptions op = new OpenOptions();
                    op.SetOpenWorksetsConfiguration(null);  // makes all worksets opened?
                    op.DetachFromCentralOption = DetachFromCentralOption.DoNotDetach;
                    ModelPath mdlPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(FileToOpen);

                    string fName = System.IO.Path.GetFileNameWithoutExtension(FileToOpen);
                    string fext  = System.IO.Path.GetExtension(FileToOpen);

                    string UserInitials = Environment.UserName.ToString();
                    fName      = fName + "_" + UserInitials + fext;
                    runningMsg = selectedFilePathName + " for " + UserInitials;
                    HUD.SetMsg(runningMsg, "Processing for " + UserInitials);
                    HUD.Show();
                    string   source           = FileToOpen;
                    string[] stringSeparators = new string[] { "\\" };
                    var      result           = source.Split(stringSeparators, StringSplitOptions.None);

                    string    localPrjPath = string.Empty;
                    string    fullLFname   = string.Empty;
                    ModelPath localPath    = null;
                    try {
                        if (result.Length > 4)
                        {
                            localPrjPath = _locRevitRoot + "\\" + result[3] + "_" + UserInitials + "\\";
                            fullLFname   = localPrjPath + fName;
                            //MessageBox.Show(fullLFname, "First Pass Local Path");
                            localPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(fullLFname);
                        }
                        else
                        {
                            HUD.Close();
                            System.Windows.MessageBox.Show("Based on its location, the file selected does not look like a project file .\n\n" + FileToOpen, "Not Touching This Without A Ten Foot Pole");
                            Close();
                            return;
                        }

                        #region Check For Open Document
                        DocumentSet ds = _uiapp.Application.Documents;
                        foreach (Document d in ds)
                        {
                            String dF = d.PathName.Replace(@"\\SYSFILE\CADD", "J:");
                            if (fullLFname.ToUpper().Equals(dF.ToUpper()))
                            {
                                string msg = "You have " + selectedFilePathName + " already open";
                                msg = msg + " or it is linked to a file you have open. Either way";
                                msg = msg + " Revit will not let you open it until the other one is unloaded.";
                                System.Windows.MessageBox.Show(msg, "Sorry, You Cannot Open The File");
                                HUD.Close();
                                Close();
                                return;
                            }
                        }
                        #endregion

                        if (!Directory.Exists(localPrjPath))
                        {
                            try {
                                runningMsg = runningMsg + "\n\nCreated Local Folder: " + localPrjPath;
                                HUD.SetMsg(runningMsg, "Creating This Local Folder");
                                Directory.CreateDirectory(localPrjPath);
                            } catch (Exception ex) {
                                HUD.Close();
                                System.Windows.MessageBox.Show(localPrjPath + "\n\n" + ex.Message, "Error Creating Directory");
                                Close();
                                return;
                            }
                        }
                        else
                        {
                            runningMsg = runningMsg + "\n\nUsing Local Folder: " + localPrjPath;
                            HUD.SetMsg(runningMsg, "Using This Local Folder");
                        }
                    } catch (Exception) {
                        HUD.Close();
                        System.Windows.MessageBox.Show("Error: Did Not Create " + localPrjPath, "Debug");
                        Close();
                        return;
                    }

                    #region Handle any existing local file
                    if (File.Exists(fullLFname))
                    {
                        string StashFolder = localPrjPath + "PriorsStash\\";
                        runningMsg = runningMsg + "\n\nStashing Older Local File To: " + StashFolder;
                        HUD.SetMsg(runningMsg, "Stashing Older Local File To");
                        if (!Directory.Exists(StashFolder))
                        {
                            try {
                                Directory.CreateDirectory(StashFolder);
                            } catch (Exception ex) {
                                HUD.Close();
                                System.Windows.MessageBox.Show(StashFolder + "\n\n" + ex.Message, "Error Creating Directory");
                                Close();
                                return;
                            }
                        }
                        string OrgFNameWOExt = System.IO.Path.GetFileNameWithoutExtension(fullLFname);
                        string ext           = System.IO.Path.GetExtension(fullLFname);
                        string NewFNameWExt  = AssignNewUniqueFileName(StashFolder + OrgFNameWOExt + ext);
                        try {
                            File.Move(fullLFname, NewFNameWExt);
                            int qtyDeleted = LimitNumberOfStashedFiles(StashFolder + OrgFNameWOExt + ext, stashMax);
                            if (qtyDeleted > 0)
                            {
                                runningMsg = runningMsg + "\n\nTrashed " + qtyDeleted.ToString() + " stashed older file" + pluralOrNot(qtyDeleted) + " from the PriorsStash folder.";
                            }
                        } catch (Exception ex) {
                            HUD.Close();
                            System.Windows.MessageBox.Show(fullLFname + "\nto\n" + NewFNameWExt + "\n\n" + ex.Message, "File Error Moving File");
                            Close();
                            return;
                        }
                        string backupFldr = localPrjPath + OrgFNameWOExt + "_backup";
                        if (Directory.Exists(backupFldr))
                        {
                            try {
                                runningMsg = runningMsg + "\n\nTrashing Older Backup Folder: " + backupFldr;
                                HUD.SetMsg(runningMsg, "Trashing Older Backup Folder");
                                Directory.Delete(backupFldr, true);
                            } catch (Exception ex) {
                                HUD.Close();
                                System.Windows.MessageBox.Show(backupFldr + "\n\n" + ex.Message, "Error Deleting Backup Folder");
                                Close();
                                return;
                            }
                        }
                    }
                    #endregion

                    runningMsg = runningMsg + "\n\nLocal Document Is: " + fullLFname;
                    /////runningMsg = runningMsg + "\n\n" + ExcludeTheseMsg();
                    HUD.SetMsg(runningMsg, "Revit Is Opening This Document For " + UserInitials);
                    HUD.UpdateLayout();
                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
                    HUD.Close();
                    SetStatusBarText(_revitHandle, "Just guessing that maybe you actually think something is happening.");

                    #region Finally Create and Open
                    Autodesk.Revit.UI.UIDocument newUIDoc = null;

                    if (mdlPath != null || localPath != null)
                    {
                        AKSOpenUtils AKSOpen = new AKSOpenUtils(_uiapp, revVersion);
                        // MessageBox.Show(fullLFname, "Will OpenNewLocalFromModelPath");
                        PokeRevit();
                        newUIDoc = AKSOpen.DoOpenNewLocalFromModelPath(mdlPath, localPath);
                    }
                    #endregion
                    adWin.ComponentManager.Ribbon.Visibility = System.Windows.Visibility.Visible;
                } catch (Exception ex) {
                    HUD.Close();
                    System.Windows.MessageBox.Show(ex.Message + " | " + ex.InnerException.Message, "Where is this Bummer");
                    Close();
                    return;
                }

                UpDateRecentsList(FileToOpen);

                Close();
            }
        }
Exemple #10
0
 public Result Execute(UIApplication app)
 {
     if (ModuleData.up_send_enter)
     {
         Thread thread = new Thread(() =>
         {
             var autoEvent = new AutoResetEvent(true);
             _Timer        = new System.Threading.Timer(UiInput.KeyEnter, autoEvent, 20000, 20000);
         });
         thread.Start();
     }
     try
     {
         string assemblyPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
         Print(string.Format("[{0}] Запуск...", DateTime.Now.ToString("T")), KPLN_Loader.Preferences.MessageType.Header);
         ModuleData.AutoConfirmEnabled = true;
         if (app.Application.Documents.IsEmpty)
         {
             Print("Создание [placeholder] документа...", KPLN_Loader.Preferences.MessageType.Regular);
             app.Application.NewProjectDocument(UnitSystem.Metric);
         }
         int max  = Documents.Count;
         int step = 0;
         foreach (DbDocument doc in Documents)
         {
             step++;
             string step_info = string.Format("[{0}/{1}]", step.ToString(), max.ToString());
             try
             {
                 Print(string.Format("[{0}] Открытие {1}...", DateTime.Now.ToString("T"), doc.Path), KPLN_Loader.Preferences.MessageType.Header);
                 ModelPath   path    = ModelPathUtils.ConvertUserVisiblePathToModelPath(doc.Path);
                 OpenOptions options = new OpenOptions()
                 {
                     DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets, Audit = false
                 };
                 WorksetConfiguration config = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets);
                 options.SetOpenWorksetsConfiguration(config);
                 Document docu = app.Application.OpenDocumentFile(path, options);
                 try
                 {
                     DbRowData rowData = new DbRowData();
                     rowData.Errors.Add(new DbError("Ошибка привязки к уровню", CheckTools.CheckLevels(docu)));
                     rowData.Errors.Add(new DbError("Зеркальные элементы", CheckTools.CheckMirrored(docu)));
                     rowData.Errors.Add(new DbError("Ошибка мониторинга осей", CheckTools.CheckMonitorGrids(docu)));
                     rowData.Errors.Add(new DbError("Ошибка мониторинга уровней", CheckTools.CheckMonitorLevels(docu)));
                     rowData.Errors.Add(new DbError("Дубликаты имен", CheckTools.CheckNames(docu)));
                     rowData.Errors.Add(new DbError("Ошибки подгруженных связей", CheckTools.CheckSharedLocations(docu) + CheckTools.CheckLinkWorkSets(docu)));
                     rowData.Errors.Add(new DbError("Предупреждения Revit", CheckTools.CheckErrors(docu)));
                     rowData.Errors.Add(new DbError("Размер файла", CheckTools.CheckFileSize(doc.Path)));
                     rowData.Errors.Add(new DbError("Элементы в наборах подгруженных связей", CheckTools.CheckElementsWorksets(docu)));
                     DbController.WriteValue(doc.Id.ToString(), rowData.ToString());
                     Print(string.Format("[{0}] Закрытие документа...", DateTime.Now.ToString("T")), KPLN_Loader.Preferences.MessageType.Header);
                 }
                 catch (Exception e)
                 {
                     PrintError(e);
                 }
                 docu.Close(false);
             }
             catch (Exception e)
             {
                 PrintError(e);
             }
         }
         ModuleData.AutoConfirmEnabled = false;
         _Timer.Dispose();
         return(Result.Succeeded);
     }
     catch (Exception e)
     {
         ModuleData.AutoConfirmEnabled = false;
         PrintError(e);
         _Timer.Dispose();
         return(Result.Failed);
     }
 }
Exemple #11
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;

            WorksetConfiguration openConfig  = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
            OpenOptions          openOptions = new OpenOptions();

            openOptions.SetOpenWorksetsConfiguration(openConfig);
            openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;

            SaveAsOptions            wsaveAs    = new SaveAsOptions();
            WorksharingSaveAsOptions saveConfig = new WorksharingSaveAsOptions();

            saveConfig.SaveAsCentral = true;
            wsaveAs.SetWorksharingOptions(saveConfig);
            wsaveAs.OverwriteExistingFile = true;

            SaveAsOptions saveAs = new SaveAsOptions();

            saveAs.OverwriteExistingFile = true;

            destinationpath = "";
            documents.Clear();

            string date = DateTime.Now.ToString("dd/MM/yyyy");

            int completed = 0;

            int failed = 0;

            var exportdialog = new RevitBatchExporter.Dialogs.ExportDialog();

            var dialog = exportdialog.ShowDialog();

            if (dialog != DialogResult.OK)
            {
                return(Result.Cancelled);
            }

            bool purge = exportdialog.PurgeCheckBox.Checked;

            bool removeCADlinks = exportdialog.RemoveCADLinksCheckBox.Checked;

            bool removeCADImports = exportdialog.RemoveCADImportsCheckBox.Checked;

            bool removeRVTlinks = exportdialog.RemoveRVTLinksCheckBox.Checked;

            bool removeSchedules = exportdialog.SchedulesCheckBox.Checked;

            bool ungroup = exportdialog.UngroupCheckBox.Checked;

            bool removesheets = exportdialog.SheetsCheckBox.Checked;

            bool removeviewsON = exportdialog.ViewsONSheetsCheckBox.Checked;

            bool removeviewsNOT = exportdialog.ViewsNotSheetsCheckBox.Checked;

            bool exportnwc = exportdialog.NWCCheckBox.Checked;

            bool exportifc = exportdialog.IFCCheckBox.Checked;

            bool removeallsheetsviews = false;

            if (removesheets && removeviewsON && removeviewsNOT)
            {
                removeallsheetsviews = true;
                removesheets         = false;
                removeviewsON        = false;
                removeviewsNOT       = false;
            }

            string reason = exportdialog.IssueReasonTextBox.Text.TrimEnd().TrimStart();

            string customdate = exportdialog.DateTextBox.Text.TrimEnd().TrimStart();

            string nameprefix = exportdialog.PrefixTextBox.Text.TrimEnd().TrimStart();

            string namesuffix = exportdialog.SuffixTextBox.Text.TrimEnd().TrimStart();

            string debugmessage = "";

            bool samepath = false;

            List <string[]> results = new List <string[]>();

            foreach (string path in documents)
            {
                string destdoc = nameprefix + Path.GetFileName(path.Replace(".rvt", "")) + namesuffix + ".rvt";

                if (File.Exists(destinationpath + destdoc))
                {
                    samepath = true;
                    break;
                }

                string pathOnly = Path.GetDirectoryName(path) + "\\";

                if (pathOnly == destinationpath)
                {
                    samepath = true;
                    break;
                }
            }

            if (samepath)
            {
                TaskDialog td = new TaskDialog("XPORT");
                td.MainInstruction = "Some documents already exist in the destination path.";
                td.MainContent     = "The files will be overritten, do you wish to continue?";

                td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Continue");
                td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel");

                switch (td.Show())
                {
                case TaskDialogResult.CommandLink1:
                    break;

                case TaskDialogResult.CommandLink2:
                    return(Result.Cancelled);

                default:
                    return(Result.Cancelled);
                }
            }

            uiapp.DialogBoxShowing += new EventHandler <DialogBoxShowingEventArgs>(OnDialogBoxShowing);
            uiapp.Application.FailuresProcessing += FailureProcessor;

            DateTime start = DateTime.Now;

            foreach (string path in documents)
            {
                string[] result = new string[5];

                if (!File.Exists(path))
                {
                    result[0] = Path.GetFileName(path.Replace(".rvt", ""));
                    result[1] = "false";
                    result[2] = "false";
                    result[3] = "File Not Found";
                    result[4] = "";
                    results.Add(result);
                    failed++;
                    continue;
                }

                try
                {
                    DateTime s1 = DateTime.Now;

                    Document doc = uiapp.Application.OpenDocumentFile(ModelPathUtils.ConvertUserVisiblePathToModelPath(path), openOptions);

                    Transaction t1 = new Transaction(doc, "XP");

                    t1.Start();

                    if (customdate != "")
                    {
                        date = customdate;
                    }

                    try
                    {
                        doc.ProjectInformation.LookupParameter("Model Issue Date").Set(date);
                    }
                    catch { };

                    try
                    {
                        doc.ProjectInformation.IssueDate = date;
                    }
                    catch { };

                    if (reason != "")
                    {
                        try
                        {
                            doc.ProjectInformation.LookupParameter("Model Issue Reason").Set(reason);
                        }
                        catch { }
                    }

                    if (removeCADlinks)
                    {
                        DeleteCADLinks(doc);
                    }
                    if (removeCADImports)
                    {
                        DeleteCADImports(doc);
                    }
                    if (removeRVTlinks)
                    {
                        DeleteRVTLinks(doc);
                    }
                    if (removeviewsNOT)
                    {
                        DeleteViewsNotOnSheets(doc);
                    }
                    if (removeviewsON)
                    {
                        DeleteViewsONSheets(doc);
                    }
                    if (removesheets)
                    {
                        DeleteSheets(doc);
                    }
                    if (removeallsheetsviews)
                    {
                        DeleteAllViewsSheets(doc);
                    }
                    if (removeSchedules)
                    {
                        DeleteSchedules(doc);
                    }
                    if (ungroup)
                    {
                        UngroupGroups(doc);
                    }
                    if (purge)
                    {
                        PurgeDocument(doc);
                    }

                    t1.Commit();

                    string docname = doc.Title;

                    docname = docname.Replace("_detached", "");

                    if (docname.EndsWith(".rvt"))
                    {
                        docname = docname.Replace(".rvt", "");
                    }

                    if (nameprefix != "")
                    {
                        docname = nameprefix + docname;
                    }

                    if (namesuffix != "")
                    {
                        docname = docname + namesuffix;
                    }

                    bool nwcexported = false;

                    bool ifcexported = false;

                    if (exportnwc)
                    {
                        nwcexported = ExportNWC(doc, destinationpath, docname);
                    }
                    if (exportifc)
                    {
                        ifcexported = ExportIFC(doc, destinationpath, docname);
                    }

                    try
                    {
                        if (doc.IsWorkshared)
                        {
                            doc.SaveAs(destinationpath + docname + ".rvt", wsaveAs);
                            doc.Close(false);
                        }
                        else
                        {
                            doc.SaveAs(destinationpath + docname + ".rvt", saveAs);
                            doc.Close(false);
                        }
                    }
                    catch { doc.Close(false); }

                    try
                    {
                        Directory.Delete(destinationpath + docname + "_backup", true);
                    }
                    catch { }

                    try
                    {
                        Directory.Delete(destinationpath + "Revit_temp", true);
                    }
                    catch { }

                    doc.Dispose();
                    completed++;

                    DateTime e1 = DateTime.Now;

                    int h = (e1 - s1).Hours;

                    int m = (e1 - s1).Minutes;

                    int s = (e1 - s1).Seconds;


                    result[0] = Path.GetFileName(path.Replace(".rvt", ""));
                    result[1] = nwcexported.ToString();
                    result[2] = ifcexported.ToString();
                    result[3] = "Completed";
                    result[4] = h.ToString() + ":" + m.ToString() + ":" + s.ToString();

                    results.Add(result);
                }
                catch (Exception e)
                {
                    debugmessage = "\n" + "\n" + e.Message;
                    result[0]    = Path.GetFileName(path.Replace(".rvt", ""));
                    result[1]    = "false";
                    result[2]    = "false";
                    result[3]    = "Failed";
                    result[4]    = "";

                    results.Add(result);
                    failed++;
                }
            }

            uiapp.DialogBoxShowing -= OnDialogBoxShowing;
            uiapp.Application.FailuresProcessing -= FailureProcessor;

            DateTime end = DateTime.Now;

            int hours = (end - start).Hours;

            int minutes = (end - start).Minutes;

            int seconds = (end - start).Seconds;

            //TaskDialog.Show("Results", "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s" + debugmessage);

            TaskDialog rd = new TaskDialog("XPORT");

            rd.MainInstruction = "Results";
            rd.MainContent     = "Exported to: " + destinationpath + "\n" + "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s";

            rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Close");
            rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Show Details");

            documents.Clear();

            destinationpath = "";

            switch (rd.Show())
            {
            case TaskDialogResult.CommandLink1:
                return(Result.Succeeded);

            case TaskDialogResult.CommandLink2:

                var resultsdialog = new RevitBatchExporter.Dialogs.ResultsDialog();

                foreach (string[] r in results)
                {
                    var item = new ListViewItem(r);
                    resultsdialog.ResultsView.Items.Add(item);
                }

                var rdialog = resultsdialog.ShowDialog();

                return(Result.Succeeded);

            default:
                return(Result.Succeeded);
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;

            DestinationPath = string.Empty;
            Documents       = new List <string>();
            Splash          = string.Empty;
            Errors          = new List <string[]>();

            string date = DateTime.Now.ToString("dd/MM/yyyy");

            int completed = 0;

            int failed = 0;

            ExportDialog exportdialog = new ExportDialog();

            System.Windows.Forms.DialogResult dialog = exportdialog.ShowDialog();

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

            WorksetConfiguration openconfig  = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
            OpenOptions          openoptions = new OpenOptions();

            openoptions.SetOpenWorksetsConfiguration(openconfig);
            if (exportdialog.DiscardRadioButton.Checked)
            {
                openoptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets;
            }
            else
            {
                openoptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
            }

            SaveAsOptions            worksharedsaveas = new SaveAsOptions();
            WorksharingSaveAsOptions saveConfig       = new WorksharingSaveAsOptions
            {
                SaveAsCentral = true
            };

            worksharedsaveas.SetWorksharingOptions(saveConfig);
            worksharedsaveas.OverwriteExistingFile = true;

            SaveAsOptions regularsaveas = new SaveAsOptions
            {
                OverwriteExistingFile = true
            };

            if (exportdialog.AuditCheckBox.Checked)
            {
                openoptions.Audit = true;
            }

            if (exportdialog.SafeNameTextbox.Text.Trim() != string.Empty)
            {
                Splash = exportdialog.SafeNameTextbox.Text.Trim();
            }

            string customdate = exportdialog.DateTimePickerIssue.Value.ToString("yyyy/MM/dd");

            string nameprefix = exportdialog.PrefixTextBox.Text.Trim();

            string namesuffix = exportdialog.SuffixTextBox.Text.Trim();

            bool samepath = false;

            List <string[]> results = new List <string[]>();

            foreach (string path in Documents)
            {
                string destdoc = nameprefix + Path.GetFileNameWithoutExtension(path) + namesuffix + ".rvt";

                if (File.Exists(DestinationPath + destdoc))
                {
                    samepath = true;
                    break;
                }

                string pathonly = Path.GetDirectoryName(path) + "\\";

                if (pathonly == DestinationPath)
                {
                    samepath = true;
                    break;
                }
            }

            if (samepath)
            {
                TaskDialog td = new TaskDialog("Export")
                {
                    MainInstruction = "Some documents already exist in the destination path.",
                    MainContent     = "The files will be overritten, do you wish to continue?"
                };

                td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Continue");
                td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel");

                switch (td.Show())
                {
                case TaskDialogResult.CommandLink1:
                    break;

                case TaskDialogResult.CommandLink2:
                    return(Result.Cancelled);

                default:
                    return(Result.Cancelled);
                }
            }

            uiapp.DialogBoxShowing += new EventHandler <DialogBoxShowingEventArgs>(OnDialogBoxShowing);
            uiapp.Application.FailuresProcessing += FailureProcessor;

            DateTime start = DateTime.Now;

            foreach (string path in Documents)
            {
                string[] result        = new string[6];
                string   resultmessage = string.Empty;

                if (!File.Exists(path))
                {
                    result[0] = Path.GetFileName(path);
                    result[1] = "File Not Found";
                    result[2] = string.Empty;
                    results.Add(result);
                    failed++;
                    continue;
                }

                DateTime s1 = DateTime.Now;

                Document doc = null;

                //try
                //{
                doc = uiapp.Application.OpenDocumentFile(ModelPathUtils.ConvertUserVisiblePathToModelPath(path), openoptions);

                string docname = nameprefix + Path.GetFileNameWithoutExtension(path) + namesuffix;

                using (Transaction t = new Transaction(doc, "Export"))
                {
                    t.Start();

                    if (exportdialog.AutoCheckBox.Checked)
                    {
                        doc.ProjectInformation.IssueDate = date;
                    }
                    else
                    {
                        doc.ProjectInformation.IssueDate = customdate;
                    }

                    if (exportdialog.RemoveCADLinksCheckBox.Checked)
                    {
                        DeleteCADLinks(doc);
                    }
                    if (exportdialog.RemoveCADImportsCheckBox.Checked)
                    {
                        DeleteCADImports(doc);
                    }
                    if (exportdialog.RemoveRVTLinksCheckBox.Checked)
                    {
                        DeleteRVTLinks(doc);
                    }
                    DeleteViewsAndSheets(doc, exportdialog.ViewsONSheetsCheckBox.Checked, exportdialog.ViewsNOTSheetsCheckBox.Checked, exportdialog.SheetsCheckBox.Checked, exportdialog.TemplatesCheckBox.Checked);
                    if (exportdialog.RemoveSchedulesCheckBox.Checked)
                    {
                        DeleteSchedules(doc);
                    }
                    if (exportdialog.UngroupCheckBox.Checked)
                    {
                        UngroupGroups(doc);
                    }
                    if (exportdialog.PurgeCheckBox.Checked)
                    {
                        PurgeDocument(doc);
                    }

                    t.Commit();
                }


                if (doc.IsWorkshared)
                {
                    doc.SaveAs(DestinationPath + docname + ".rvt", worksharedsaveas);
                }
                else
                {
                    doc.SaveAs(DestinationPath + docname + ".rvt", regularsaveas);
                }

                doc.Close(false);

                string backupfolder = DestinationPath + docname + "_backup";
                string tempfolder   = DestinationPath + "Revit_temp";

                if (Directory.Exists(backupfolder))
                {
                    Directory.Delete(backupfolder, true);
                }
                if (Directory.Exists(tempfolder))
                {
                    Directory.Delete(tempfolder, true);
                }

                resultmessage = "Completed";
                completed++;
                //}
                // catch (Exception e)
                //{
                //    try
                //    {
                //        doc.Close(false);
                //    }
                //    catch { }

                //    resultmessage = e.Message;
                //    failed++;
                //}

                DateTime e1 = DateTime.Now;

                int h = (e1 - s1).Hours;
                int m = (e1 - s1).Minutes;
                int s = (e1 - s1).Seconds;

                result[0] = Path.GetFileName(path);
                result[1] = resultmessage;
                result[2] = h.ToString() + ":" + m.ToString() + ":" + s.ToString();
                results.Add(result);
            }

            uiapp.DialogBoxShowing -= OnDialogBoxShowing;
            uiapp.Application.FailuresProcessing -= FailureProcessor;

            DateTime end = DateTime.Now;

            int hours = (end - start).Hours;

            int minutes = (end - start).Minutes;

            int seconds = (end - start).Seconds;

            TaskDialog rd = new TaskDialog("Export")
            {
                MainInstruction = "Results",
                MainContent     = "Exported to: " + DestinationPath + "\n" + "Completed: " + completed.ToString() + "\nFailed: " + failed.ToString() + "\nTotal Time: " + hours.ToString() + " h " + minutes.ToString() + " m " + seconds.ToString() + " s"
            };

            rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Close");
            rd.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Show Details");

            switch (rd.Show())
            {
            case TaskDialogResult.CommandLink1:
                return(Result.Succeeded);

            case TaskDialogResult.CommandLink2:

                ResultsDialog resultsdialog = new ResultsDialog();

                foreach (string[] r in results)
                {
                    var item = new System.Windows.Forms.ListViewItem(r);
                    resultsdialog.ResultsView.Items.Add(item);
                }

                var rdialog = resultsdialog.ShowDialog();

                return(Result.Succeeded);

            default:
                return(Result.Succeeded);
            }
        }
        public Document OpenRevitDocument(string revitFileName)
        {
            Document doc = null;

            try
            {
                LogFileManager.AppendLog("Open Revit Document: " + revitFileName);
                BasicFileInfo   basicFileInfo   = BasicFileInfo.Extract(revitFileName);
                FileOpenOptions fileOpenOptions = projectSettings.UpgradeOptions.UpgradeVersionOpenOptions;

                if (basicFileInfo.IsWorkshared)
                {
                    ModelPath   modelPath   = ModelPathUtils.ConvertUserVisiblePathToModelPath(revitFileName);
                    OpenOptions openOptions = new OpenOptions();
                    openOptions.Audit = fileOpenOptions.Audit;
                    if (fileOpenOptions.DetachAndPreserveWorksets)
                    {
                        openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
                    }

                    IList <WorksetPreview> wsPreviews      = new List <WorksetPreview>();
                    IList <WorksetId>      worksetIds      = new List <WorksetId>();
                    WorksetConfiguration   wsConfiguration = new WorksetConfiguration();

                    try
                    {
                        wsPreviews = WorksharingUtils.GetUserWorksetInfo(modelPath);
                        if (wsPreviews.Count > 0)
                        {
                            foreach (WorksetPreview wsPreview in wsPreviews)
                            {
                                worksetIds.Add(wsPreview.Id);
                            }

                            if (fileOpenOptions.OpenAllWorkset)
                            {
                                wsConfiguration.Open(worksetIds);
                            }
                            else
                            {
                                wsConfiguration.Close(worksetIds);
                            }
                            openOptions.SetOpenWorksetsConfiguration(wsConfiguration);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogFileManager.AppendLog("[Warning] Open Worksets", ex.Message);
                    }
                    doc = uiApp.Application.OpenDocumentFile(modelPath, openOptions);
                }
                else
                {
                    doc = uiApp.Application.OpenDocumentFile(revitFileName);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogFileManager.AppendLog("[Error] Open Revit Document", message);
            }
            return(doc);
        }