Example #1
0
//    public void ReadAllFiles(string directory)
//    {
//        var fileNames = Directory.GetFiles(directory);
//        List<string> datedNames = new List<string>;

//    }
//    public string ReadDate(string filename)
//        {
//        if (filename.Length > 8)
//            {
//                var dateTest = filename.Substring(0,8);
//            }
//        if (int.TryParse(dateTest, out fileDate))
//            {
//               return DateTime.ParseExact(dateStub, "yyyyMMdd", null);
//            }
//        else { return DateTime.Today;}
//    }

    public Result Execute(
        ExternalCommandData commandData,
        ref string message,
        ElementSet elements)
    {
        Autodesk.Revit.UI.UIApplication m_app;
        m_app = commandData.Application;
        Autodesk.Revit.ApplicationServices.Application app = m_app.Application;

        // Check worksharing mode of each document
        // Open Revit projects
        OpenFileDialog theDialogRevit = new OpenFileDialog();

        theDialogRevit.Title            = "Select Revit Project Files";
        theDialogRevit.Filter           = "RVT files|*.rvt";
        theDialogRevit.FilterIndex      = 1;
        theDialogRevit.InitialDirectory = @"D:\";
        theDialogRevit.Multiselect      = true;

        if (theDialogRevit.ShowDialog() == DialogResult.OK)
        {
            DateTime            todaysDate           = DateTime.Today;
            string              dateStamp            = string.Format("{0}", todaysDate.ToString("yyyyMMdd"));
            string              mpath                = "";
            string              mpathOnlyFilename    = "";
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            string              currentFolder        = Path.GetDirectoryName(theDialogRevit.FileName);


            folderBrowserDialog1.Description = "Select Folder Where Revit Projects to be Saved in Local";
            //folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialog1.SelectedPath = currentFolder;

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                mpath = folderBrowserDialog1.SelectedPath;
                foreach (String projectPath in theDialogRevit.FileNames)
                {
                    // convert input string to directory info.
                    FileInfo  filePath = new FileInfo(projectPath);
                    ModelPath mp       = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName);

                    OpenOptions opt = new OpenOptions();
                    opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
                    mpathOnlyFilename           = string.Format("{0}_{1}", dateStamp, filePath.Name);
                    Document                 openedDoc = app.OpenDocumentFile(mp, opt);
                    SaveAsOptions            options   = new SaveAsOptions();
                    WorksharingSaveAsOptions wsOptions = new WorksharingSaveAsOptions();
                    options.OverwriteExistingFile = true;
                    wsOptions.SaveAsCentral       = true;
                    options.SetWorksharingOptions(wsOptions);
                    ModelPath modelPathout = ModelPathUtils.ConvertUserVisiblePathToModelPath(mpath + "\\" + mpathOnlyFilename);
                    openedDoc.SaveAs(modelPathout, options);
                    openedDoc.Close(false);
                }
            }

            // Scan backup folder and retrieve date prefixes
            //List<string> filesToDelete =  ReadAllFiles(mpath);
        }
        return(Result.Succeeded);
    }
Example #2
0
        public bool IsCentralFile(Document document)
        {
            var isCentralFile = false;

            try
            {
                var centralModelPath = document.GetWorksharingCentralModelPath();
                if (null != centralModelPath)
                {
                    var userVisiblePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralModelPath);
                    if (centralModelPath.ServerPath)
                    {
                        const string revitServerPrefix = "RSN://";
                        const string a360Prefix        = "A360://";
                        var          relativePath      = "";

                        if (userVisiblePath.Contains(revitServerPrefix))
                        {
                            var serverLocation = revitServerPrefix + centralModelPath.CentralServerPath;
                            relativePath = userVisiblePath.Substring(serverLocation.Length);
                        }
                        else if (userVisiblePath.Contains(a360Prefix))
                        {
                            var serverLocation = a360Prefix + centralModelPath.CentralServerPath;
                            relativePath = userVisiblePath.Substring(serverLocation.Length);
                        }

                        var serverPath  = new ServerPath(centralModelPath.CentralServerPath, relativePath);
                        var centralGUID = document.Application.GetWorksharingCentralGUID(serverPath);
                        if (centralGUID != Guid.Empty)
                        {
                            var currentModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(document.PathName);
                            if (null != currentModelPath)
                            {
                                var currentGuid = currentModelPath.GetModelGUID();
                                if (currentGuid != Guid.Empty)
                                {
                                    if (centralGUID.Equals(currentGuid))
                                    {
                                        isCentralFile = true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (document.PathName.ToUpper() == userVisiblePath.ToUpper())
                        {
                            isCentralFile = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
                MessageBox.Show("Failed to determine whether the file is central or local.\n" + ex.Message, "IsCentralFile", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(isCentralFile);
        }
        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; // 2017
                LinkLoadResult res = null; // 2018

                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
        }
Example #4
0
        protected void UpgradeFile(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }

            BasicFileInfo fileInfo = BasicFileInfo.Extract(modelPath);

            if (fileInfo.Format.Equals("2019"))
            {
                return;
            }

            string pathName = doc.PathName;

            string[]  pathParts = pathName.Split('\\');
            string[]  nameParts = pathParts[pathParts.Length - 1].Split('.');
            string    extension = nameParts[nameParts.Length - 1];
            string    filePath  = "revitupgrade." + extension;
            ModelPath path      = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);

            SaveAsOptions saveOpts = new SaveAsOptions();

            // Check for permanent preview view
            if (doc
                .GetDocumentPreviewSettings()
                .PreviewViewId
                .Equals(ElementId.InvalidElementId))
            {
                // use 3D view as preview
                View view = new FilteredElementCollector(doc)
                            .OfClass(typeof(View))
                            .Cast <View>()
                            .Where(vw =>
                                   vw.ViewType == ViewType.ThreeD && !vw.IsTemplate
                                   )
                            .FirstOrDefault();

                if (view != null)
                {
                    saveOpts.PreviewViewId = view.Id;
                }
            }
            doc.SaveAs(path, saveOpts);
        }
Example #5
0
        Stream(ArrayList data, Document doc)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(Document)));

            data.Add(new Snoop.Data.Object("Application", doc.Application));
            data.Add(new Snoop.Data.String("Title", doc.Title));
            data.Add(new Snoop.Data.String("Pathname", doc.PathName));
            data.Add(new Snoop.Data.Object("Settings", doc.Settings));
            if (!doc.IsFamilyDocument)
            {
                data.Add(new Snoop.Data.BindingMap("Parameter bindings", doc.ParameterBindings));
            }
            data.Add(new Snoop.Data.Enumerable("Phases", doc.Phases));
            data.Add(new Snoop.Data.Bool("Reactions are up to date", doc.ReactionsAreUpToDate));
            data.Add(new Snoop.Data.Object("Active View", doc.ActiveView));
            data.Add(new Snoop.Data.String("Display unit system", doc.DisplayUnitSystem.ToString()));
            data.Add(new Snoop.Data.Object("Active project location", doc.ActiveProjectLocation));
            data.Add(new Snoop.Data.Object("Project information", doc.ProjectInformation));
            data.Add(new Snoop.Data.Enumerable("Project locations", doc.ProjectLocations));
            data.Add(new Snoop.Data.Object("Site location", doc.SiteLocation));
            data.Add(new Snoop.Data.Object("Project unit", doc.GetUnits()));
            try
            {
                Transaction t = new Transaction(doc);
                t.SetName("PlanTopologies");
                t.Start();
                data.Add(new Snoop.Data.Enumerable("Plan topologies", doc.PlanTopologies));
                t.RollBack();
            }
            catch (Autodesk.Revit.Exceptions.ArgumentException)
            {
                //catch exception caused because of inability to create transaction for linked document
            }
            ElementSet elemSet1                    = new ElementSet();
            FilteredElementCollector fec           = new FilteredElementCollector(doc);
            ElementClassFilter       wallFilter    = new ElementClassFilter(typeof(Wall));
            ElementClassFilter       notWallFilter = new ElementClassFilter(typeof(Wall), true);
            LogicalOrFilter          orFilter      = new LogicalOrFilter(wallFilter, notWallFilter);

            fec.WherePasses(orFilter);
            List <Element> elements = fec.ToElements() as List <Element>;

            foreach (Element element in elements)
            {
                elemSet1.Insert(element);
            }

            data.Add(new Snoop.Data.ElementSet("Elements", elemSet1));

            data.Add(new Snoop.Data.Bool("Is modified", doc.IsModified));
            data.Add(new Snoop.Data.Bool("Is workshared", doc.IsWorkshared));

            data.Add(new Snoop.Data.Bool("Is A Family Document", doc.IsFamilyDocument));
            if (doc.IsFamilyDocument)
            {
                data.Add(new Snoop.Data.Object("Family Manager", doc.FamilyManager));
                data.Add(new Snoop.Data.Object("Owner Family", doc.OwnerFamily));
            }

            if (doc.GetWorksharingCentralModelPath() != null)
            {
                ModelPath mp = doc.GetWorksharingCentralModelPath();
                string    userVisiblePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(mp);
                data.Add(new Snoop.Data.String("Worksharing central model path", userVisiblePath));
                if ((mp.ServerPath))
                {
                    try
                    {
                        // this is a bit weird, the ModelPath is in an abstract format, we must re-make as a ServerPath
                        string     prefix             = "RSN://" + mp.CentralServerPath;
                        string     serverRelativePath = userVisiblePath.Substring(prefix.Length);
                        ServerPath serverPath         = new ServerPath(mp.CentralServerPath, serverRelativePath);
                        Guid       g = doc.Application.GetWorksharingCentralGUID(serverPath);
                        data.Add(new Snoop.Data.String("Central Model Guid", (g != null) ? g.ToString() : "null"));
                    }
                    catch (Exception ex)
                    {
                        data.Add(new Snoop.Data.Exception("Central Model Guid", ex));
                    }
                }
            }
            else
            {
                data.Add(new Snoop.Data.String("Worksharing central model path", ""));
            }

            try
            {
                data.Add(new Snoop.Data.Object("Print manager", doc.PrintManager));
            }
            catch (Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Print manager", ex));
            }

            //data.Add(new Snoop.Data.Enumerable("Print settings", doc.PrintSettings));  //TBD: Behaves badly, need to investigate.

            data.Add(new Snoop.Data.Enumerable("Beam system types", collectorOfClass <BeamSystemType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Continuous footing types", collectorOfClass <WallFoundationType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Curtain system types", collectorOfClass <CurtainSystemType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Dimension types", collectorOfClass <DimensionType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Electrical equipment types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_ElectricalEquipment)));
            data.Add(new Snoop.Data.Enumerable("Fascia types", collectorOfClass <FasciaType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Floor types", collectorOfClass <FloorType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Grid types", collectorOfClass <GridType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Gutter types", collectorOfClass <GutterType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Level types", collectorOfClass <LevelType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Lighting device types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_LightingDevices)));
            data.Add(new Snoop.Data.Enumerable("Lighting fixture types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_LightingFixtures)));
            data.Add(new Snoop.Data.Enumerable("Mechanical equipment types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_MechanicalEquipment)));
            data.Add(new Snoop.Data.Enumerable("Mullion types", doc.MullionTypes));
            data.Add(new Snoop.Data.Enumerable("Panel types", collectorOfClass <PanelType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Annotation symbol types", collectorForAnnotationSymbolTypes(doc)));
            data.Add(new Snoop.Data.Enumerable("Text note types", collectorOfClass <TextNoteType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Rebar bar types", collectorOfClass <RebarBarType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Rebar cover types", collectorOfClass <RebarCoverType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Rebar hook types", collectorOfClass <RebarHookType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Rebar shapes", collectorOfClass <RebarShape>(doc)));
            data.Add(new Snoop.Data.Enumerable("Roof types", collectorOfClass <RoofType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Room tag types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_RoomTags)));
            data.Add(new Snoop.Data.Enumerable("Slab edge types", collectorOfClass <SlabEdgeType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Space tag types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_MEPSpaceTags)));
            data.Add(new Snoop.Data.Enumerable("Spot dimension types", collectorOfClass <SpotDimensionType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Text note types", collectorOfClass <TextNoteType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Title blocks", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_TitleBlocks)));
            data.Add(new Snoop.Data.Enumerable("Truss types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_Truss)));
            data.Add(new Snoop.Data.Enumerable("View sheet sets", collectorOfClass <ViewSheetSet>(doc)));
            data.Add(new Snoop.Data.Enumerable("Wall types", collectorOfClass <WallType>(doc)));
        }
Example #6
0
        /// <summary>
        /// Count the element in each file
        /// </summary>
        /// <param name="revitDoc"></param>
        /// <param name="countItParams"></param>
        /// <param name="results"></param>
        internal static void CountElements(Document revitDoc, CountItParams countItParams)
        {
            //logic goes in here!

            FilteredElementCollector elemCollector = new FilteredElementCollector(revitDoc);

            elemCollector.OfClass(typeof(Wall));
            List <Wall>             wallElements  = new List <Wall>();
            List <RoofBase>         roofElements  = new List <RoofBase>();
            ICollection <ElementId> userSelection = elemCollector.ToElementIds();
            Element elmnt;

            foreach (var i in userSelection)
            {
                elmnt = revitDoc.GetElement(i);
                if (elmnt.Category.Name == "Walls")
                {
                    wallElements.Add(elmnt as Wall);
                }
                else if (elmnt.Category.Name == "Roofs")
                {
                    roofElements.Add(elmnt as RoofBase);
                }
            }


            //Collecting all types to be used in model
            string wcName;
            FilteredElementCollector wallTypeColl  = new FilteredElementCollector(revitDoc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType();
            List <string>            wallTypeNames = new List <string>();

            foreach (var wc in wallTypeColl)
            {
                wcName = wc.LookupParameter("Type Name").AsString();
                //TaskDialog.Show("WCNAME WALLTYPE", wcName);
                wallTypeNames.Add(wcName);
            }
            string wtName;
            FilteredElementCollector windowTypeColl  = new FilteredElementCollector(revitDoc).OfCategory(BuiltInCategory.OST_Windows).WhereElementIsElementType();
            List <string>            windowTypeNames = new List <string>();

            foreach (var wt in windowTypeColl)
            {
                wtName = wt.LookupParameter("Type Name").AsString();
                //TaskDialog.Show("WTNAME WALLTYPE", wtName);
                windowTypeNames.Add(wtName);
            }
            string rcName;
            FilteredElementCollector roofTypeColl = new FilteredElementCollector(revitDoc).OfCategory(BuiltInCategory.OST_Roofs).WhereElementIsElementType();
            List <string>            roofTypeName = new List <string>();

            foreach (var rc in roofTypeColl)
            {
                rcName = rc.LookupParameter("Type Name").AsString();
                //TaskDialog.Show("RTYPE ROOF TYPE", rcName);
                roofTypeName.Add(rcName);
            }
            //Form1 new_form = new Form1();
            //new_form.ShowDialog();
            string extMaterials     = countItParams.extMaterials;
            string materialColor    = countItParams.materialColor;
            string roofMaterial     = countItParams.roofMaterial;
            string fenestrationTrim = countItParams.fenestrationTrim;
            string columnStyle      = countItParams.columnStyle;
            //TaskDialog.Show("ext material", extMaterials);
            //List<string> wallTypeColl_list = wallTypeColl.ToList();
            var wtlist = wallTypeColl.ToList();
            //TaskDialog.Show("walltypenamecount", wallTypeNames.Count.ToString());
            Element        insertElement;
            List <Element> ws = new List <Element>();
            List <Element> ds = new List <Element>();
            Transaction    t  = new Transaction(revitDoc, "Edit walls");

            t.Start();
            foreach (var wall in wallElements)
            {
                ws.Clear();
                ds.Clear();
                for (int i = 0; i < wallTypeNames.Count; i++)
                {
                    if (wallTypeNames[i].Contains(extMaterials) & wallTypeNames[i].Contains(materialColor))
                    {
                        wall.WallType = wallTypeColl.First <Element>(x => x.Name.Equals(wallTypeNames[i].ToString())) as WallType;
                    }
                }
                IList <ElementId> allInserts = wall.FindInserts(true, false, false, false);
                foreach (var ai in allInserts)
                {
                    insertElement = revitDoc.GetElement(ai);
                    if (insertElement.Category != null)
                    {
                        if (insertElement.Category.Name == "Windows")
                        {
                            ws.Add(insertElement);
                        }
                        if (insertElement.Category.Name == "Doors")
                        {
                            ds.Add(insertElement);
                        }
                    }
                }
                foreach (Element window in ws)
                {
                    for (int i = 0; i < windowTypeNames.Count; i++)
                    {
                        if (windowTypeNames[i].Contains(fenestrationTrim))
                        {
                            //    window. = windowTypeColl.First<Element>(x => x.Name.Equals(windowTypeNames[i].ToString())) as FamilySymbol;
                        }
                    }
                }
            }
            t.Commit();

            t.Start();

            foreach (var roof in roofElements)
            {
                for (int i = 0; i < roofTypeName.Count; i++)
                {
                    if (roofTypeName[i].Contains(roofMaterial))
                    {
                        roof.RoofType = roofTypeColl.First <Element>(x => x.Name.Equals(roofTypeName[i].ToString())) as RoofType;
                    }
                }
            }

            t.Commit();

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt");

            revitDoc.SaveAs(path, new SaveAsOptions());

            //TaskDialog.Show("End", "job done");
            //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);
        }
        private void ReloadFromButton_Click(object sender, RoutedEventArgs e)
        {
            //DataRowView selectedRow = (DataRowView)linkDataGrid.SelectedItems[0];
            LinkData selectedRow = (LinkData)linkDataGrid.SelectedItems[0];

            if (selectedRow != null)
            {
                // Find an Excel File
                System.Windows.Forms.OpenFileDialog openDlg = new System.Windows.Forms.OpenFileDialog()
                {
                    Title            = "Reload From an Excel File",
                    Filter           = "Excel Files (*.xls; *.xlsx)|*.xls;*.xlsx",
                    RestoreDirectory = true
                };


                System.Windows.Forms.DialogResult result = openDlg.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string excelFilePath = openDlg.FileName;

                    if (System.IO.File.Exists(excelFilePath))
                    {
                        // read the Excel file and create the schedule
                        Excel.Application excelApp     = new Excel.Application();
                        Excel.Workbook    workbook     = excelApp.Workbooks.Open(excelFilePath);
                        Excel.Sheets      wbWorksheets = workbook.Worksheets;

                        List <WorksheetObject> worksheetObjs = new List <WorksheetObject>();
                        foreach (Excel.Worksheet ws in wbWorksheets)
                        {
                            WorksheetObject wo   = new WorksheetObject();
                            string          name = ws.Name;
                            wo.Name = name;
                            Excel.Range range = ws.UsedRange;
                            try
                            {
                                range.CopyPicture(Excel.XlPictureAppearance.xlPrinter, Excel.XlCopyPictureFormat.xlBitmap);
                                if (Clipboard.GetDataObject() != null)
                                {
                                    IDataObject data = Clipboard.GetDataObject();
                                    if (data.GetDataPresent(DataFormats.Bitmap))
                                    {
                                        System.Drawing.Image img = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
                                        wo.Image = img;
                                    }
                                }
                            }
                            catch { }
                            worksheetObjs.Add(wo);
                        }

                        // Pop up the worksheet form
                        WorksheetSelectForm wsForm = new WorksheetSelectForm(worksheetObjs, this, doc);
                        wsForm.ShowDialog();

                        if (wsForm.DialogResult.HasValue && wsForm.DialogResult.Value)
                        {
                            for (int i = 0; i < elementIds.Count; i++)
                            {
                                try
                                {
                                    int intValue = selectedRow.ElementId;
                                    if (elementIds[i].IntegerValue == intValue)
                                    {
                                        // read and reload the file.
                                        Scheduler creator = new Scheduler();
                                        creator.ModifySchedule(doc, elementIds[i], excelFilePath, worksheetObj.Name, "Reload Excel Schedule", pathTypes[i], contentOnly);
                                        string docPath;
                                        if (doc.IsWorkshared)
                                        {
                                            docPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
                                        }
                                        else
                                        {
                                            docPath = doc.PathName;
                                        }

                                        if ((PathType)pathTypes[i] == PathType.Relative)
                                        {
                                            paths[i] = PathExchange.GetRelativePath(excelFilePath, docPath);
                                        }
                                        else
                                        {
                                            paths[i] = excelFilePath;
                                        }

                                        worksheets[i] = worksheetObj.Name;
                                        System.IO.FileInfo fi = new System.IO.FileInfo(excelFilePath);
                                        dateTimes[i] = fi.LastWriteTimeUtc.ToString();

                                        // Read the schema information
                                        Autodesk.Revit.DB.ExtensibleStorage.Schema schema = Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(schemaGuid);
                                        if (schema != null)
                                        {
                                            Autodesk.Revit.DB.ExtensibleStorage.Entity entity = null;
                                            DataStorage ds = SchemaManager.GetDataStorage(doc);
                                            try
                                            {
                                                entity = ds.GetEntity(schema);
                                            }
                                            catch { }

                                            if (entity != null)
                                            {
                                                Transaction trans = new Transaction(doc, "Update Excel Document");
                                                trans.Start();
                                                entity.Set <IList <string> >("ExcelFilePath", paths);
                                                entity.Set <IList <string> >("WorksheetName", worksheets);
                                                entity.Set <IList <string> >("DateTime", dateTimes);
                                                entity.Set <IList <int> >("PathType", pathTypes);
                                                ds.SetEntity(entity);
                                                trans.Commit();

                                                BuildTable();
                                            }
                                        }
                                    }
                                }
                                catch { }
                            }
                        }
                        try
                        {
                            workbook.Close();
                            Marshal.ReleaseComObject(worksheets);
                            //Marshal.ReleaseComObject(worksheet);
                            Marshal.ReleaseComObject(workbook);
                            excelApp.Quit();
                            Marshal.ReleaseComObject(excelApp);
                        }
                        catch { }
                    }
                }
            }
        }
Example #9
0
        /// <summary>
        /// Method designed to directly load a family into a project using only a family symbol
        /// </summary>
        /// <param name="curdoc"></param>
        /// <param name="famsym"></param>
        /// <param name="cmd">External Command Data from the current command</param>
        /// <param name="doctoloadfrom">Document the family symbol should be loaded from</param>
        public static FamilySymbol LoadFamilyDirect(this Document curdoc, FamilySymbol famsym, Document doctoloadfrom, ExternalCommandData cmd)
        {
            Family newfamily = null;

            // grab the application and change the active document
            using (UIApplication uiapp = cmd.Application)
            {
                OpenOptions oop = new OpenOptions();

                oop.AllowOpeningLocalByWrongUser = true;
                oop.DetachFromCentralOption      = DetachFromCentralOption.DetachAndPreserveWorksets;

                // open "doctoloadfrom" (linked doc) and make it the active document
                if (uiapp.ActiveUIDocument.Document != doctoloadfrom)
                {
                    // try opening the document from memory only
                    try
                    {
                        Document newcurdoc = curdoc.Application.OpenDocumentFile(ModelPathUtils.ConvertUserVisiblePathToModelPath(doctoloadfrom.PathName), oop);
                    }

                    // was unable to open the document for some reason
                    catch
                    {
                        uiapp.OpenAndActivateDocument(ModelPathUtils.ConvertUserVisiblePathToModelPath(doctoloadfrom.PathName), oop, false);
                        throw new Exception("Failed in attempt to open file. File name is:" + doctoloadfrom.PathName);
                    }
                }

                // open the family document
                newfamily = famsym.Family;
                using (Document doc_family = doctoloadfrom.EditFamily(newfamily))
                {
                    // load it into the original document
                    doc_family.LoadFamily(curdoc);

                    // close the family once done
                    doc_family.Close(false);
                    //doctoloadfrom.Close(true);
                }

                // return control to the original active document
                // could create possible bug - write a method to both
                // move to another current document
                // close all but current document
                if (uiapp.ActiveUIDocument.Document != curdoc)
                {
                    while (uiapp.ActiveUIDocument.Document != curdoc)
                    {
                        uiapp.ActiveUIDocument.Document.Close(false);
                    }
                }

                using (Transaction tr_regen = new Transaction(curdoc, "Regenerating the document..."))
                {
                    tr_regen.Start();

                    // regenerate that document
                    curdoc.Regenerate();
                    tr_regen.Commit();
                }
            }

            return(famsym);
        }
Example #10
0
        public bool ValidateModel(Document doc, ref string report, IEnumerable <AddInsParameter> parameters)
        {
            report += "Проверка связанных файлов";

            if (!Settings.SetParameters(parameters))
            {
                report += $"\n\tПараметры проверки не прошли проверку";
                return(false);
            }
            var result        = true;
            var linkTypes     = new FilteredElementCollector(doc).OfClass(typeof(RevitLinkType)).Cast <RevitLinkType>().ToList();
            var linkInstances = new FilteredElementCollector(doc).OfClass(typeof(RevitLinkInstance)).Cast <RevitLinkInstance>().Where(c => c.Name.Contains("rvt")).ToList();
            var messageTitle  = string.Empty;

            if (Settings.CheckPathType)
            {
                messageTitle = $"\nУстановите значение \"{Settings.PathType}\" у параметра \"Пути\" для следующих связанных файлов Revit:";
                var pathType = Settings.PathType == "Абсолютный" ? PathType.Absolute : PathType.Relative;
                var linksWithWrongPathType = linkTypes.Where(linkType => linkType.PathType != pathType);
                result &= AddMessageToReport(linksWithWrongPathType, messageTitle, ref report);
            }

            if (Settings.CheckReferenceType)
            {
                messageTitle = $"\nУстановите тип связи \"{Settings.AttachmentType}\" для следующих связанных файлов Revit:";
                var attachemntType = Settings.AttachmentType == "Внедрение" ? AttachmentType.Attachment : AttachmentType.Overlay;
                var linksWithWrongAttachemtType = linkTypes.Where(linkType => linkType.AttachmentType != attachemntType);
                result &= AddMessageToReport(linksWithWrongAttachemtType, messageTitle, ref report);
            }


            if (Settings.CheckPin)
            {
                messageTitle = $"\nЗакрепите булавкой следующие связанные файлы Revit:";
                Func <RevitLinkInstance, bool> IsWrongFileStatus = (linkInstance) =>
                {
                    var linkedFileStatus = doc
                                           .GetElement(linkInstance.GetTypeId())
                                           .GetExternalFileReference()
                                           .GetLinkedFileStatus();
                    return(!(linkedFileStatus == LinkedFileStatus.Invalid || linkedFileStatus == LinkedFileStatus.Unloaded));
                };
                var unpinnedLinkIstances = linkInstances.Where(c => IsWrongFileStatus(c) && !c.Pinned);
                result &= AddMessageToReport(unpinnedLinkIstances, messageTitle, ref report);
            }

            if (Settings.CheckDuplicatedInstance)
            {
                messageTitle = $"\nОбратите внимание, в проекте имеются одинаковые экземпляры связанных файлов:";
                var duplicatedInstance = linkInstances
                                         .GroupBy(u => u.GetTypeId())
                                         .Where(u => u.Count() > 1)
                                         .Select(u => u.First());
                //.Select(u => doc.GetElement(u.Key));
                result &= AddMessageToReport(duplicatedInstance, messageTitle, ref report);
            }

            if (Settings.CheckServerPath)
            {
                messageTitle = $"\nВсе связанные файлы Revit должны быть загружены с сервера \"{Settings.ServerName}\".Файлы не соответствующие требованию:";
                Func <RevitLinkType, bool> IsLoadFromForbiddenSource = (linkType) =>
                {
                    var externalFileReference = linkType.GetExternalFileReference();
                    var linkedFileStatus      = externalFileReference.GetLinkedFileStatus();
                    if (linkedFileStatus == LinkedFileStatus.Invalid || linkedFileStatus == LinkedFileStatus.Unloaded)
                    {
                        return(false);
                    }
                    var linkedFilePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(externalFileReference.GetPath());
                    return(!(linkedFilePath.ToLower().Contains(Settings.ServerName.ToLower())));
                };

                var loadFromForbiddenSource = linkTypes.Where(c => IsLoadFromForbiddenSource(c));
                result &= AddMessageToReport(loadFromForbiddenSource, messageTitle, ref report);
            }

            if (Settings.CheckBasePointMatching)
            {
                messageTitle = $"\nБазовая точка  связном файлен не совпадает с базовой точкой проекта.Проверьте расположение связных файлов:";
                Func <Document, XYZ> GetBasePoint = (document) =>
                {
                    return(new FilteredElementCollector(document)
                           .OfClass(typeof(BasePoint))
                           .Cast <BasePoint>()
                           .Where(c => !c.IsShared)
                           .First()
                           .get_BoundingBox(null)
                           .Max);
                };
                var projectBasePointCoordinate = GetBasePoint(doc);
                Func <RevitLinkInstance, bool> IsBasePointMismatched = (linkInstance) =>
                {
                    var linkTransform = linkInstance.GetTotalTransform();
                    var linkBasePoint = GetBasePoint(linkInstance.GetLinkDocument());
                    var linkPointBaseIntoProjectCoordinate = linkTransform.OfPoint(linkBasePoint);
                    return(!projectBasePointCoordinate.IsAlmostEqualTo(linkPointBaseIntoProjectCoordinate));
                };
                var basePointMismatchedLinks = linkInstances.Where(c => IsBasePointMismatched(c));
                result &= AddMessageToReport(basePointMismatchedLinks, messageTitle, ref report);
            }

            report += $"\nПроверка пройдена успешно - {result}";
            return(result);
        }
Example #11
0
        /// <summary>
        /// Link in the new created document to parent document.
        /// </summary>
        /// <param name="originalIFCFileName">The full path to the original IFC file.  Same as baseLocalFileName if the IFC file is not on a server.</param>
        /// <param name="baseLocalFileName">The full path to the IFC file on disk.</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 originalIFCFileName, string baseLocalFileName, Document ifcDocument, Document originalDocument, bool useExistingType, bool doSave)
        {
            bool   saveSucceded = true;
            string fileName     = GenerateRevitFileName(baseLocalFileName);

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

                try
                {
                    ifcDocument.SaveAs(fileName, saveAsOptions);
                }
                catch
                {
                    saveSucceded = false;
                }

                if (!saveSucceded)
                {
                    try
                    {
                        string tempPathDir          = Path.GetTempPath();
                        string fileNameOnly         = Path.GetFileName(fileName);
                        string intermediateFileName = tempPathDir + fileNameOnly;
                        ifcDocument.SaveAs(tempPathDir + fileNameOnly, saveAsOptions);

                        File.Copy(intermediateFileName, fileName);
                        Application application = ifcDocument.Application;
                        ifcDocument.Close(false);

                        ifcDocument = application.OpenDocumentFile(fileName);
                        File.Delete(intermediateFileName);
                        saveSucceded = true;
                    }
                    catch (Exception ex)
                    {
                        // We still want to close the document to prevent having a corrupt model in memory.
                        saveSucceded = false;
                        Importer.TheLog.LogError(-1, ex.Message, 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);
            }

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath(originalIFCFileName);

            // Relative path type only works if the model isn't in the cloud.  As such, we'll try again if the
            // routine returns an exception.
            ExternalResourceReference ifcResource = null;

            for (int ii = 0; ii < 2; ii++)
            {
                PathType pathType = (ii == 0) ? PathType.Relative : PathType.Absolute;
                try
                {
                    ifcResource = ExternalResourceReference.CreateLocalResource(originalDocument,
                                                                                ExternalResourceTypes.BuiltInExternalResourceTypes.IFCLink, path, pathType);
                    break;
                }
                catch
                {
                    ifcResource = null;
                }
            }

            if (ifcResource == null)
            {
                Importer.TheLog.LogError(-1, "Couldn't create local IFC cached file.  Aborting import.", true);
            }


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

                try
                {
                    if (revitLinkTypeId == ElementId.InvalidElementId)
                    {
                        RevitLinkOptions options    = new RevitLinkOptions(true);
                        LinkLoadResult   loadResult = RevitLinkType.CreateFromIFC(originalDocument, ifcResource, 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, ifcResource, fileName, false);
                    }
                }
            }

            return(revitLinkTypeId);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //add the error handler
            UIApplication uiApp = commandData.Application;

            Autodesk.Revit.ApplicationServices.Application dbApp = uiApp.Application;
            dbApp.FailuresProcessing += MigrateFamiliesErrorHandler.MigrateFamiliesFailureHandler;

            log.AppendLine("**Family Migration: {0}", DateTime.Now.ToLongDateString());

            //Prompt the user for a directory containing files to be migrated
            DialogResult        result;
            FolderBrowserDialog sourceDirectoryDialog = new FolderBrowserDialog();

            sourceDirectoryDialog.Description         = "Select a directory containing families to be migrated";
            sourceDirectoryDialog.ShowNewFolderButton = false;
            result = sourceDirectoryDialog.ShowDialog();
            switch (result)
            {
            //Directory selected by user
            case DialogResult.OK:
                sourceDirectory = sourceDirectoryDialog.SelectedPath;
                break;

            //Dialog cancelled
            case DialogResult.Cancel:
                return(Result.Cancelled);

            //Unexpected result
            default:
                return(Result.Failed);
            }
            log.AppendLine("--Source directory selected: {0}", sourceDirectory);

            //Prompt the user for a directory to send migrated files to
            FolderBrowserDialog destinationDirectoryDialog = new FolderBrowserDialog();

            destinationDirectoryDialog.Description         = "Select an output directory";
            destinationDirectoryDialog.ShowNewFolderButton = true;
            result = destinationDirectoryDialog.ShowDialog();
            switch (result)
            {
            //Directory selected by user
            case DialogResult.OK:
                destinationDirectory = destinationDirectoryDialog.SelectedPath;
                break;

            //Dialog cancelled
            case DialogResult.Cancel:
                return(Result.Cancelled);

            //Unexpected result
            default:
                return(Result.Failed);
            }
            log.AppendLine("--Output directory selected: {0}", destinationDirectory);

            //Open each family and save in the current version of revit
            var app      = commandData.Application.Application;
            var openOpts = new OpenOptions();

            openOpts.Audit    = true;
            familiesToMigrate = GetEligibleFamiles(sourceDirectory);
            log.AppendLine("--{0} elligible families found", familiesToMigrate.Count());
            foreach (var sourceFileSubPath in familiesToMigrate)
            {
                try
                {
                    Document  dbDoc;
                    ModelPath sourceModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(sourceDirectory + '\\' + sourceFileSubPath);
                    log.AppendLine("+++++");
                    log.AppendLine("**Processing {0}", sourceFileSubPath);
                    dbDoc = app.OpenDocumentFile(sourceModelPath, openOpts);
                    var       destFilePath         = GetDestinationFilePath(sourceFileSubPath, destinationDirectory);
                    ModelPath destinationModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(destFilePath);
                    try
                    {
                        var saveOpts = new SaveAsOptions();
                        saveOpts.Compact               = true;
                        saveOpts.MaximumBackups        = 2;
                        saveOpts.OverwriteExistingFile = true;
                        if (!Directory.Exists(Path.GetDirectoryName(destFilePath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(destFilePath));
                        }
                        dbDoc.SaveAs(destinationModelPath, saveOpts);
                        dbDoc.Close(false);
                        log.AppendLine("--Saved migrated family: {0}", destFilePath);
                    }
                    catch (Exception e)
                    {
                        log.AppendLine("!!Could not save {0} to {1}", sourceFileSubPath, destFilePath);
                        log.LogException(e);
                    }
                }
                catch (Exception e)
                {
                    log.AppendLine("!!Could not open {0}", sourceFileSubPath);
                    log.LogException(e);
                }
            }

            //remove the error handler and write the log
            dbApp.FailuresProcessing -= MigrateFamiliesErrorHandler.MigrateFamiliesFailureHandler;
            File.WriteAllText(logFilePath, log.Text);
            return(Result.Succeeded);
        }
Example #13
0
        /**
         *
         * Genetic Algorithm with Revit API
         *
         * This sample is using GeneticSharp Library (github.com/giacomelli/GeneticSharp)
         * The MIT License (MIT)
         * Copyright (c) 2013 Diego Giacomelli
         */
        public void GridObjectPlacement(DesignAutomationData data)
        {
            m_doc = data.RevitDoc;
            m_app = data.RevitApp;

            InputData inputParameters = JsonConvert.DeserializeObject <InputData>(File.ReadAllText("params.json"));

            // Family Symbol
            Document familyProjectDoc = m_app.OpenDocumentFile("family.rvt");

            string    tempFamilyName      = Path.GetFileNameWithoutExtension(inputParameters.FamilyFileName) + ".rfa";
            ModelPath tempFamilyModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(tempFamilyName);

            FamilySymbol tempFamilySymbol = null;

            FilteredElementCollector familyInstanceCollector
                = new FilteredElementCollector(familyProjectDoc)
                  .WhereElementIsNotElementType()
                  .OfCategory(BuiltInCategory.OST_Furniture)
                  .OfClass(typeof(FamilyInstance));

            foreach (Element familyInstanceElem in familyInstanceCollector)
            {
                FamilyInstance fi = familyInstanceElem as FamilyInstance;

                Element superComponent = fi.SuperComponent;

                if (superComponent == null)
                {
                    tempFamilySymbol = fi.Symbol;

                    Family family = tempFamilySymbol.Family;

                    Document familyDoc = familyProjectDoc.EditFamily(family);

                    Family loadedFamily = familyDoc.LoadFamily(m_doc);

                    ISet <ElementId> familySymbolIds = loadedFamily.GetFamilySymbolIds();

                    foreach (ElementId familySymbolId in familySymbolIds)
                    {
                        FamilySymbol familySymbol = m_doc.GetElement(familySymbolId) as FamilySymbol;

                        m_familySymbol = familySymbol;
                    }

                    break;
                }
            }

            if (!m_familySymbol.IsActive)
            {
                using (Transaction tx = new Transaction(m_doc))
                {
                    tx.Start("Transaction Activate Family Symbol");
                    m_familySymbol.Activate();
                    tx.Commit();
                }
            }

            // Room
            m_room = m_doc.GetElement(inputParameters.RoomUniqueId) as Room;

            // Level
            m_level = m_doc.GetElement(m_room.LevelId) as Level;

            // View
            ElementId viewId = m_level.FindAssociatedPlanViewId();

            if (viewId != null)
            {
                m_view = m_doc.GetElement(viewId) as View;
            }

            // Selected Placement Method
            m_selectedPlacementMethod = int.Parse(inputParameters.GridTypeId);

            // Construct Chromosomes with 3 params, m_objectDistanceX, m_objectDistanceY, m_selectedPlacementMethod
            var chromosome = new FloatingPointChromosome(
                new double[] { double.Parse(inputParameters.DistanceXMinParam), double.Parse(inputParameters.DistanceYMinParam), double.Parse(inputParameters.DistanceWallMinParam) },
                new double[] { double.Parse(inputParameters.DistanceXMaxParam), double.Parse(inputParameters.DistanceYMaxParam), double.Parse(inputParameters.DistanceWallMaxParam) },
                new int[] { 32, 32, 32 },
                new int[] { 2, 2, 2 });

            // Population Settings
            //
            // The population size needs to be 'large enough'.
            // The question of when a population is large enough is difficult to answer.
            // Generally, it depends on the project, the number of genes, and the gene value range.
            // A good rule of thumb is to set the population size to at least 3x the number of inputs.
            // If the results don't start to converge to an answer, you may need to increase the population size.
            //
            // by www.generativedesign.org/02-deeper-dive/02-04_genetic-algorithms/02-04-02_initialization-phase
            var population = new Population(8, 12, chromosome);

            // Fitness Function Settings
            //
            // Call CreateObjectPlacementPointList() and get count of points.
            // This sample maximize a number of objects to place in a room.
            //
            // A fitness function is used to evaluate how close (or far off) a given design solution is from meeting the designer�fs goals.
            //
            // by www.generativedesign.org/02-deeper-dive/02-04_genetic-algorithms/02-04-03_evaluation-phase
            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;

                var values = fc.ToFloatingPoints();

                m_objectDistanceX = values[0];
                m_objectDistanceY = values[1];
                m_minimumDistanceFromObjectToWall = values[2];

                List <XYZ> objectPlacementPointList = CreateObjectPlacementPointList();

                return(objectPlacementPointList.Count);
            });

            var selection = new EliteSelection();
            var crossover = new UniformCrossover(0.5f);
            var mutation  = new FlipBitMutation();

            // Termination Condition Settings
            //
            // To finish the process in half an hour, this sample sets 2 conditions.
            var termination = new OrTermination(
                new GenerationNumberTermination(20),
                new TimeEvolvingTermination(TimeSpan.FromMinutes(10)));

            // Construct GeneticAlgorithm
            var ga = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation);

            ga.Termination = termination;

            Console.WriteLine("Generation: objectDistanceX, objectDistanceY, minimumDistanceFromObjectToWall = objectCount");

            var latestFitness = 0.0;

            // Callback Function of Generation Result
            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    var phenotype = bestChromosome.ToFloatingPoints();

                    m_objectDistanceX = phenotype[0];
                    m_objectDistanceY = phenotype[1];
                    m_minimumDistanceFromObjectToWall = phenotype[2];

                    Console.WriteLine(
                        "Generation {0,2}: objectDistanceX: {1}, objectDistanceY: {2}, minimumDistanceFromObjectToWall: {3} = objectCount: {4}",
                        ga.GenerationsNumber,
                        m_objectDistanceX,
                        m_objectDistanceY,
                        m_minimumDistanceFromObjectToWall,
                        bestFitness
                        );

                    List <XYZ> objectPlacementPointList = CreateObjectPlacementPointList();

                    using (Transaction tx = new Transaction(m_doc))
                    {
                        tx.Start("Transaction Create Family Instance");

                        m_view.SetCategoryHidden(new ElementId(BuiltInCategory.OST_Furniture), false);

                        foreach (XYZ point in objectPlacementPointList)
                        {
                            FamilyInstance fi = m_doc.Create.NewFamilyInstance(point, m_familySymbol, m_level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                            m_doc.Regenerate();

                            BoundingBoxXYZ fiBB = fi.get_BoundingBox(m_view);

                            double xDiff = fiBB.Max.X - fiBB.Min.X;
                            double yDiff = fiBB.Max.Y - fiBB.Min.Y;

                            if (m_objectDistanceX / m_objectDistanceY >= 1.2 && yDiff / xDiff >= 1.2)
                            {
                                LocationPoint location = fi.Location as LocationPoint;

                                if (null != location)
                                {
                                    XYZ fiLocationPoint = location.Point;

                                    XYZ axisPoint = new XYZ(fiLocationPoint.X, fiLocationPoint.Y, fiLocationPoint.Z + 10);

                                    Line axis = Line.CreateBound(fiLocationPoint, axisPoint);

                                    location.Rotate(axis, Math.PI / 2.0);
                                }
                            }
                            else if (m_objectDistanceY / m_objectDistanceX >= 1.2 && xDiff / yDiff >= 1.2)
                            {
                                LocationPoint location = fi.Location as LocationPoint;

                                if (null != location)
                                {
                                    XYZ fiLocationPoint = location.Point;

                                    XYZ axisPoint = new XYZ(fiLocationPoint.X, fiLocationPoint.Y, fiLocationPoint.Z + 10);

                                    Line axis = Line.CreateBound(fiLocationPoint, axisPoint);

                                    location.Rotate(axis, Math.PI / 2.0);
                                }
                            }
                        }

                        DWGExportOptions dwgOptions = new DWGExportOptions();

                        ICollection <ElementId> views = new List <ElementId>();
                        views.Add(m_view.Id);

                        m_doc.Export(Directory.GetCurrentDirectory() + "\\exportedDwgs", m_level.Name + "_" + m_room.Name + "_Gen " + ga.GenerationsNumber + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"), views, dwgOptions);

                        tx.RollBack();
                    }
                }
            };

            ga.Start();
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // Obtain all external resource references
            // (saying BIM360 Cloud references and local
            // file references this time)

            ISet <ElementId> xrefs = ExternalResourceUtils
                                     .GetAllExternalResourceReferences(doc);

            string caption = "BIM360 Links";

            try
            {
                int n   = 0;
                var msg = string.Empty;

                foreach (ElementId eid in xrefs)
                {
                    var elem = doc.GetElement(eid);
                    if (elem == null)
                    {
                        continue;
                    }

                    // Get RVT document links only this time

                    var link = elem as RevitLinkType;
                    if (link == null)
                    {
                        continue;
                    }

                    var map  = link.GetExternalResourceReferences();
                    var keys = map.Keys;

                    foreach (var key in keys)
                    {
                        var reference = map[key];

                        // Contains Forge BIM360 ProjectId
                        // (i.e., LinkedModelModelId) and
                        // ModelId (i.e., LinkedModelModelId)
                        // if it's from BIM360 Docs.
                        // They can be used in calls to
                        // ModelPathUtils.ConvertCloudGUIDsToCloudPath.

                        var dictinfo = reference.GetReferenceInformation();

                        // Link Name shown on the Manage Links dialog

                        var displayName = reference.GetResourceShortDisplayName();
                        var path        = reference.InSessionPath;
                    }

                    try
                    {
                        // Load model temporarily to get the model
                        // path of the cloud link

                        var result = link.Load();

                        // Link ModelPath for Revit internal use

                        var mdPath = result.GetModelName();

                        link.Unload(null);

                        // Convert model path to user visible path,
                        // i.e., saved Path shown on the Manage Links
                        // dialog

                        var path = ModelPathUtils
                                   .ConvertModelPathToUserVisiblePath(mdPath);

                        // Reference Type shown on the Manage Links dialog

                        var refType = link.AttachmentType;

                        msg += string.Format("{0} {1}\r\n",
                                             link.AttachmentType, path);

                        ++n;
                    }
                    catch (Exception ex) // never catch all exceptions!
                    {
                        TaskDialog.Show(caption, ex.Message);
                    }
                }

                caption = string.Format("{0} BIM360 Link{1}",
                                        n, Util.PluralSuffix(n));

                TaskDialog.Show(caption, msg);
            }
            catch (Exception ex)
            {
                TaskDialog.Show(caption, ex.Message);
            }
            return(Result.Succeeded);
        }
        /// <summary>
        /// Returns the cut lines.
        /// </summary>
        /// <param name="viewId">The view identifier.</param>
        public static void CutLines(ElementId viewId)
        {
            Utils.Log(string.Format("UtilsSectionView.CutLines started...", ""));

            var uidoc = DocumentManager.Instance.CurrentUIDocument;
            var doc   = uidoc.Document;
            var view  = doc.GetElement(viewId) as View;
            var app   = doc.Application;

            Options opt = new Options();

            opt.View = view;

            BoundingBoxXYZ crop = view.CropBox;

            IList <DetailCurve> detailCurves = new List <DetailCurve>();
            IList <Curve>       linkedCurves = new List <Curve>();

            Transform tr = view.CropBox.Transform;

            string path = Path.Combine(Path.GetTempPath(), "Copy.rvt");

            var rliCollection = new FilteredElementCollector(doc)
                                .OfClass(typeof(RevitLinkInstance))
                                .WhereElementIsNotElementType()
                                .Cast <RevitLinkInstance>();

            Document link = null;

            RevitServices.Transactions.TransactionManager.Instance.ForceCloseTransaction();

            CloseCopy();

            Utils.Log(string.Format("Preparing Revit Links...", ""));

            if (rliCollection.Count() > 0)
            {
                #region RevitLinkInstances
                foreach (RevitLinkInstance rli in rliCollection)
                {
                    ElementId efrId = rli.GetTypeId();

                    var status = ExternalFileUtils.GetExternalFileReference(doc, efrId).GetLinkedFileStatus();

                    Utils.Log(string.Format("Status {0}...", status));

                    if (status == LinkedFileStatus.InClosedWorkset ||
                        status == LinkedFileStatus.Invalid ||
                        status == LinkedFileStatus.LocallyUnloaded ||
                        status == LinkedFileStatus.NotFound ||
                        status == LinkedFileStatus.Unloaded)
                    {
                        continue;
                    }
                    app.CopyModel(ModelPathUtils.ConvertUserVisiblePathToModelPath(rli.GetLinkDocument().PathName), path, true);

                    link = app.OpenDocumentFile(path);
                    // access projectlocations
                    // test if the the project location in the host file exists in the linked document
                    // if exists retrieve the transform object via project position
                    // apply the transform to the total transform of the revit link instance

                    Utils.Log(string.Format("Processing {0}...", path));

                    Transform rliTransform = rli.GetTotalTransform();

                    // TODO: include angle in the calculation
                    // TODO: include different project location from the Link Instance
                    // TODO: test for different locations of the same instance

                    tr.Origin = rliTransform.Inverse.OfPoint(view.Origin);
                    tr.BasisX = rliTransform.Inverse.OfVector(-view.RightDirection);
                    tr.BasisY = XYZ.BasisZ;
                    tr.BasisZ = tr.BasisX.CrossProduct(tr.BasisY);

                    BoundingBoxXYZ bb = new BoundingBoxXYZ();
                    bb.Transform = tr;
                    XYZ min = view.CropBox.Min;
                    XYZ max = view.CropBox.Max;
                    bb.Min = new XYZ(min.X, min.Y, 0);
                    bb.Max = new XYZ(max.X, max.Y, -min.Z);

                    IList <ElementId> detailCurveIds = new List <ElementId>();

                    var linkedViewId = ElementId.InvalidElementId;

                    // TODO: create other view family types, currently works only for sections

                    using (Transaction q = new Transaction(link, "Cut1"))
                    {
                        q.Start();

                        ElementId vftId = new FilteredElementCollector(link)
                                          .OfClass(typeof(ViewFamilyType))
                                          .WhereElementIsElementType()
                                          .Cast <ViewFamilyType>()
                                          .First(x => x.ViewFamily == ViewFamily.Section)
                                          .Id;

                        View linkedView = ViewSection.CreateSection(link, vftId, bb);

                        link.Regenerate();

                        foreach (Curve c in CutCurvesInView(link, linkedView.Id))
                        {
                            linkedCurves.Add(c.CreateTransformed(rliTransform));
                        }

                        q.RollBack();
                    }

                    link.Close(false);

                    Utils.Log(string.Format("Completed", ""));
                }
                #endregion
            }



            Utils.Log(string.Format("Processing current document...", ""));

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

                #region Current Document Detail Curves

                IList <ElementId> toDelete = new List <ElementId>();

                foreach (Group g in new FilteredElementCollector(doc, view.Id)
                         .OfClass(typeof(Group))
                         .WhereElementIsNotElementType()
                         .Cast <Group>()
                         .Where(x => x.GroupType.Name == view.Name))
                {
                    g.Pinned = false;

                    toDelete.Add(g.Id);
                }

                if (toDelete.Count > 0)
                {
                    doc.Delete(toDelete);
                    toDelete.Clear();
                }

                Utils.Log(string.Format("Deleted {0} groups.", toDelete.Count));

                GraphicsStyle gs = new FilteredElementCollector(doc)
                                   .OfClass(typeof(GraphicsStyle))
                                   .WhereElementIsNotElementType()
                                   .Cast <GraphicsStyle>()
                                   .First(x => x.GraphicsStyleCategory.Name == "Medium Lines"); // TODO make it usable for different languages as well

                Utils.Log(string.Format("Preparing for extracting curves...", ""));

                foreach (Curve c in CutCurvesInView(doc, view.Id))
                {
                    try
                    {
                        var dc = doc.Create.NewDetailCurve(view, c);
                        if (null != dc)
                        {
                            detailCurves.Add(dc);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }

                if (linkedCurves.Count > 0)
                {
                    foreach (Curve c in linkedCurves.Where(x => x.Length > doc.Application.ShortCurveTolerance))
                    {
                        try
                        {
                            var dc = doc.Create.NewDetailCurve(view, c);
                            if (null != dc)
                            {
                                detailCurves.Add(dc);
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }

                foreach (DetailCurve dc in detailCurves)
                {
                    dc.LineStyle = gs;
                }

                // this is necessary otherwise a warning pops up for editing a group outside of scope
                doc.Regenerate();
                #endregion

                #region Group
                foreach (GroupType gt in new FilteredElementCollector(doc)
                         .OfClass(typeof(GroupType))
                         .WhereElementIsElementType()
                         .Where(x => x.Name == view.Name))
                {
                    toDelete.Add(gt.Id);
                }

                if (toDelete.Count > 0)
                {
                    doc.Delete(toDelete);
                }

                if (detailCurves.Count > 0)
                {
                    Group g = doc.Create.NewGroup(detailCurves.Select(x => x.Id).ToList());
                    g.GroupType.Name = view.Name;
                    g.Pinned         = true;
                }
                #endregion

                t.Commit();
            }

            CloseCopy();

            Utils.Log(string.Format("UtilsSectionView.CutLines completed.", ""));
        }
Example #16
0
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            string expetedfilesavepath = "";

            if (doc.IsWorkshared)
            {
                expetedfilesavepath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
            }
            else
            {
                expetedfilesavepath = doc.PathName;
            }

            string MyECCAFile = Path.GetDirectoryName(expetedfilesavepath) + "\\ECCalcAidFile.bin";



            ECCAProject myProject = new ECCAProject(MyECCAFile);

            try
            {
                IList <ElementId> selectedElements = uidoc.Selection.GetElementIds().ToList();
                if (selectedElements.Count > 0)
                {
                    Element selectedBeam        = doc.GetElement(selectedElements[0]);
                    bool    validStructuralBeam = ValidateStructuralBeam(selectedBeam);

                    if (validStructuralBeam == true)
                    {
                        ECCABeam newBeam = ConvertToECCABeam(selectedBeam);


                        if (!(myProject.BeamCollection.IsUnique(newBeam)))
                        {
                            MessageBox.Show("Note this beam already exisits in the collection, do you want to reset its properties?", "Warning ", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        }


                        frm_ECCAProgram ECCAMainProgram = new frm_ECCAProgram(myProject, newBeam);


                        ECCAMainProgram.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("The element you selected cannot be read as a structural beam");
                    }
                }

                //serialisation test
            }
            catch (Exception ex)
            {
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// delete elements depends on the input params.json file
        /// </summary>
        /// <param name="data"></param>
        public static void DeleteAllElements(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }


            // For CountIt workItem: If RvtParameters is null, count all types
            DeleteElementsParams deleteElementsParams = DeleteElementsParams.Parse("params.json");

            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("Delete Elements");
                if (deleteElementsParams.walls)
                {
                    FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Wall));
                    doc.Delete(col.ToElementIds());
                }
                if (deleteElementsParams.columns)
                {
                    FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Column));
                    doc.Delete(col.ToElementIds());
                }
                if (deleteElementsParams.floors)
                {
                    FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Floor));
                    doc.Delete(col.ToElementIds());
                }
                if (deleteElementsParams.doors)
                {
                    FilteredElementCollector collector  = new FilteredElementCollector(doc);
                    ICollection <ElementId>  collection = collector.OfClass(typeof(FamilyInstance))
                                                          .OfCategory(BuiltInCategory.OST_Doors)
                                                          .ToElementIds();
                    doc.Delete(collection);
                }
                if (deleteElementsParams.windows)
                {
                    FilteredElementCollector collector  = new FilteredElementCollector(doc);
                    ICollection <ElementId>  collection = collector.OfClass(typeof(FamilyInstance))
                                                          .OfCategory(BuiltInCategory.OST_Windows)
                                                          .ToElementIds();
                    doc.Delete(collection);
                }
                transaction.Commit();
            }

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt");

            doc.SaveAs(path, new SaveAsOptions());
        }
        private void PathTypeSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var      comboBox      = sender as ComboBox;
            int      selectedIndex = comboBox.SelectedIndex;
            PathType pt            = PathType.Absolute;

            if (selectedIndex == 1)
            {
                pt = PathType.Relative;
            }
            int currentRowIndex = linkDataGrid.Items.IndexOf(linkDataGrid.CurrentItem);

            try
            {
                bool empty = false;
                if (doc.PathName == string.Empty)
                {
                    empty = true;
                }
                if (!empty)
                {
                    if (currentRowIndex >= 0)
                    {
                        LinkData ld      = LinkedData[currentRowIndex];
                        string   newPath = string.Empty;
                        string   docPath;
                        if (doc.IsWorkshared)
                        {
                            docPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
                        }
                        else
                        {
                            docPath = doc.PathName;
                        }
                        switch (pt)
                        {
                        case PathType.Absolute:
                            newPath = PathExchange.GetFullPath(ld.Path, docPath);
                            break;

                        case PathType.Relative:
                            newPath = PathExchange.GetRelativePath(ld.Path, docPath);
                            break;
                        }
                        ld.Path     = newPath;
                        ld.PathType = pt;

                        // Rebuild list
                        int             listLen  = LinkedData.Count;
                        List <LinkData> tempList = LinkedData;
                        LinkedData = new List <LinkData>();
                        for (int i = 0; i < listLen; i++)
                        {
                            if (i == currentRowIndex)
                            {
                                LinkedData.Add(ld);
                            }
                            else
                            {
                                LinkedData.Add(tempList[i]);
                            }
                        }

                        pathChanged = true;
                        //BuildTable();
                        UpdateLayout();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:\n\n" + ex.ToString());
            }
        }
Example #19
0
        private void ConvertSAT2RFA()
        {
            //Get the documnet from the data(i.e)templatefile document
            Document doc = _rvtApp.NewFamilyDocument(RFA_TEMPLATE);

            //check document is not null
            if (doc == null)
            {
                throw new InvalidOperationException("Could not create family.");
            }

            //Create the transaction as we are going to modify the document by importing the family file
            //Import SAT file into template file
            using (Transaction transaction = new Transaction(doc))
            {
                //Start the transaction
                transaction.Start("CONVERTING SAT TO RFA FILE");

                //FailureHandlingOptions will collect those warnings which occurs while importing the SAT file and deletes those warning
                //These warnings occurs because all the data from the SAT file cannot be converted to revit family file(.rfa file)
                //For simple SAT files((i.e)SAT file of a Box) these type of warnings won't occur.
                FailureHandlingOptions FH_options = transaction.GetFailureHandlingOptions();
                FH_options.SetFailuresPreprocessor(new Warning_Swallower());
                transaction.SetFailureHandlingOptions(FH_options);

                //Create SATImportOptions
                //It help you to import the .sat files
                SATImportOptions SAT_IOption = new SATImportOptions();
                SAT_IOption.VisibleLayersOnly = true;
                SAT_IOption.Placement         = ImportPlacement.Centered;
                SAT_IOption.ColorMode         = ImportColorMode.Preserved;
                SAT_IOption.Unit = ImportUnit.Default;

                //get the perfect view for the placement of imported SAT file(i.e REF.LEVEL)
                //Collect all the views and get the view named as "Ref. Level" where we are going to import the sat file
                FilteredElementCollector view_collector = new FilteredElementCollector(doc).OfClass(typeof(View)).WhereElementIsNotElementType();
                IList <ElementId>        view_ids       = view_collector.ToElementIds() as IList <ElementId>;
                View view = null;
                foreach (ElementId view_id in view_ids)
                {
                    View v = doc.GetElement(view_id) as View;
                    if (v.Name.Contains("Ref. Level"))
                    {
                        view = v;
                    }
                }

                //import the .SAT file to family template file ((i.e)Metric Generic Model.rft)
                doc.Import(SAT_INPUT, SAT_IOption, view);

                //After importing
                //to save the changes commit the transaction
                transaction.Commit();
            }

            //save the imported .SAT file as .RFA file
            //If the family file(.rfa) with same name  already exists in the rfa_path,overwrite the already existing family file with the modified family file
            ModelPath     RFAmodelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(RFA_TEMP);
            SaveAsOptions SAO          = new SaveAsOptions();

            SAO.OverwriteExistingFile = true;

            //Save the familyfile
            doc.SaveAs(RFAmodelPath, SAO);

            doc.Close();
        }
        private bool FindINI()
        {
            bool result = false;

            try
            {
                string masterFilePath = "";
                if (doc.IsWorkshared)
                {
                    ModelPath modelPath = doc.GetWorksharingCentralModelPath();
                    masterFilePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(modelPath);
                    if (string.IsNullOrEmpty(masterFilePath))
                    {
                        masterFilePath = doc.PathName;
                    }
                }
                else
                {
                    masterFilePath = doc.PathName;
                }

                if (!string.IsNullOrEmpty(masterFilePath))
                {
                    iniPath = masterFilePath.Replace(".rvt", "_mass.ini");
                    if (!File.Exists(iniPath))
                    {
                        FileStream fs = File.Create(iniPath);

                        TaskDialog taskdialog = new TaskDialog("Mass from Room");
                        taskdialog.MainInstruction   = "Select a directory for the Mass families.";
                        taskdialog.MainContent       = "If you choose the option for the default directory,\n the new folder will be created in the same directory as the Revit project.";
                        taskdialog.AllowCancellation = true;
                        taskdialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Select a directory.");
                        taskdialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Default Directory.");

                        TaskDialogResult tResult = taskdialog.Show();

                        if (TaskDialogResult.CommandLink1 == tResult)
                        {
                            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                            folderBrowserDialog.Description         = "Select a directory that you want to use as the default.";
                            folderBrowserDialog.ShowNewFolderButton = true;

                            if (DialogResult.OK == folderBrowserDialog.ShowDialog())
                            {
                                massFolder = folderBrowserDialog.SelectedPath;
                            }
                        }
                        else if (TaskDialogResult.CommandLink2 == tResult)
                        {
                            massFolder = Path.GetDirectoryName(masterFilePath) + @"\RoomMass";
                            if (!Directory.Exists(massFolder))
                            {
                                Directory.CreateDirectory(massFolder);
                            }
                        }

                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            sw.WriteLine("MassFolder:" + massFolder);
                        }
                        fs.Close();
                    }

                    if (File.Exists(iniPath))
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to find INI file. \n" + ex.Message, "INIDataManager : FindINI", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                result = false;
            }
            return(result);
        }
        public static void DoJob(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            Document rvtDoc = data.RevitDoc;

            if (rvtDoc == null)
            {
                throw new InvalidOperationException("Could not open document!");
            }

            //add shared parameter definition
            //AddSetOfSharedParameters(rvtDoc);

            try
            {
                #region "delete existing direct shapes"
                // Deleting existing DirectShape
                // might need to filter out the shapes for room only?
                // get ready to filter across just the elements visible in a view
                FilteredElementCollector coll = new FilteredElementCollector(rvtDoc);
                coll.OfClass(typeof(DirectShape));
                IEnumerable <DirectShape> DSdelete = coll.Cast <DirectShape>();

                using (Transaction tx = new Transaction(rvtDoc))
                {
                    tx.Start("Delete Direct Shape");

                    try
                    {
                        foreach (DirectShape ds in DSdelete)
                        {
                            ICollection <ElementId> ids = rvtDoc.Delete(ds.Id);
                        }

                        tx.Commit();
                    }
                    catch (ArgumentException)
                    {
                        tx.RollBack();
                        throw new InvalidOperationException("Delete Direct Shape Failed!");
                    }
                }
                #endregion
                //get all rooms
                FilteredElementCollector m_Collector = new FilteredElementCollector(rvtDoc);
                m_Collector.OfCategory(BuiltInCategory.OST_Rooms);
                IList <Element> m_Rooms  = m_Collector.ToElements();
                int             roomNbre = 0;

                ElementId roomId = null;

                //  Iterate the list and gather a list of boundaries
                foreach (Room room in m_Rooms)
                {
                    //  Avoid unplaced rooms
                    if (room.Area > 1)
                    {
                        #region "found box of a room"
                        String _family_name = "testRoom-" + room.UniqueId.ToString();

                        using (Transaction tr = new Transaction(rvtDoc))
                        {
                            tr.Start("Create Mass");

                            // Found BBOX

                            BoundingBoxXYZ bb = room.get_BoundingBox(null);
                            XYZ            pt = new XYZ((bb.Min.X + bb.Max.X) / 2, (bb.Min.Y + bb.Max.Y) / 2, bb.Min.Z);

                            //  Get the room boundary
                            IList <IList <BoundarySegment> > boundaries = room.GetBoundarySegments(new SpatialElementBoundaryOptions()); // 2012


                            // a room may have a null boundary property:
                            int n = 0;

                            if (null != boundaries)
                            {
                                n = boundaries.Count;
                            }

                            //  The array of boundary curves
                            CurveArray m_CurveArray = new CurveArray();


                            // Add Direct Shape
                            List <CurveLoop> curveLoopList = new List <CurveLoop>();

                            if (0 < n)
                            {
                                int iBoundary = 0, iSegment;

                                foreach (IList <BoundarySegment> b in boundaries) // 2012
                                {
                                    List <Curve> profile = new List <Curve>();
                                    ++iBoundary;
                                    iSegment = 0;

                                    foreach (BoundarySegment s in b)
                                    {
                                        ++iSegment;
                                        Curve curve = s.GetCurve(); // 2016
                                        profile.Add(curve);         //add shape for instant object
                                    }

                                    try
                                    {
                                        CurveLoop curveLoop = CurveLoop.Create(profile);
                                        curveLoopList.Add(curveLoop);
                                    }
                                    catch (Exception)
                                    {
                                        //Debug.WriteLine(ex.Message);
                                    }
                                }
                            }
                            #endregion
                            #region "add direct shape"
                            try
                            {
                                SolidOptions options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId);

                                Frame frame = new Frame(pt, XYZ.BasisX, -XYZ.BasisZ, XYZ.BasisY);

                                //  Simple insertion point
                                XYZ pt1 = new XYZ(0, 0, 0);
                                //  Our normal point that points the extrusion directly up
                                XYZ ptNormal = new XYZ(0, 0, 100);
                                //  The plane to extrude the mass from
                                Plane       m_Plane       = Plane.CreateByNormalAndOrigin(ptNormal, pt1);
                                SketchPlane m_SketchPlane = SketchPlane.Create(rvtDoc, m_Plane); // 2014

                                //height of room
                                Location      loc    = room.Location;
                                LocationPoint lp     = loc as LocationPoint;
                                Level         oBelow = getNearestBelowLevel(rvtDoc, lp.Point.Z);
                                Level         oUpper = getNearestUpperLevel(rvtDoc, lp.Point.Z);
                                double        height = oUpper.Elevation - oBelow.Elevation;

                                Solid roomSolid;
                                roomSolid = GeometryCreationUtilities.CreateExtrusionGeometry(curveLoopList, ptNormal, height);

                                DirectShape ds = DirectShape.CreateElement(rvtDoc, new ElementId(BuiltInCategory.OST_GenericModel));

                                ds.SetShape(new GeometryObject[] { roomSolid });

                                //make a note with room number
                                roomId = ds.Id;

                                roomNbre += 1;
                                tr.Commit();
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                            #endregion
                        }

                        //add room number as shared parameters to the objects
                        #region "add shared parameter values"
                        using (Transaction tx = new Transaction(rvtDoc))
                        {
                            tx.Start("Change P");

                            Element readyDS = rvtDoc.GetElement(roomId);
                            //Parameter p = readyDS.LookupParameter("RoomNumber");
                            Parameter p = readyDS.get_Parameter(BuiltInParameter.ALL_MODEL_MARK);
                            if (p != null)
                            {
                                p.Set(room.Number.ToString());
                            }
                            tx.Commit();
                        }
                        Debug.Write("room id:" + roomId.IntegerValue.ToString());
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.ToString());
            }


            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt");
            rvtDoc.SaveAs(path, new SaveAsOptions());
        }
        // https://forums.autodesk.com/t5/revit-api-forum/reload-revit-links-from/m-p/7722248
        public Result Execute1(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // Get application and document objects

            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            // NO TRANSACTION NEEDS TO BE OPENED

            try
            {
                using (Transaction tx = new Transaction(doc))
                {
                    // Collect files linked in current project

                    FilteredElementCollector collector     = new FilteredElementCollector(doc);
                    ICollection <Element>    linkInstances = collector.OfClass(typeof(RevitLinkType)).ToElements();

                    // Check which elements are loaded > to be used as filter

                    List <bool> loaded = new List <bool>();
                    foreach (RevitLinkType i in linkInstances)
                    {
                        loaded.Add(RevitLinkType.IsLoaded(doc, i.Id));
                    }

                    // Convert ICollection into a list of RevitLinkTypes
                    int i1 = 0;

                    List <RevitLinkType> revLinkType = new List <RevitLinkType>();
                    foreach (RevitLinkType rli in linkInstances)
                    {
                        if (!loaded[i1++])
                        {
                            revLinkType.Add(rli);
                        }
                    }

                    // Put names of linked files into a list of strings
                    int i2 = 0;

                    List <string> linkNames = new List <string>();
                    foreach (Element eli in linkInstances)
                    {
                        if (!loaded[i2++])
                        {
                            linkNames.Add(eli.Name.Split(' ')[0]);
                        }
                    }

                    // Prompt user with files selection dialog

                    //Start:
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    openFileDialog1.InitialDirectory = (@"P:\");
                    openFileDialog1.Filter           = "RVT|*.rvt";
                    openFileDialog1.Multiselect      = true;
                    openFileDialog1.RestoreDirectory = true;

                    // If you select the files and hit OK (in the file browser)

                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        // Show which files (path + version) has been selected before linking them

                        StringBuilder userSelectionWVersion = new StringBuilder();
                        foreach (string fp in openFileDialog1.FileNames)
                        {
                            userSelectionWVersion.AppendLine(
                                fp.ToString()
                                + " which was created with " +
                                BasicFileInfo.Extract(fp).SavedInVersion.ToString().ToUpper());
                        }

                        // Recap the user with his selection + Revit version of the file

                        DialogResult linkCorrect = MessageBox.Show(
                            userSelectionWVersion.ToString(),
                            "You selected the files:",
                            MessageBoxButtons.OKCancel);

                        // Put paths of files selected by user into a list

                        if (linkCorrect == DialogResult.OK)
                        {
                            List <string> userSelectionNames = new List <string>();
                            foreach (string fp in openFileDialog1.FileNames)
                            {
                                userSelectionNames.Add(fp.ToString());
                            }

                            // Check which of the files that the user selected have the same name of the files linked in the project

                            IEnumerable <string> elementsToReload = userSelectionNames.Where(a => linkNames.Exists(b => a.Contains(b)));

                            // Show which files need to be reloaded

                            StringBuilder intersection = new StringBuilder();
                            foreach (string fp in elementsToReload)
                            {
                                intersection.AppendLine(fp.ToString());
                            }
                            DialogResult promptToLoad = MessageBox.Show(intersection.ToString(), "The following files need to be roloaded");

                            // Initialize + populate list of ModelPaths > path from where to reload

                            List <ModelPath> modPaths = new List <ModelPath>();

                            foreach (string fp in elementsToReload)
                            {
                                FileInfo  filePath = new FileInfo(fp);
                                ModelPath linkpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.ToString());
                                modPaths.Add(linkpath);
                            }

                            // Zip together file (as RevitLinkType) and the corresponding path to be reloaded from > Reload

                            foreach (var ab in revLinkType.Zip(modPaths, Tuple.Create))
                            {
                                ab.Item1.LoadFrom(ab.Item2, new WorksetConfiguration());
                            }
                        }
                        return(Result.Succeeded);
                    }
                }
            }
            catch (Exception ex)
            {
                // If something went wrong return Result.Failed

                DialogResult genericException = MessageBox.Show(ex.Message, "Oops there was problem!");

                return(Result.Failed);
            }
            return(Result.Succeeded);
        }
Example #23
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            //Create folder dialog path
            FileOpenDialog file_dia = new FileOpenDialog("SAT file (*.sat)|*.sat");

            file_dia.Title = "Select SAT file to import";
            file_dia.Show();
            ModelPath path = file_dia.GetSelectedModelPath();

            file_dia.Dispose();

            //Convert file path to a string
            string path_str = ModelPathUtils.ConvertModelPathToUserVisiblePath(path);

            SATImportOptions satOpt = new SATImportOptions();

            FilteredElementCollector filEle = new FilteredElementCollector(doc);

            IList <Element> views = filEle.OfClass(typeof(View)).ToElements();

            View import_view = views[0] as View;

            try
            {
                using (Transaction trans = new Transaction(doc, "Import SAT"))
                {   // Start transaction, import SAT file and get the element
                    trans.Start();
                    ElementId importedElementId = doc.Import(path_str, satOpt, import_view);
                    Element   importedElement   = doc.GetElement(importedElementId);

                    //Extract geometry element from the imported element
                    Options         geoOptions       = new Options();
                    GeometryElement importedGeometry = importedElement.get_Geometry(geoOptions);


                    //Iterate through the geometry elements extracting the geometry as individual elements
                    foreach (GeometryObject geoObj in importedGeometry)
                    {
                        GeometryInstance instance = geoObj as GeometryInstance;
                        foreach (GeometryObject instObj in instance.SymbolGeometry)
                        {
                            Solid solid = instObj as Solid;
                            FreeFormElement.Create(doc, solid);
                        }
                    }

                    //Delete SAT file

                    doc.Delete(importedElementId);
                    trans.Commit();
                }

                return(Result.Succeeded);
            }

            catch
            {
                TaskDialog.Show("Error Importing", "Something went wrong");
                return(Result.Failed);
            }
        }
        /// <summary>
        /// Remove DWF links from model and return
        /// the total number of deleted elements.
        /// </summary>
        int RemoveDwfLinkUsingExternalFileUtils(
            Document doc)
        {
            List <ElementId> idsToDelete
                = new List <ElementId>();

            ICollection <ElementId> ids = ExternalFileUtils
                                          .GetAllExternalFileReferences(doc);

            foreach (ElementId id in ids)
            {
                Element e = doc.GetElement(id);

                Debug.Print(Util.ElementDescription(e));

                ExternalFileReference xr = ExternalFileUtils
                                           .GetExternalFileReference(doc, id);

                ExternalFileReferenceType xrType
                    = xr.ExternalFileReferenceType;

                if (xrType == ExternalFileReferenceType.DWFMarkup)
                {
                    ModelPath xrPath = xr.GetPath();

                    string path = ModelPathUtils
                                  .ConvertModelPathToUserVisiblePath(xrPath);

                    if (path.EndsWith(".dwf") ||
                        path.EndsWith(".dwfx"))
                    {
                        idsToDelete.Add(id);
                    }
                }
            }

            int n = idsToDelete.Count;

            ICollection <ElementId> idsDeleted = null;

            if (0 < n)
            {
                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Delete DWFx Links");

                    idsDeleted = doc.Delete(idsToDelete);

                    t.Commit();
                }
            }

            int m = (null == idsDeleted)
        ? 0
        : idsDeleted.Count;

            Debug.Print(string.Format(
                            "Selected {0} DWF external file reference{1}, "
                            + "{2} element{3} successfully deleted.",
                            n, Util.PluralSuffix(n), m, Util.PluralSuffix(m)));

            return(m);
        }
Example #25
0
        /// <summary>
        /// List all DWG, RVT and other links of a given document.
        /// </summary>
        void ListLinks(ModelPath location)
        {
            string path = ModelPathUtils
                          .ConvertModelPathToUserVisiblePath(location);

            string content = string.Format(
                "The document at '{0}' ",
                path);

            List <string> links = null;

            // access transmission data in the given Revit file

            TransmissionData transData = TransmissionData
                                         .ReadTransmissionData(location);

            if (transData == null)
            {
                content += "does not have any transmission data";
            }
            else
            {
                // collect all (immediate) external references in the model

                ICollection <ElementId> externalReferences
                    = transData.GetAllExternalFileReferenceIds();

                int n = externalReferences.Count;

                content += string.Format(
                    "has {0} external reference{1}{2}",
                    n, PluralSuffix(n), DotOrColon(n));

                links = new List <string>(n);

                // find every reference that is a link

                foreach (ElementId refId in externalReferences)
                {
                    ExternalFileReference extRef
                        = transData.GetLastSavedReferenceData(refId);

                    links.Add(string.Format("{0} {1}",
                                            extRef.ExternalFileReferenceType,
                                            ModelPathUtils.ConvertModelPathToUserVisiblePath(
                                                extRef.GetPath())));
                }
            }
            Debug.Print(content);

            TaskDialog dlg = new TaskDialog("List Links");

            dlg.MainInstruction = content;

            if (null != links && 0 < links.Count)
            {
                string s = string.Join("  \r\n",
                                       links.ToArray());

                Debug.Print(s);

                dlg.MainContent = s;
            }
            dlg.Show();
        }
Example #26
0
        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);
            }
        }
Example #27
0
        public AdminFamiliesBAPRequest(UIApplication uiApp, String text)
        {
            MainUI uiForm = BARevitTools.Application.thisApp.newMainUi;

            uiForm.adminFamiliesBAPDoneLabel.Visible = false;
            RVTDocument   doc           = uiApp.ActiveUIDocument.Document;
            SaveAsOptions saveAsOptions = new SaveAsOptions();

            saveAsOptions.Compact               = true;
            saveAsOptions.MaximumBackups        = 3;
            saveAsOptions.OverwriteExistingFile = true;
            Dictionary <string, ExternalDefinition> sharedParameterDefinitions = new Dictionary <string, ExternalDefinition>();

            //Determine if the shared parameters file is accessible and try to get the shared parameters so their definition names and definitions could be added to a dictionary
            bool sharedParametersIsAccessible = true;

            try
            {
                DefinitionGroups sharedParameterGroups = uiApp.Application.OpenSharedParameterFile().Groups;
                foreach (DefinitionGroup group in sharedParameterGroups)
                {
                    foreach (ExternalDefinition definition in group.Definitions)
                    {
                        if (!sharedParameterDefinitions.Keys.Contains(definition.Name))
                        {
                            sharedParameterDefinitions.Add(definition.Name, definition);
                        }
                    }
                }
            } //If the access fails, then the shared parameters file was not accessible.
            catch { sharedParametersIsAccessible = false; }

            //Get the number of families to process from the DataGridView
            int filesToProcess = 0;

            foreach (DataGridViewRow rowCount in uiForm.adminFamiliesBAPFamiliesDGV.Rows)
            {
                if (rowCount.Cells["Family Select"].Value.ToString() == "True")
                {
                    filesToProcess++;
                }
            }

            //Prepare the progress bar
            uiForm.adminFamiliesBAPProgressBar.Value   = 0;
            uiForm.adminFamiliesBAPProgressBar.Minimum = 0;
            uiForm.adminFamiliesBAPProgressBar.Maximum = filesToProcess;
            uiForm.adminFamiliesBAPProgressBar.Step    = 1;
            uiForm.adminFamiliesBAPProgressBar.Visible = true;

            //Stop any edits to the DataGridView of parameters to add
            uiForm.adminFamiliesBAPParametersDGV.EndEdit();
            try
            {
                foreach (DataGridViewRow row in uiForm.adminFamiliesBAPFamiliesDGV.Rows)
                {
                    try
                    {
                        //If the checkbox for including the family in the process is not null, continue
                        if (row.Cells["Family Select"].Value != null)
                        {
                            //Grab the file path for the family
                            string        filePath      = row.Cells["Family Path"].Value.ToString();
                            List <string> famParamNames = new List <string>();
                            //If the checkbox is checked to select the family
                            if (row.Cells["Family Select"].Value.ToString() == "True")
                            {
                                //Open the family document
                                RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, filePath);
                                if (famDoc.IsFamilyDocument)
                                {
                                    //Grab the family manager and make a list of parameter names already in the family
                                    FamilyManager familyManager = famDoc.FamilyManager;
                                    foreach (FamilyParameter famParam in familyManager.Parameters)
                                    {
                                        if (!famParamNames.Contains(famParam.Definition.Name))
                                        {
                                            famParamNames.Add(famParam.Definition.Name);
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }

                                    foreach (DataGridViewRow newParamRow in uiForm.adminFamiliesBAPParametersDGV.Rows)
                                    {
                                        try
                                        {
                                            //Get the name of the parameter, group, and type of parameter to add
                                            string name = newParamRow.Cells["Parameter Name"].Value.ToString();
                                            BuiltInParameterGroup group = RVTOperations.GetBuiltInParameterGroupFromString(newParamRow.Cells["Parameter Group"].Value.ToString());
                                            ParameterType         type  = RVTOperations.GetParameterTypeFromString(newParamRow.Cells["Parameter Type"].Value.ToString());
                                            //Determine if the checkbox for making the parameter an instance parameter is checked
                                            bool isInstance = false;
                                            try
                                            {
                                                isInstance = Convert.ToBoolean(newParamRow.Cells["Parameter Is Instance"].Value.ToString());
                                            }
                                            catch { isInstance = false; }

                                            //Determine if the read-only checkbox for the parameter being a shared parameter is checked.
                                            bool isShared = false;
                                            try
                                            {
                                                isShared = Convert.ToBoolean(newParamRow.Cells["Parameter Is Shared"].Value.ToString());
                                            }
                                            catch { isShared = false; }

                                            //If the parameter is shared, and the parameter file is still accessible, and the family does not already contain a parameter with that name, continue
                                            if (isShared == true && sharedParametersIsAccessible == true && !famParamNames.Contains(name))
                                            {
                                                using (Transaction t = new Transaction(famDoc, "Add Parameter"))
                                                {
                                                    t.Start();
                                                    //Get the parameter definition from the dictionary of shared parameters, then add it to the family
                                                    ExternalDefinition definition = sharedParameterDefinitions[newParamRow.Cells["Parameter Name"].Value.ToString()];
                                                    FamilyParameter    newParam   = familyManager.AddParameter(definition, group, isInstance);
                                                    try
                                                    {
                                                        //Try to assign the parameter value if one is to be assigned
                                                        if (newParamRow.Cells["Parameter Value"].Value != null)
                                                        {
                                                            //If the number of types is greater than 0, cycle through them
                                                            if (familyManager.Types.Size > 0)
                                                            {
                                                                foreach (FamilyType familyType in familyManager.Types)
                                                                {
                                                                    //For each type, make a subtransaction
                                                                    SubTransaction s1 = new SubTransaction(famDoc);
                                                                    s1.Start();
                                                                    try
                                                                    {
                                                                        //Then set the family type as current
                                                                        familyManager.CurrentType = familyType;
                                                                        //Attempt to set the parameter value
                                                                        RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                                        s1.Commit();
                                                                    }
                                                                    catch
                                                                    {
                                                                        //If that fails, let the user know and break out of the loop
                                                                        MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for type {2} in family {3}.", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], familyType.Name, row.Cells["Family Name"]));
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                //If there was was no family types in the family, just set it for the default one
                                                                RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                            }
                                                        }
                                                    }
                                                    catch
                                                    {
                                                        //If assignment fails, let the user know the parameter value, parameter name, and the family where the failure occured.
                                                        MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for family {2}", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], row.Cells["Family Name"]));
                                                    }
                                                    t.Commit();
                                                }
                                            }
                                            else if (isShared == true && sharedParametersIsAccessible == false && !famParamNames.Contains(name))
                                            {
                                                //If the shared parameter file could not be accessed, let the user know
                                                MessageBox.Show(String.Format("Could not set the shared parameter {0} because the shared parameters file for this project could not be found. " +
                                                                              "Verify the shared parameters file is mapped correctly.", name));
                                            }
                                            else if (isShared != true && !famParamNames.Contains(name))
                                            {
                                                //Otherwise, just make a standard parameter
                                                using (Transaction t = new Transaction(famDoc, "Add Parameter"))
                                                {
                                                    t.Start();
                                                    FamilyParameter newParam = familyManager.AddParameter(name, group, type, isInstance);
                                                    try
                                                    {
                                                        if (newParamRow.Cells["Parameter Value"].Value != null)
                                                        {
                                                            RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                        }
                                                    }
                                                    catch { continue; }
                                                    t.Commit();
                                                }
                                            }
                                            else
                                            {
                                                //If all other conditions were not met, then the parameter already exists.
                                                MessageBox.Show(String.Format("Could not make parameter '{0}' for {1} because it already exists.", name, famDoc.Title));
                                            }
                                        }
                                        catch { continue; }
                                        finally
                                        {
                                            //Save the family
                                            ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);
                                            famDoc.SaveAs(filePath, saveAsOptions);
                                        }
                                    }
                                }
                                //Close the family
                                famDoc.Close(false);
                            }
                            else
                            {
                                continue;
                            }
                            //Step forward the progress bar
                            uiForm.adminFamiliesBAPProgressBar.PerformStep();
                        }
                    }
                    catch
                    {
                        MessageBox.Show("The family could not be opened, likely due to being saved in a newer version of Revit");
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                //Clean up the backups when done
                GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesBAPFamilyDirectory);
            }
            uiForm.adminFamiliesBAPProgressBar.Visible = false;
            uiForm.adminFamiliesBAPDoneLabel.Visible   = true;
            uiForm.Update();
        }