/// <summary>
        /// export to a HTML page that contains the PanelScheduleView instance data.
        /// </summary>
        /// <returns>the exported file path</returns>
        public override string Export()
        {
            string asemblyName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string tempFile = asemblyName.Replace("PanelSchedule.dll", "template.html");

            if (!System.IO.File.Exists(tempFile))
            {
                TaskDialog messageDlg = new TaskDialog("Warnning Message");
                messageDlg.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
                messageDlg.MainContent = "Can not find 'template.html', please make sure the 'template.html' file is in the same folder as the external command assembly.";
                messageDlg.Show();
                return null;
            }
            

            string panelScheduleFile = asemblyName.Replace("PanelSchedule.dll", ReplaceIllegalCharacters(m_psView.Name) + ".html");

            XmlDocument doc = new XmlDocument();
            XmlTextWriter tw = new XmlTextWriter(panelScheduleFile, null);
            doc.Load(tempFile);

            XmlNode psTable = doc.DocumentElement.SelectSingleNode("//div/table[1]");
            DumpPanelScheduleData(psTable, doc);
            
            doc.Save(tw);

            return panelScheduleFile;
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            var dialog = new TaskDialog( "Create DirectShape" )
              {
            MainInstruction = "Select the way you want to create shape"
              };

              dialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink1, "Initial shape builder" );
              dialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink2, "Jeremy's shape builder" );
              dialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink3, "Simple shape builder" );

              switch( dialog.Show() )
              {
            case TaskDialogResult.CommandLink1:
              CreateDirectShapeInitial.Execute1( commandData );
              break;

            case TaskDialogResult.CommandLink2:
              CreateDirectShape.Execute( commandData );
              break;

            case TaskDialogResult.CommandLink3:
              CreateDirectShapeSimple.Execute( commandData );
              break;
              }
              return Result.Succeeded;
        }
        void EnablePortCustomization_Checked(object sender, RoutedEventArgs e)
        {
            if (!EnablePortCustomization.IsChecked.Value)
                return;

            var rDialog = new TaskDialog()
            {
                Caption = StringResources.Instance.Main.Product_Name,
                Instruction = StringResources.Instance.Main.PreferenceWindow_Network_Port_Customization_Dialog_Instruction,
                Icon = TaskDialogIcon.Information,
                Content = StringResources.Instance.Main.PreferenceWindow_Network_Port_Customization_Dialog_Content,
                Buttons =
                {
                    new TaskDialogButton(TaskDialogCommonButton.Yes, StringResources.Instance.Main.PreferenceWindow_Network_Port_Customization_Dialog_Button_Yes),
                    new TaskDialogButton(TaskDialogCommonButton.No, StringResources.Instance.Main.PreferenceWindow_Network_Port_Customization_Dialog_Button_No),
                },
                DefaultCommonButton = TaskDialogCommonButton.No,

                OwnerWindow = WindowUtil.GetTopWindow(),
                ShowAtTheCenterOfOwner = true,
            };

            if (rDialog.Show().ClickedCommonButton == TaskDialogCommonButton.No)
                EnablePortCustomization.IsChecked = false;
        }
        /// <summary>
        /// Shows a dialog asking the user whether she want to create the
        /// specified folder.
        /// </summary>
        /// <param name="path">The folder path.</param>
        /// <returns>
        /// 	<c>true</c> is user wants to create folder; otherwise <c>false</c>.
        /// </returns>
        public bool AskToCreateFolder(string path)
        {
            const string createButtonName = "create";
            const string cancelButtonName = "cancel";

            TaskDialog dialog = new TaskDialog
            {
                Caption = "Create folder?",
                Instruction = "Create folder?",
                Content = "The folder \"" + path + "\" does not exist.",
                MainIcon = TaskDialogStandardIcon.Warning,
                Controls =
                {
                    new TaskDialogCommandLink
                    {
                        Text = "Create Folder",
                        Instruction = "This will create the folder for you and start the image resizing.",
                        Name = createButtonName
                    },
                    new TaskDialogCommandLink
                    {
                        Text = "Cancel",
                        Instruction = "This will cancel the operation and let you choose another output folder.",
                        Name = cancelButtonName
                    }
                }
            };

            TaskDialogResult result = dialog.Show();
            return result.CustomButtonClicked == createButtonName;
        }
        public void AppDialogShowing(object sender, Autodesk.Revit.UI.Events.DialogBoxShowingEventArgs arg)
        {
            //get the help id of the showing dialog
            int dialogId = arg.HelpId;

            //Format the prompt information string
            string promptInfo = "lalala";
            promptInfo += "HelpId : " + dialogId.ToString();

            //Show the prompt information and allow the user close the dialog directly
            TaskDialog td = new TaskDialog("taskDialog1");
            td.MainContent = promptInfo;
            TaskDialogCommonButtons buttons = TaskDialogCommonButtons.Ok| TaskDialogCommonButtons.Cancel;
            td.CommonButtons = buttons;
            //??liuzbkuv mjhglku
            TaskDialogResult tdr = td.Show();
            if (TaskDialogResult.Cancel == tdr)
            {
                //Do not show the Revit dialog
                arg.OverrideResult(1);
            }
            else
            {
                //Continue to show the Revit dialog
                arg.OverrideResult(0);
            }
        }
Beispiel #6
0
 public Result Execute( Autodesk.Revit.UI.ExternalCommandData cmdData, ref string msg, ElementSet elems )
 {
   TaskDialog helloDlg = new TaskDialog( "Autodesk Revit" );
   helloDlg.MainContent = "Hello World from " + System.Reflection.Assembly.GetExecutingAssembly().Location;
   helloDlg.Show();
   return Result.Cancelled;
 }
Beispiel #7
0
 /// <summary>
 /// Display an error message.
 /// </summary>
 public static void ErrorMsg( string msg )
 {
     Util.Log( msg );
       TaskDialog dlg = new TaskDialog( App.Caption );
       dlg.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
       dlg.MainInstruction = msg;
       dlg.Show();
 }
Beispiel #8
0
 public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
     ref string message, Autodesk.Revit.DB.ElementSet elements)
 {
     TaskDialog dlg = new TaskDialog(@"Hello Revit");
     dlg.MainContent = @"Hello Revit";
     dlg.MainInstruction = @"Say hello!";
     dlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, @"Hello");
     dlg.Show();
     return Autodesk.Revit.UI.Result.Succeeded;
 }
Beispiel #9
0
        /// <summary>
        /// MessageBox wrapper for error message.
        /// </summary>
        public static void ErrorMsg( string msg )
        {
            Debug.WriteLine( msg );

              //WinForms.MessageBox.Show( msg, Caption, WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Error );

              TaskDialog d = new TaskDialog( Caption );
              d.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
              d.MainInstruction = msg;
              d.Show();
        }
Beispiel #10
0
        /// <summary>
        /// Startup
        /// </summary>
        /// <param name="application"></param>
        /// <returns></returns>
        public Result OnStartup(UIControlledApplication application)
        {
            try
            {
            // Version
            if (!application.ControlledApplication.VersionName.Contains(RevitVersion))
                {
                    using (TaskDialog td = new TaskDialog("Cannot Continue"))
                    {
                        td.TitleAutoPrefix = false;
                        td.MainInstruction = "Incompatible Revit Version";
                        td.MainContent = "This Add-In was built for Revit "+ RevitVersion + ", please contact CASE for assistance.";
                        td.Show();
                    }
                    return Result.Cancelled;
                }

                // Master Tab
                const string c_tabName = "CASE";

                try
                {
                    // Create the Tab
                    application.CreateRibbonTab(c_tabName);
                }
                catch { }

            string m_issuetracker = "Case.IssueTracker.dll";
            // Tab
            RibbonPanel m_panel = application.CreateRibbonPanel(c_tabName, "Case Issue Tracker");

                // Button Data
                PushButton m_pushButton = m_panel.AddItem(new PushButtonData("Issue Tracker",
                                                                                                 "Issue Tracker",
                                                                                                 Path.Combine(_path, "Case.IssueTracker.Revit.dll"),
                                                                                                 "Case.IssueTracker.Revit.Entry.CmdMain")) as PushButton;

                // Images and Tooltip
                if (m_pushButton != null)
                {
                    m_pushButton.Image = LoadPngImgSource("Case.IssueTracker.Assets.CASEIssueTrackerIcon16x16.png", m_issuetracker);
                    m_pushButton.LargeImage = LoadPngImgSource("Case.IssueTracker.Assets.CASEIssueTrackerIcon32x32.png", m_issuetracker);
                    m_pushButton.ToolTip = "Case Issue Manager";
                }

            }
            catch (Exception ex1)
            {
                MessageBox.Show("exception: " + ex1);
                return Result.Failed;
            }

            return Result.Succeeded;
        }
Beispiel #11
0
        /// <summary>
        /// Duct Command
        /// </summary>
        /// <param name="commandData"></param>
        /// <param name="message"></param>
        /// <param name="elements"></param>
        /// <returns></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
              {

            // Version
            if (!commandData.Application.Application.VersionName.Contains("2015"))
            {

              // Failure
              using (TaskDialog td = new TaskDialog("Cannot Continue"))
              {
            td.TitleAutoPrefix = false;
            td.MainInstruction = "Incompatible Revit Version";
            td.MainContent = "This Add-In was built for Revit 2015, please contact CASE for assistance...";
            td.Show();
              }
              return Result.Failed;

            }

            // Settings
            clsSettings m_s = new clsSettings(commandData);

            // Main Category Selection Form
            using (form_Orient dlg = new form_Orient())
            {
              dlg.ShowDialog();

              if (!dlg.DoConduit && !dlg.DoDuct && !dlg.DoPipe & !dlg.DoTray) return Result.Cancelled;

              // Process Data
              if (dlg.DoConduit) m_s.ProcessConduit();
              if (dlg.DoDuct) m_s.ProcessDuct();
              if (dlg.DoPipe) m_s.ProcessPipe();
              if (dlg.DoTray) m_s.ProcessTray();

            }

            // Success
            return Result.Succeeded;

              }
              catch (Exception ex)
              {

            // Failure
            message = ex.Message;
            return Result.Failed;

              }
        }
Beispiel #12
0
        /// <summary>
        /// Report Groups by View
        /// </summary>
        /// <param name="commandData"></param>
        /// <param name="message"></param>
        /// <param name="elements"></param>
        /// <returns></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
              {

            // Version
            if (!commandData.Application.Application.VersionName.Contains("2015"))
            {
              // Failure
              using (TaskDialog td = new TaskDialog("Cannot Continue"))
              {
            td.TitleAutoPrefix = false;
            td.MainInstruction = "Incompatible Version of Revit";
            td.MainContent = "This Add-In was built for Revit 2015, please contact CASE for assistance.";
            td.Show();
              }
              return Result.Cancelled;
            }

            // Settings
            clsSettings m_s = new clsSettings(commandData);
            if (m_s.ModelGroups.Count + m_s.DetailGroups.Count < 1)
            {
              using (TaskDialog td = new TaskDialog("No Groups Found"))
              {
            td.TitleAutoPrefix = false;
            td.MainInstruction = "No Groups Found";
            td.Show();
              }
              return Result.Cancelled;
            }

            // Form
            using (form_Main d = new form_Main(m_s))
            {
              d.ShowDialog();
            }

            // Success
            return Result.Succeeded;

              }
              catch (Exception ex)
              {

            // Failure
            message = ex.Message;
            return Result.Failed;

              }
        }
Beispiel #13
0
        /// <summary>
        /// Command
        /// </summary>
        /// <param name="commandData"></param>
        /// <param name="message"></param>
        /// <param name="elements"></param>
        /// <returns></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
              {
            // Version
            if (!commandData.Application.Application.VersionName.Contains("2015"))
            {
              // Failure
              using (TaskDialog m_td = new TaskDialog("Cannot Continue"))
              {
            m_td.TitleAutoPrefix = false;
            m_td.MainInstruction = "Incompatible Version of Revit";
            m_td.MainContent = "This Add-In was built for Revit 2015, please contact CASE for assistance.";
            m_td.Show();
              }
              return Result.Cancelled;
            }

            Version m_version = typeof(CmdMain).Assembly.GetName().Version;

            RegistryKey m_key = Registry.CurrentUser
              .CreateSubKey(@"Software\CASE\Case.ParallelWalls\");

            if (m_key != null && m_key.GetValue(m_version.ToString()) == null)
            {
              form_SplashScreen m_splash = new form_SplashScreen(m_key);

              m_splash.ShowDialog();
            }

            clsElementSelection m_selection = new clsElementSelection(commandData.Application.ActiveUIDocument);

            clsVectors m_vectors = new clsVectors(
              m_selection.RefElement,
              m_selection.WallElement);

            clsWallTransform m_transform = new clsWallTransform(
              m_selection.WallElement,
              m_vectors.AxisLine,
              m_vectors.DeltaAngle);

            // Success
            return Result.Succeeded;
              }
              catch (Exception m_ex)
              {
            // Failure
            message = m_ex.Message;
            return Result.Failed;
              }
        }
        /// <summary>
        /// Shows a question dialog with Yes/No buttons.
        /// </summary>
        /// <param name="title">The title of the question.</param>
        /// <param name="question">The question.</param>
        /// <returns>
        /// 	<c>true</c> is user answered yes; otherwise <c>false</c>.
        /// </returns>
        public bool AskYesNoQuestion(string title, string question)
        {
            TaskDialog dialog = new TaskDialog
            {
                Caption = title,
                Instruction = title,
                Content = question,
                MainIcon = TaskDialogStandardIcon.Warning,
                StandardButtons = TaskDialogStandardButtons.YesNo
            };

            TaskDialogResult result = dialog.Show();
            return result.StandardButtonClicked == TaskDialogStandardButton.Yes;
        }
Beispiel #15
0
        /// <summary>
        /// Ask User
        /// </summary>
        /// <returns></returns>
        internal static bool ShowMessage()
        {
            using (TaskDialog td = new TaskDialog("Explanation"))
            {
              td.TitleAutoPrefix = false;
              td.MainInstruction = "Update 'CurveOrientation' Parameters";
              td.MainContent += "This command requires that an instance text parameter named 'CurveOrientation' exist on all elements of the target category.\n\n";
              td.MainContent += "A text string of HORIZONTAL, VERTICAL, or SLOPED will then get placed into each element's 'CurveOrientation' parameter for the primary purpose of clash detection filtering in an external program.";
            td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Update 'CurveOrientation' Parameters");
              td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel and Do Nothing");
              if (td.Show() == TaskDialogResult.CommandLink1)
             return true;
              else
             return false;

            }
        }
Beispiel #16
0
    /// <summary>
    /// Main Command Entry Point
    /// </summary>
    /// <param name="commandData"></param>
    /// <param name="message"></param>
    /// <param name="elements"></param>
    /// <returns></returns>
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
      try
      {

        // Version
        if (!commandData.Application.Application.VersionName.Contains("2014"))
        {
          using (TaskDialog td = new TaskDialog("Cannot Continue"))
          {
            td.TitleAutoPrefix = false;
            td.MainInstruction = "Incompatible Revit Version";
            td.MainContent = "This Add-In was built for Revit 2014, please contact info@case-inc for assistance...";
            td.Show();
          }
          return Result.Cancelled;
        }

        // Form Running?
        if (_isRunning && _appIssueTracker != null && _appIssueTracker.RvtWindow.IsLoaded)
        {
          _appIssueTracker.Focus();
          return Result.Succeeded;
        }

        _isRunning = true;

        ThisCmd = this;
        _appIssueTracker = new AppIssueTracker();
        _appIssueTracker.ShowForm(commandData.Application);
        return Result.Succeeded;

      }
      catch (Exception e)
      {
        message = e.Message;
        return Result.Failed;
      }

    }
Beispiel #17
0
    /// <summary>
    /// Main Command Entry Point
    /// </summary>
    /// <param name="commandData"></param>
    /// <param name="message"></param>
    /// <param name="elements"></param>
    /// <returns></returns>
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
      try
      {

        //Version check
        //2016 and 2015 use an amost identical API
        if (!commandData.Application.Application.VersionName.Contains("2015") && !commandData.Application.Application.VersionName.Contains("2016"))
        {
          using (var td = new TaskDialog("Untested version"))
          {
            td.TitleAutoPrefix = false;
            td.MainInstruction = "Untested Revit Version";
            td.MainContent = "This Add-In was built and tested only for Revit 2016 or 2015, proceed at your own risk";
            td.Show();
          }
        }

        // Form Running?
        if (_isRunning && _extAppBcfier != null && _extAppBcfier.RvtWindow.IsLoaded)
        {
          _extAppBcfier.Focus();
          return Result.Succeeded;
        }

        _isRunning = true;

        ThisCmd = this;
        _extAppBcfier = new ExtAppBcfier();
        _extAppBcfier.ShowForm(commandData.Application);
        return Result.Succeeded;

      }
      catch (Exception e)
      {
        message = e.Message;
        return Result.Failed;
      }

    }
        public override void Execute(object parameter)
        {
            var selectedItems = GetSelectedItems();
            var items = GetProjectItems(selectedItems);

            var item = items.FirstOrDefault();
            if (item == null)
            {
                return;
            }

            var project = ProjectManager.GetProject(item);
            if (project == null)
            {
                return;
            }

            var site = project.Site;
            if (site == null)
            {
                return;
            }

            var dialog = new SelectFileDialog
            {
                Site = site
            };

            if (!dialog.ShowDialog())
            {
                return;
            }

            var options = new TaskDialogOptions
            {
                Title = "Folder Synchronization",
                CommonButtons = TaskDialogCommonButtons.None,
                Content = "Select the synchronization mode.",
                MainIcon = VistaTaskDialogIcon.Information,
                DefaultButtonIndex = 0,
                CommandButtons = new[]
                {
                    "Mirror - every change is applied",
                    "Copy - only create and edit changes are applied"
                },
                AllowDialogCancellation = true
            };

            var r = TaskDialog.Show(options).CommandButtonResult;
            if (r == null)
            {
                return;
            }

            var mode = r == 0 ? FolderSynchronizationMode.Mirror : FolderSynchronizationMode.Copy;

            var fileName = dialog.SelectedFilePath.TrimStart('\\');

            var absoluteFileName = Path.Combine(site.WebRootPath, fileName);
            if (File.Exists(absoluteFileName))
            {
                fileName = Path.GetDirectoryName(fileName) ?? string.Empty;
            }

            var folderSynchronizationManager = AppHost.Container.Get<FolderSynchronizationManager>();

            var sourceFolder = folderSynchronizationManager.GetFolderFileName(project, item);
            var destinationFolder = fileName + "\\";

            folderSynchronizationManager.Add(project, sourceFolder, destinationFolder, mode, "*.*");
        }
        private List <ViewPlan> CreateNewViewPlan(Document doc, List <Level> newLevels)
        {
            List <ViewPlan> viewPlans = new List <ViewPlan>();

            // Prepare the ViewFamilyType for the ViewPlan creation
            ViewFamilyType viewFamilyType =
                (from elem in new FilteredElementCollector(doc)
                 .OfClass(typeof(ViewFamilyType))
                 .Cast <ViewFamilyType>()
                 where elem.ViewFamily == ViewFamily.StructuralPlan
                 select elem)
                .First();

            View standardTemplate =
                ViewTemplate.FindViewTemplateOrDefault(
                    _doc,
                    ViewType.CeilingPlan,
                    Default.TEMPLATE_NAME_STANDARD_FLOOR,
                    out bool standardTemplateIsFound);

            View foundationTemplate =
                ViewTemplate.FindViewTemplateOrDefault(
                    _doc,
                    ViewType.CeilingPlan,
                    Default.TEMPLATE_NAME_FOUNDATION,
                    out bool foundationTemplateIsFound);

            using (Transaction t = new Transaction(doc, "Create View Plans"))
            {
                try
                {
                    t.Start();
                    for (int i = 0; i < newLevels.Count; i++)
                    {
                        Level    level    = newLevels[i];
                        ViewPlan viewPlan = ViewPlan.Create(doc, viewFamilyType.Id, level.Id);
                        viewPlan.Name = $"0{i + 1} {level.Name}";
                        viewPlans.Add(viewPlan);
                        // TODO: Deal with the case when template is not found
                        if (!viewPlan.Name.ToLower().Contains(Default.KEYWORD_FOUNDATION) && standardTemplateIsFound)
                        {
                            viewPlan.ViewTemplateId = standardTemplate.Id;
                        }

                        if (viewPlan.Name.ToLower().Contains(Default.KEYWORD_FOUNDATION) && foundationTemplateIsFound)
                        {
                            viewPlan.ViewTemplateId = foundationTemplate.Id;
                        }

                        // Associate level to the new viewplan
                        AssociateLevelToNewViewPlan(level, viewPlan);
                    }
                    t.Commit();
                }
                catch (Exception e)
                {
                    TaskDialog.Show("Revit", $"Exception when creating view plans : {e.Message}");
                    t.RollBack();
                }
            }
            return(viewPlans);
        }
Beispiel #20
0
 public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
 {
     var td = new TaskDialog("Run it") { MainContent = "YIPEE DO DAH!!", CommonButtons = TaskDialogCommonButtons.Close };
     td.Show();
     return Result.Succeeded;
 }
Beispiel #21
0
        //Helper method
        private Dictionary <string, List <Tuple <string, string> > > ReadDataFromExcelAndReturn()
        {
            Document doc = this.Document;

            Microsoft.Office.Interop.Excel.ApplicationClass appExcel;
            Workbook   newWorkbook = null;
            _Worksheet objsheet    = null;
            Range      range;
            //group xcel data in a dictionaty so we can lookup by Feeder Designator as the key
            Dictionary <string, List <Tuple <string, string> > > dictXlFeederData = new Dictionary <string, List <Tuple <string, string> > >();

            string docPath = doc.PathName;
            string docName = doc.Title;

            if (docPath.EndsWith(".rvt"))
            {
                docName += ".rvt";
            }

            int    index     = docPath.IndexOf(docName);
            string cleanPath = (index < 0)
                                                ? docPath
                                        : docPath.Remove(index, docName.Length);

            string xlpath = cleanPath + "FEEDER SCHEDULE.xlsx";

            try
            {
                //TaskDialog.Show("Verify Files Exist", xlpath);
                appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                // then go and load this into excel
                newWorkbook = appExcel.Workbooks.Open(xlpath, true, true);
            }

            catch (System.Runtime.InteropServices.COMException)
            {
                TaskDialog.Show("WHOOPS", "Excel File does not exist. Create and format the following file:" + "\n" + "\n" + xlpath);
                return(null);
            }


            //get the active worksheet
            objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;

            //get the value that the lookup table will be using.
            string feederDesignatorParameterName = objsheet.get_Range("A1").get_Value().ToString();
            //add it to the dictionary for later reference
            var dictValue     = new List <Tuple <string, string> >();
            var dictValueItem = Tuple.Create(feederDesignatorParameterName, "");

            dictValue.Add(dictValueItem);
            dictXlFeederData.Add(FEEDER_PARAMETER_DESIGNATOR_IN_REVIT_AND_EXCEL, dictValue);

            //confirm with user that the value that the calc value is correct
            TaskDialog.Show("Verify Parameter", "This Macro will use this parameter from excel to map to element parameter in Revit. " +
                            "Verify that the case is the same in Revit" + "\n" + "\n" + feederDesignatorParameterName);

            // Read Each Cell and Compare
            //if(Celltostring == string.empty)

            int rowCount    = 1;
            int columnCount = 1;

            //string rangeStr;
            range = objsheet.UsedRange;

            // create arrays that are the length on the excel range (-1 for bc the array starts w/ 0)
            //string[] columnHeaderParameters = new string[range.Columns.Count - 1];
            //string[] feederParameterValues = new string[range.Rows.Count - 1];



            int columnHeaderRow = 1;

            //start getting values in second row
            //reset to the first column
            for (rowCount = 2; rowCount <= range.Rows.Count; rowCount++)
            {
                string feederDesignatorValue = "nil";
                var    rowData = new List <Tuple <string, string> >();
                //itterate thru each colum for each row
                for (columnCount = 1; columnCount <= range.Columns.Count; columnCount++)
                {
                    if (columnCount == 1)
                    {
                        feederDesignatorValue = (string)(range.Cells[rowCount, columnCount] as Range).Value2.ToString();
                    }
                    else
                    {
                        var columnHeader = (string)(range.Cells[columnHeaderRow, columnCount] as Range).Value2.ToString();
                        var rowValue     = (string)(range.Cells[rowCount, columnCount] as Range).Value2.ToString();
                        rowData.Add(Tuple.Create(columnHeader, rowValue));
                    }
                }

                dictXlFeederData.Add(feederDesignatorValue, rowData);
            }


            return(dictXlFeederData);
        }
            Transform.CreateTranslation(_offset); // 2014
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES

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

            Options opt = app.Create.NewGeometryOptions();

            XyzEqualityComparer comparer
                = new XyzEqualityComparer(1e-6);

#if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
            Creator creator = new Creator(doc);

            Transaction t = new Transaction(doc);

            t.Start("Create model curve copies of top face edges");
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES

            IList <Face> topFaces = new List <Face>();

            int n;
            int nWalls = 0;

            //foreach( Element e in uidoc.Selection.Elements ) // 2014

            foreach (ElementId id in uidoc.Selection.GetElementIds()) // 2015
            {
                Element e = doc.GetElement(id);

                Wall wall = e as Wall;

                if (null == wall)
                {
                    Debug.Print("Skipped "
                                + Util.ElementDescription(e));
                    continue;
                }

                // Get the side faces

                IList <Reference> sideFaces
                    = HostObjectUtils.GetSideFaces(wall,
                                                   ShellLayerType.Exterior);

                // Access the first side face

                Element e2 = doc.GetElement(sideFaces[0]);

                Debug.Assert(e2.Id.Equals(e.Id),
                             "expected side face element to be the wall itself");

                Face face = e2.GetGeometryObjectFromReference(
                    sideFaces[0]) as Face;

                if (null == face)
                {
                    Debug.Print("No side face found for "
                                + Util.ElementDescription(e));
                    continue;
                }

                // When there are opening such as doors or
                // windows in the wall, we need to find the
                // outer loop.
                // For one possible approach to extract the
                // outermost loop, please refer to
                // http://thebuildingcoder.typepad.com/blog/2008/12/2d-polygon-areas-and-outer-loop.html

                // Determine the outer loop of the side face
                // by finding the polygon with the largest area

                XYZ       normal;
                double    area, dist, maxArea = 0;
                EdgeArray outerLoop = null;

                foreach (EdgeArray ea in face.EdgeLoops)
                {
                    if (CmdWallProfileArea.GetPolygonPlane(
                            ea.GetPolygon(), out normal, out dist, out area) &&
                        Math.Abs(area) > Math.Abs(maxArea))
                    {
                        maxArea   = area;
                        outerLoop = ea;
                    }
                }

                n = 0;

#if GET_FACES_FROM_OUTER_LOOP
                // With the outermost loop, calculate the top faces

                foreach (Edge edge in outerLoop)
                {
                    // For each edge, get the neighbouring
                    // face and check its normal

                    for (int i = 0; i < 2; ++i)
                    {
                        PlanarFace pf = edge.get_Face(i)
                                        as PlanarFace;

                        if (null == pf)
                        {
                            Debug.Print("Skipped non-planar face on "
                                        + Util.ElementDescription(e));
                            continue;
                        }

                        if (Util.PointsUpwards(pf.Normal, 0.9))
                        {
                            if (topFaces.Contains(pf))
                            {
                                Debug.Print("Duplicate face on "
                                            + Util.ElementDescription(e));
                            }
                            else
                            {
                                topFaces.Add(pf);
                                ++n;
                            }
                        }
                    }
                }
#endif // GET_FACES_FROM_OUTER_LOOP

                List <XYZ> sideVertices = outerLoop.GetPolygon();

                // Go over all the faces of the wall and
                // determine which ones fulfill the following
                // two criteria: (i) planar face pointing
                // upwards, and (ii) neighbour of the side
                // face outer loop.

                Solid solid = wall.get_Geometry(opt)
                              .OfType <Solid>()
                              .First <Solid>(sol => null != sol);

                foreach (Face f in solid.Faces)
                {
                    if (IsTopFace(f))
                    {
                        IList <XYZ> faceVertices
                            = f.Triangulate().Vertices;

                        //if( sideVertices.Exists( v
                        //  => faceVertices.Contains<XYZ>( v, comparer ) ) )
                        //{
                        //  topFaces.Add( f );
                        //  ++n;
                        //}

                        foreach (XYZ v in faceVertices)
                        {
                            if (sideVertices.Contains <XYZ>(
                                    v, comparer))
                            {
                                topFaces.Add(f);
                                ++n;

#if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
                                // Display face for debugging purposes

                                foreach (EdgeArray ea in f.EdgeLoops)
                                {
                                    IEnumerable <Curve> curves
                                        = ea.Cast <Edge>()
                                          .Select <Edge, Curve>(
                                              x => x.AsCurve());

                                    foreach (Curve curve in curves)
                                    {
                                        //creator.CreateModelCurve( curve.get_Transformed( _t ) ); // 2013
                                        creator.CreateModelCurve(curve.CreateTransformed(_t)); // 2014
                                    }
                                }
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES

                                break;
                            }
                        }
                    }
                }

                Debug.Print(string.Format(
                                "{0} top face{1} found on {2} ({3})",
                                n, Util.PluralSuffix(n),
                                Util.ElementDescription(e)),
                            nWalls++);
            }

#if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
            t.Commit();
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES

            string s = string.Format(
                "{0} wall{1} successfully processed",
                nWalls, Util.PluralSuffix(nWalls));

            n = topFaces.Count;

            TaskDialog.Show("Wall Top Faces",
                            string.Format(
                                "{0} with {1} top face{2}.",
                                s, n, Util.PluralSuffix(n)));

            return(Result.Succeeded);
        }
        public static string AskForSelection([NotNull] string title, [CanBeNull] string header, [NotNull] string message, [NotNull] IEnumerable <string> options, [CanBeNull] Window owner, [CanBeNull] string defaultValue = null, [CanBeNull] bool?allowMultiSelect = null, [CanBeNull] bool?forceShinyDialog = null)
        {
            Assert.ArgumentNotNull(title, nameof(title));
            Assert.ArgumentNotNull(message, nameof(message));
            Assert.ArgumentNotNull(options, nameof(options));

            var optionsArray = options.ToArray();

            if (forceShinyDialog == true || (optionsArray.Length < 5 && allowMultiSelect != true))
            {
                TaskDialogOptions config = new TaskDialogOptions
                {
                    Owner                   = owner,
                    Title                   = title,
                    MainInstruction         = header ?? title,
                    Content                 = message,
                    CommandButtons          = optionsArray,
                    MainIcon                = VistaTaskDialogIcon.Information,
                    AllowDialogCancellation = true
                };


                TaskDialogResult res = null;
                if (owner == null)
                {
                    res = TaskDialog.Show(config);
                }
                else
                {
                    owner.Dispatcher.Invoke(() => { res = TaskDialog.Show(config); });
                }

                if (res == null)
                {
                    return(null);
                }

                var resultIndex = res.CommandButtonResult;
                if (resultIndex == null)
                {
                    return(null);
                }

                return(optionsArray[(int)resultIndex]);
            }

            SelectDialog dialog = new SelectDialog
            {
                DataContext      = optionsArray,
                Title            = message,
                AllowMultiSelect = allowMultiSelect ?? false
            };

            if (defaultValue != null)
            {
                dialog.DefaultValue = defaultValue;
            }

            object result = null;

            if (owner == null)
            {
                result = ShowDialog(dialog, null);
            }
            else
            {
                owner.Dispatcher.Invoke(() => { result = ShowDialog(dialog, owner); });
            }

            return(result as string);
        }
Beispiel #24
0
        /// <summary>
        /// Exports as an IFC file on clicking OK.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">Event arguments that contains the event data.</param>
        private void buttonExport_Click(object sender, RoutedEventArgs args)
        {
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(textBoxSetupFileName.Text);
            string filePath = Path.GetDirectoryName(textBoxSetupFileName.Text);

            // Show Path is invalid message if the path is blank or invalid.
            if (!string.IsNullOrWhiteSpace(filePath) && !Directory.Exists(filePath))
            {
                TaskDialog.Show("Error", Properties.Resources.ValidPathExists);
            }
            else
            {
                // Create a default .ifc file if the file name is blank
                if (String.IsNullOrWhiteSpace(filePath))
                {
                    updateFileName();
                }

                // Check for a valid IFC File format, if it does not exists, append the default IFC file format to export to the file
                if (Path.GetExtension(textBoxSetupFileName.Text).IndexOf(Properties.Resources.IFC, StringComparison.CurrentCultureIgnoreCase) == -1)
                {
                    textBoxSetupFileName.Text = textBoxSetupFileName.Text.ToString() + "." + m_defaultExt;
                }

                // Prompt for overwriting the file if it is already present in the directory.
                if (File.Exists(textBoxSetupFileName.Text))
                {
                    TaskDialogResult msgBoxResult = TaskDialog.Show(Properties.Resources.IFCExport, String.Format(Properties.Resources.FileExists, textBoxSetupFileName.Text), TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No);
                    if (msgBoxResult == TaskDialogResult.No)
                    {
                        return;
                    }
                }
                if (Win32API.RtlIsDosDeviceName_U(textBoxSetupFileName.Text) != 0)
                {
                    TaskDialog.Show(Properties.Resources.IFCExport, String.Format(Properties.Resources.ReservedDeviceName, textBoxSetupFileName.Text));
                    return;
                }

                IFCExportConfiguration selectedConfig = GetSelectedConfiguration();
                if (m_EditConfigVisited && LastSelectedConfig.ContainsKey(selectedConfig.Name))
                {
                    selectedConfig = LastSelectedConfig[selectedConfig.Name];
                }

                // This check will be done only for IFC4 and above as this only affects IfcMapConversion use that starts in IFC4 onward
                if (!OptionsUtil.ExportAsOlderThanIFC4(selectedConfig.IFCVersion))
                {
                    // Check whether the resulting offset (to wcs) will be too large due to geo-reference information, raise warning
                    BasePoint surveyPoint      = BasePoint.GetSurveyPoint(TheDocument);
                    BasePoint projectBasePoint = BasePoint.GetProjectBasePoint(TheDocument);
                    {
                        XYZ deltaOffset = XYZ.Zero;
                        switch (selectedConfig.SitePlacement)
                        {
                        case SiteTransformBasis.Internal:
                            deltaOffset = projectBasePoint.Position;
                            break;

                        case SiteTransformBasis.Project:
                            // Offset from Project point is Zero, unchanged from the initial value
                            break;

                        case SiteTransformBasis.ProjectInTN:
                            // Offset from Project point is Zero, unchanged from the initial value
                            break;

                        case SiteTransformBasis.Site:
                            deltaOffset = projectBasePoint.Position - surveyPoint.Position;
                            break;

                        case SiteTransformBasis.Shared:
                            deltaOffset = projectBasePoint.SharedPosition;
                            break;

                        default:
                            break;
                        }

                        if (!XYZ.IsWithinLengthLimits(deltaOffset))
                        {
                            TaskDialogResult msgBoxResult = TaskDialog.Show(Properties.Resources.IFCExport, Properties.Resources.OffsetDistanceTooLarge,
                                                                            TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel);
                            if (msgBoxResult == TaskDialogResult.Cancel)
                            {
                                return;
                            }
                        }
                    }
                }

                Result = IFCExportResult.ExportAndSaveSettings;
                Close();

                // Set IFC File header with the selected exchange requirement
                if (selectedConfig.ExchangeRequirement != KnownERNames.NotDefined)
                {
                    IFCFileHeader     ifcFileHeader = new IFCFileHeader();
                    IFCFileHeaderItem fileHeaderItem;
                    bool newFileHeader = false;

                    if (!ifcFileHeader.GetSavedFileHeader(IFCCommandOverrideApplication.TheDocument, out fileHeaderItem))
                    {
                        // Do minimum initialization if the header item is not initialized
                        fileHeaderItem = new IFCFileHeaderItem(IFCCommandOverrideApplication.TheDocument);
                        newFileHeader  = true;
                    }

                    string erName = selectedConfig.ExchangeRequirement.ToString();
                    string newExchangeRequirement = "ExchangeRequirement [" + erName + "]";
                    if (newFileHeader || fileHeaderItem.FileDescription == null || !fileHeaderItem.FileDescription.Equals(newExchangeRequirement))
                    {
                        fileHeaderItem.FileDescription = newExchangeRequirement;
                        ifcFileHeader.UpdateFileHeader(IFCCommandOverrideApplication.TheDocument, fileHeaderItem);
                    }
                }

                LastSelectedConfig[selectedConfig.Name] = selectedConfig;
                TheDocument.Application.WriteJournalComment("Dialog Closed", true);
            }
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            bool run_ViewSheetSet_Views_benchmark = true;

            if (run_ViewSheetSet_Views_benchmark)
            {
                string     s  = GetViewSheetSetViewsBenchmark(doc);
                TaskDialog td = new TaskDialog(
                    "ViewSheetSet.Views Benchmark");
                td.MainContent = s;
                td.Show();
                return(Result.Succeeded);
            }

            FilteredElementCollector sheets
                = new FilteredElementCollector(doc);

            sheets.OfClass(typeof(ViewSheet));

            // map with key = sheet element id and
            // value = list of viewport element ids:

            Dictionary <ElementId, List <ElementId> >
            mapSheetToViewport =
                new Dictionary <ElementId, List <ElementId> >();

            // map with key = viewport element id and
            // value = sheet element id:

            Dictionary <ElementId, ElementId> mapViewportToSheet
                = new Dictionary <ElementId, ElementId>();

            foreach (ViewSheet sheet in sheets)
            {
                //int n = sheet.Views.Size; // 2014

                ISet <ElementId> viewIds = sheet.GetAllPlacedViews(); // 2015

                int n = viewIds.Count;

                Debug.Print(
                    "Sheet {0} contains {1} view{2}: ",
                    Util.ElementDescription(sheet),
                    n, Util.PluralSuffix(n));

                ElementId idSheet = sheet.Id;

                int i = 0;

                foreach (ElementId id in viewIds)
                {
                    View v = doc.GetElement(id) as View;

                    BoundingBoxXYZ bb;

                    bb = v.get_BoundingBox(doc.ActiveView);

                    Debug.Assert(null == bb,
                                 "expected null view bounding box");

                    bb = v.get_BoundingBox(sheet);

                    Debug.Assert(null == bb,
                                 "expected null view bounding box");

                    Element viewport = GetViewport(sheet, v);

                    // null if not in active view:

                    bb = viewport.get_BoundingBox(doc.ActiveView);

                    BoundingBoxUV outline = v.Outline;

                    Debug.WriteLine(string.Format(
                                        "  {0} {1} bb {2} outline {3}",
                                        ++i, Util.ElementDescription(v),
                                        (null == bb ? "<null>" : Util.BoundingBoxString(bb)),
                                        Util.BoundingBoxString(outline)));

                    if (!mapSheetToViewport.ContainsKey(idSheet))
                    {
                        mapSheetToViewport.Add(idSheet,
                                               new List <ElementId>());
                    }
                    mapSheetToViewport[idSheet].Add(v.Id);

                    Debug.Assert(
                        !mapViewportToSheet.ContainsKey(v.Id),
                        "expected viewport to be contained"
                        + " in only one single sheet");

                    mapViewportToSheet.Add(v.Id, idSheet);
                }
            }
            return(Result.Cancelled);
        }
        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);
        }
Beispiel #27
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Transaction trans = new Transaction(revit.Application.ActiveUIDocument.Document, "Revit.SDK.Samples.AreaReinCurve");

            trans.Start();
            ElementSet selected = new ElementSet();

            foreach (ElementId elementId in revit.Application.ActiveUIDocument.Selection.GetElementIds())
            {
                selected.Insert(revit.Application.ActiveUIDocument.Document.GetElement(elementId));
            }

            try
            {
                m_doc = revit.Application.ActiveUIDocument.Document;

                //selected is not one rectangular AreaReinforcement
                if (!PreData(selected))
                {
                    message = "Please select only one rectangular AreaReinforcement.";
                    trans.RollBack();
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                //fail to turn off layers
                if (!TurnOffLayers())
                {
                    message = "Can't turn off layers as expected or can't find these layers.";
                    trans.RollBack();
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                //fail to remove hooks
                if (!ChangeHookType())
                {
                    message = "Can't remove HookTypes as expected.";
                    trans.RollBack();
                    return(Autodesk.Revit.UI.Result.Failed);
                }
            }
            catch (ApplicationException appEx)
            {
                message = appEx.ToString();
                trans.RollBack();
                return(Autodesk.Revit.UI.Result.Failed);
            }
            catch
            {
                message = "Unexpected error happens.";
                trans.RollBack();
                return(Autodesk.Revit.UI.Result.Failed);
            }

            //command is successful
            string msg = "All layers but Major Direction Layer or Exterior Direction Layer ";

            msg += "have been turn off; ";
            msg += "Removed the Hooks from one boundary curve of the Major Direction Layer ";
            msg += "or Exterior Direction Layer.";
            TaskDialog.Show("Revit", msg);
            trans.Commit();
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Beispiel #28
0
        public Autodesk.Revit.UI.Result Execute(
            ExternalCommandData revit,
            ref string message,
            ElementSet elements)
        {
            try
            {
                // Get the active document and view
                UIDocument             revitDoc = revit.Application.ActiveUIDocument;
                Autodesk.Revit.DB.View view     = revitDoc.Document.ActiveView;
                foreach (Autodesk.Revit.DB.ElementId elemId in revitDoc.Selection.GetElementIds())
                {
                    //if( elem.GetType() == typeof( Autodesk.Revit.DB.Structure.Rebar ) )
                    Autodesk.Revit.DB.Element elem = revitDoc.Document.GetElement(elemId);
                    if (elem is Rebar)
                    {
                        string str = "";
                        Autodesk.Revit.DB.Structure.Rebar rebar = (Autodesk.Revit.DB.Structure.Rebar)elem;
                        ParameterSet pars = rebar.Parameters;
                        foreach (Parameter param in pars)
                        {
                            string val  = "";
                            string name = param.Definition.Name;
                            Autodesk.Revit.DB.StorageType type = param.StorageType;
                            switch (type)
                            {
                            case Autodesk.Revit.DB.StorageType.Double:
                                val = param.AsDouble().ToString();
                                break;

                            case Autodesk.Revit.DB.StorageType.ElementId:
                                Autodesk.Revit.DB.ElementId id       = param.AsElementId();
                                Autodesk.Revit.DB.Element   paraElem = revitDoc.Document.GetElement(id);
                                if (paraElem != null)
                                {
                                    val = paraElem.Name;
                                }
                                break;

                            case Autodesk.Revit.DB.StorageType.Integer:
                                val = param.AsInteger().ToString();
                                break;

                            case Autodesk.Revit.DB.StorageType.String:
                                val = param.AsString();
                                break;

                            default:
                                break;
                            }
                            str = str + name + ": " + val + "\r\n";
                        }
                        TaskDialog.Show("Rebar parameters", str);
                        return(Autodesk.Revit.UI.Result.Succeeded);
                    }
                }
                message = "No rebar selected!";
                return(Autodesk.Revit.UI.Result.Failed);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
        // OnStartup() - called when Revit starts.

        public Result OnStartup(UIControlledApplication app)
        {
            TaskDialog.Show("My Dialog Title", "Hello World from App!");

            return(Result.Succeeded);
        }
 public static void ShowWarningMessage(String message, String caption)
 {
     TaskDialog.Show(caption, message, TaskDialogCommonButtons.Ok);
 }
        private void updateIdTable(IList <Element> elements, bool isTypes)
        {
            using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + _dbFilename + ";Version=3;"))
            {
                string errorElements = "";

                conn.Open();
                using (var transaction = conn.BeginTransaction())
                {
                    foreach (Element e in elements)
                    {
                        Category c = e.Category;

                        string familyAndName = ""; //get element Name

                        if (isTypes)
                        {
                            familyAndName = GetElementTypeFamilyAndName(_doc, e);
                        }
                        else
                        {
                            familyAndName = GetInstaceFamilyAndName(_doc, e);
                        }

                        if (c == null)
                        {
                            FamilySymbol fs = e as FamilySymbol;
                            if (fs != null)
                            {
                                c = fs.Family.FamilyCategory;
                            }
                        }

                        string catName = (c != null) ? c.Name : "(none)";
                        if (catName.Contains("'"))
                        {
                            catName = catName.Replace("'", "''");
                        }

                        if (familyAndName.Contains("'"))
                        {
                            familyAndName = familyAndName.Replace("'", "''");
                        }

                        var cmd = conn.CreateCommand();


                        try
                        {
                            cmd.CommandText = String.Format("INSERT INTO _objects_id (id,external_id,category,family_name,isType) VALUES({0},'{1}','{2}','{3}',{4})", e.Id.IntegerValue, e.UniqueId, catName, familyAndName, (isTypes) ? 1 : 0);

                            cmd.ExecuteNonQuery();
                        }
                        catch
                        {
                            errorElements += $"{e.Name} : {e.Id} \n";
                        }
                    }

                    transaction.Commit();

                    if (isTypes)
                    {
                        TaskDialog.Show("Type Error", errorElements);
                    }
                    else
                    {
                        TaskDialog.Show("Instance Error", errorElements);
                    }
                }
            }
        }
Beispiel #32
0
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            var document = revit.Application.ActiveUIDocument.Document;

            try
            {
                string errorMessage;
                Logic.CreateLogic(document, out errorMessage);
                if (errorMessage != null)
                {
                    TaskDialog.Show("Ошибка", errorMessage);
                }
                else
                {
                    var levels = Logic.Levels
                                 .ToDictionary(x => x.Id, x => x.Name);
                    var groups = Logic.GroupTypes
                                 .ToDictionary(x => x.Id, x => new Tuple <string, List <ElementId> >(x.Name, GetGroupId(x)));
                    var dialog = new Dialog(levels, groups);
                    dialog.ShowDialog();
                    while (dialog.DialogResult == DialogResult.OK)
                    {
                        // debug
                        var result = new StringBuilder();
                        result.AppendLine($"SelectedGroupId: {(dialog.SelectedGroupId == null ? 0 : dialog.SelectedGroupId.IntegerValue)}");
                        result.AppendLine($"SelectedStandartFloorId: {(dialog.SelectedStandartFloorId == null ? 0 : dialog.SelectedStandartFloorId.IntegerValue)}");
                        result.AppendLine("SelectedFinishingsIds:");
                        foreach (var x in dialog.SelectedFinishingsIds)
                        {
                            result.AppendLine(x.IntegerValue.ToString());
                        }
                        result.AppendLine($"SelectedUserGroupName: {dialog.SelectedUserGroupName}");
                        result.AppendLine("SelectedLevelsIds:");
                        foreach (var x in dialog.SelectedLevelsIds)
                        {
                            result.AppendLine(x.IntegerValue.ToString());
                        }
                        TaskDialog.Show("Selected", result.ToString());
                        // end debug
                        if (dialog.SelectedGroupId != null)
                        {
                            break;
                        }
                        else
                        {
                            var conflictFinishing = new List <ElementId>();
                            foreach (var finishingId in dialog.SelectedFinishingsIds)
                            {
                                if (Logic.IsFinishingInAnotherGroup(finishingId))
                                {
                                    conflictFinishing.Add(finishingId);
                                }
                            }
                            if (conflictFinishing.Count > 0)
                            {
                                var task          = new TaskDialog("Конфликт");
                                var conflictNames = new List <string>();
                                foreach (var item in conflictFinishing)
                                {
                                    conflictNames.Add(GetNameById(document, item));
                                }
                                task.ExpandedContent = string.Join("\n", conflictFinishing);//conflictNames
                                task.MainInstruction = "Некоторые элементы уже включены в другие группы." +
                                                       "Их можно удалить из других групп либо пропустить." +
                                                       "Удалить элементы из других групп?";
                                var buttons = TaskDialogCommonButtons.No | TaskDialogCommonButtons.Retry | TaskDialogCommonButtons.Yes;
                                task.CommonButtons = buttons;
                                var taskResult = task.Show();
                                if (taskResult == TaskDialogResult.No)
                                {
                                    foreach (var item in conflictFinishing)
                                    {
                                        dialog.SelectedFinishingsIds.Remove(item);
                                    }
                                    break;
                                }
                                if (taskResult == TaskDialogResult.Yes)
                                {
                                    RemoveFinishingFromGroups(document, conflictFinishing);
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        dialog.DialogResult = DialogResult.None;
                        dialog.ShowDialog();
                    }
                    //var group = document.Create.NewGroup(dialog.SelectedFinishingsIds);
                    //if(!string.IsNullOrEmpty(dialog.SelectedUserGroupName))
                    //    group.Name = dialog.SelectedUserGroupName;
                }

                //TaskDialog.Show("DuctManagement", "Погнали!");
            }
            catch (Exception e)
            {
                TaskDialog.Show("Error", e.ToString());
                return(Result.Failed);
            }
            return(Result.Succeeded);
        }
Beispiel #33
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            var projectInfo = doc.ProjectInformation;

            FooEntity fooEntity = new FooEntity();

            fooEntity.IntProperty        = int.MaxValue;
            fooEntity.ShortProperty      = short.MinValue;
            fooEntity.ByteProperty       = 0;
            fooEntity.DoubleProperty     = 8.23123456789;
            fooEntity.FloatProperty      = 0.23345F;
            fooEntity.BoolProperty       = true;
            fooEntity.StringProperty     = "The quick brown fox jumps over the lazy dog";
            fooEntity.GuidProperty       = new Guid("DFCD07E5-7218-4052-8731-1F8B74ABFCF3");
            fooEntity.ElementIdProperty  = new ElementId(9872);
            fooEntity.XyzProperty        = new XYZ(10.01, 20.02, 30.03);
            fooEntity.UvProperty         = new UV(1001, 2222.333);
            fooEntity.DeepEntityProperty =
                new DeepEntity
            {
                Count     = 789,
                ElementId = new ElementId(7777)
            };

            fooEntity.IntArrayProperty =
                new Collection <int> {
                1, 5, 8, 4, 37, 183403853, -243512, -4122345
            };
            fooEntity.ShortArrayProperty =
                new List <short>()
            {
                -23, 13456, 4236, 125, 752, 246, -234
            };
            fooEntity.ByteArrayProperty =
                new BindingList <byte>()
            {
                0, 1, 2, 3, 255
            };
            fooEntity.DoubleArrayProperty =
                new ObservableCollection <double>()
            {
                -23.45, 34.56
            };
            fooEntity.FloatArrayProperty =
                new List <float>()
            {
                99.8877665544332211F
            };
            fooEntity.BoolArrayProperty =
                new Collection <bool>()
            {
                true, true, false, true, false, false
            };
            fooEntity.StringArrayProperty =
                new List <string>()
            {
                "QWERTY", "ASDFGH", "ZxCvBN"
            };
            fooEntity.GuidArrayProperty =
                new List <Guid>()
            {
                new Guid("9E7941F8-03EE-48AC-90B7-4352911F06F7"),
                new Guid("78304C8D-B904-47A2-BDF6-C52A6B569D86"),
                new Guid("8B1ADB16-4974-4820-A0E2-129F16620331")
            };
            fooEntity.ElementIdArrayProperty =
                new List <ElementId>()
            {
                new ElementId(1),
                new ElementId(2),
                new ElementId(3)
            };
            fooEntity.XyzArrayProperty =
                new Collection <XYZ>()
            {
                XYZ.Zero,
                XYZ.BasisX,
                XYZ.BasisY,
                XYZ.BasisZ
            };
            fooEntity.UvArrayProperty =
                new BindingList <UV>()
            {
                UV.Zero,
                UV.BasisU,
                UV.BasisV,
            };

            fooEntity.BarEntityArray =
                new List <BarEntity>()
            {
                new BarEntity()
                {
                    ArrayField = new List <int>()
                    {
                        123, 456
                    },
                    Property1   = "Hello, world!",
                    Property2   = 99,
                    Property3   = 0.0000000056,
                    SubEntities = new List <DeepEntity>()
                    {
                        new DeepEntity()
                        {
                            Count = 1, ElementId = new ElementId(43)
                        },
                        new DeepEntity()
                        {
                            Count = 589, ElementId = new ElementId(55)
                        }
                    },
                    SubEntity = new DeepEntity()
                    {
                        Count = 0, ElementId = ElementId.InvalidElementId
                    }
                },
                new BarEntity()
                {
                    ArrayField = new List <int>()
                    {
                        789, 101112
                    },
                    Property1   = "Hello, again!",
                    Property2   = 88,
                    Property3   = -0.0000000056,
                    SubEntities = new List <DeepEntity>()
                    {
                        new DeepEntity()
                        {
                            Count = 100, ElementId = new ElementId(555)
                        },
                        new DeepEntity()
                        {
                            Count = 345, ElementId = new ElementId(666)
                        }
                    },
                    SubEntity = new DeepEntity()
                    {
                        Count = 12, ElementId = ElementId.InvalidElementId
                    }
                }
            };

            fooEntity.BoolXyzMap =
                new Dictionary <bool, XYZ>()
            {
                { true, new XYZ(1, 2, 3) },
                { false, new XYZ(-3, -2, -1) }
            };
            fooEntity.ByteGuidMap =
                new SortedDictionary <byte, Guid>()
            {
                { 0, new Guid("D2EF3FB3-0EF9-4F5A-BCBD-A1F84EA658B8") },
                { 255, new Guid("71DA88AA-6D47-4BF9-972A-DDB6F90BFAE0") },
                { 124, new Guid("1DDF733C-5AA1-4079-99E9-D621DBDFD928") }
            };
            fooEntity.ShortElementIdMap =
                new Dictionary <short, ElementId>()
            {
                { -23, ElementId.InvalidElementId },
                { 124, new ElementId(245) },
                { 156, new ElementId(984534) },
                { -145, new ElementId(991233516) }
            };
            fooEntity.IntBarEntityMap =
                new SortedDictionary <int, BarEntity>()
            {
                { -1, new BarEntity()
                  {
                      ArrayField = new List <int>()
                      {
                          234, 1112
                      },
                      Property1   = "Hello from map!",
                      Property2   = 33,
                      Property3   = -0.0000200056,
                      SubEntities = new List <DeepEntity>()
                      {
                          new DeepEntity()
                          {
                              Count = 100, ElementId = new ElementId(555)
                          },
                          new DeepEntity()
                          {
                              Count = 345, ElementId = new ElementId(666)
                          }
                      },
                      SubEntity = new DeepEntity()
                      {
                          Count = 12, ElementId = ElementId.InvalidElementId
                      }
                  } },
                { 775993884, new BarEntity()
                  {
                      ArrayField = new List <int>()
                      {
                          0, 123, 345564, -31243, 51454
                      },
                      Property1   = "Hello from map 2!",
                      Property2   = 33,
                      Property3   = -0.0000200056,
                      SubEntities = new List <DeepEntity>()
                      {
                          new DeepEntity()
                          {
                              Count = 100, ElementId = new ElementId(555)
                          },
                          new DeepEntity()
                          {
                              Count = 345, ElementId = new ElementId(666)
                          }
                      },
                      SubEntity = new DeepEntity()
                      {
                          Count = 12, ElementId = ElementId.InvalidElementId
                      }
                  } }
            };
            fooEntity.ElementIdStringMap =
                new Dictionary <ElementId, string>()
            {
                { new ElementId(BuiltInParameter.LEVEL_DATA_OWNING_LEVEL),
                  "LEVEL_DATA_OWNING_LEVEL" },
                { ElementId.InvalidElementId,
                  "Invalid" }
            };

            fooEntity.GuidDeepEntityMap =
                new Dictionary <Guid, DeepEntity>()
            {
                { new Guid("A85D94A3-162D-4611-BA9B-C268700ECDB1"),
                  new DeepEntity()
                  {
                      Count = 23, ElementId = new ElementId(24)
                  } }
            };
            fooEntity.StringDoubleMap =
                new SortedDictionary <string, double>()
            {
                { "one point zero five", 0.05 },
                { "one hundred and sixty six point one two three", 166.123 }
            };

            //fooEntity.NonFieldProperty = "Non field property";

            using (Transaction transaction = new Transaction(doc, "Set entity"))
            {
                transaction.Start();
                projectInfo.SetEntity(fooEntity);
                transaction.Commit();
            }

            var extractedFooEntity =
                projectInfo.GetEntity <FooEntity>();

            message = GetEntityInfo(extractedFooEntity);

            //bool entitiesAreEqual =
            //    fooEntity.Equals(extractedFooEntity);

            TaskDialog
            .Show("Extract entity",
                  message);

            return(Result.Succeeded);
        }
Beispiel #34
0
        public void QTO_2_PlaceHoldersFromDWFMarkups(
            Document doc,
            string activityId)
        {
            View activeView = doc.ActiveView;

            if (!(activeView is ViewSheet))
            {
                TaskDialog.Show("QTO",
                                "The current view must be a Sheet View with DWF markups");
                return;
            }

            ViewSheet vs = activeView as ViewSheet;

            Viewport vp = doc.GetElement(
                vs.GetAllViewports().First()) as Viewport;

            View plan = doc.GetElement(vp.ViewId) as View;

            int scale = vp.Parameters.Cast <Parameter>()
                        .First(x => x.Id.IntegerValue.Equals(
                                   (int)BuiltInParameter.VIEW_SCALE))
                        .AsInteger();

            IEnumerable <Element> dwfMarkups
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(ImportInstance))
                  .WhereElementIsNotElementType()
                  .Where(x => x.Name.StartsWith("Markup") &&
                         x.OwnerViewId.IntegerValue.Equals(
                             activeView.Id.IntegerValue));

            using (TransactionGroup tg = new TransactionGroup(doc))
            {
                tg.Start("DWF markups placeholders");

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("DWF Transfer");

                    plan.Parameters.Cast <Parameter>()
                    .First(x => x.Id.IntegerValue.Equals(
                               (int)BuiltInParameter.VIEWER_CROP_REGION))
                    .Set(1);

                    XYZ VC = (plan.CropBox.Min + plan.CropBox.Max) / 2;

                    XYZ BC = vp.GetBoxCenter();

                    t.RollBack();

                    foreach (Element e in dwfMarkups)
                    {
                        GeometryElement GeoElem = e.get_Geometry(new Options());

                        GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First();

                        GeometryElement gei = gi.GetSymbolGeometry();

                        IList <GeometryObject> gos = new List <GeometryObject>();

                        if (gei.Cast <GeometryObject>().Count(x => x is Arc) > 0)
                        {
                            continue;
                        }

                        foreach (GeometryObject go in gei)
                        {
                            XYZ med = new XYZ();

                            if (go is PolyLine)
                            {
                                PolyLine pl = go as PolyLine;

                                XYZ min = new XYZ(pl.GetCoordinates().Min(p => p.X),
                                                  pl.GetCoordinates().Min(p => p.Y),
                                                  pl.GetCoordinates().Min(p => p.Z));

                                XYZ max = new XYZ(pl.GetCoordinates().Max(p => p.X),
                                                  pl.GetCoordinates().Max(p => p.Y),
                                                  pl.GetCoordinates().Max(p => p.Z));

                                med = (min + max) / 2;
                            }

                            med = med - BC;

                            // Convert DWF sheet coordinates into model coordinates

                            XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0);
                        }
                    }

                    t.Start("DWF Transfer");

                    foreach (Element e in dwfMarkups)
                    {
                        GeometryElement GeoElem = e.get_Geometry(new Options());

                        GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First();

                        GeometryElement gei = gi.GetSymbolGeometry();

                        IList <GeometryObject> gos = new List <GeometryObject>();

                        if (gei.Cast <GeometryObject>().Count(x => x is Arc) == 0)
                        {
                            continue;
                        }

                        foreach (GeometryObject go in gei)
                        {
                            if (go is Arc)
                            {
                                Curve c = go as Curve;

                                XYZ med = c.Evaluate(0.5, true);

                                med = med - BC;

                                XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0);

                                // Warning CS0618:
                                // Autodesk.Revit.Creation.ItemFactoryBase.NewTextNote(
                                //   View, XYZ, XYZ, XYZ, double, TextAlignFlags, string)
                                // is obsolete:
                                // This method is deprecated in Revit 2016.
                                // Please use one of the TextNote.Create methods instead.

                                //doc.Create.NewTextNote( plan,
                                //                       a,
                                //                       XYZ.BasisX,
                                //                       XYZ.BasisY,
                                //                       MMtoFeet( 5 ),
                                //                       TextAlignFlags.TEF_ALIGN_CENTER,
                                //                       activityId );

                                ElementId textTypeId = new FilteredElementCollector(doc)
                                                       .OfClass(typeof(TextNoteType))
                                                       .FirstElementId();

                                TextNote.Create(doc, plan.Id, a, activityId, textTypeId);
                            }
                        }

                        t.Commit();
                    }
                }

                tg.Assimilate();
            }
        }
      /// <summary>
      /// Implementation of the command binding event for the IFC export command.
      /// </summary>
      /// <param name="sender">The event sender (Revit UIApplication).</param>
      /// <param name="args">The arguments (command binding).</param>
      public void OnIFCExport(object sender, CommandEventArgs args)
      {
         try
         {
            // Prepare basic objects
            UIApplication uiApp = sender as UIApplication;
            UIDocument uiDoc = uiApp.ActiveUIDocument;
            Document activeDoc = uiDoc.Document;

            TheDocument = activeDoc;

            // Note that when exporting multiple documents, we are still going to use the configurations from the
            // active document.  
            IFCExportConfigurationsMap configurationsMap = new IFCExportConfigurationsMap();
            configurationsMap.Add(IFCExportConfiguration.GetInSession());
            configurationsMap.AddBuiltInConfigurations();
            configurationsMap.AddSavedConfigurations();

            String mruSelection = null;
            if (m_mruConfiguration != null && configurationsMap.HasName(m_mruConfiguration))
               mruSelection = m_mruConfiguration;

            PotentiallyUpdatedConfigurations = false;
            IFCExport mainWindow = new IFCExport(uiApp, configurationsMap, mruSelection);

            mainWindow.ShowDialog();

            // If user chose to continue
            if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings)
            {
               int docsToExport = mainWindow.DocumentsToExport.Count;

               // This shouldn't happen, but just to be safe.
               if (docsToExport == 0)
                  return;

               bool multipleFiles = docsToExport > 1;

               // prompt for the file name
               SaveFileDialog fileDialog = new SaveFileDialog();
               fileDialog.AddExtension = true;

               String defaultDirectory = m_mruExportPath != null ? m_mruExportPath : null;

               if (defaultDirectory == null)
               {
                  String revitFilePath = TheDocument.PathName;
                  if (!String.IsNullOrEmpty(revitFilePath))
                  {
                     defaultDirectory = Path.GetDirectoryName(revitFilePath);
                  }
               }

               if (defaultDirectory == null)
                  defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

               string defaultExt = mainWindow.GetFileExtension();

               fileDialog.FileName = multipleFiles ? Properties.Resources.MultipleFiles : GenerateFileNameFromDocument(mainWindow.DocumentsToExport[0], null);
               fileDialog.DefaultExt = defaultExt;
               fileDialog.Filter = mainWindow.GetFileFilter();
               fileDialog.InitialDirectory = defaultDirectory;

               bool? fileDialogResult = fileDialog.ShowDialog();

               // If user chooses to continue
               if (fileDialogResult.HasValue && fileDialogResult.Value)
               {
                  // change options
                  IFCExportConfiguration selectedConfig = mainWindow.GetSelectedConfiguration();

                  // Prompt the user for the file location and path
                  String fullName = fileDialog.FileName;
                  String path = Path.GetDirectoryName(fullName);
                  String fileName = multipleFiles ? string.Empty : Path.GetFileName(fullName);

                  // This option should be rarely used, and is only for consistency with old files.  As such, it is set by environment variable only.
                  String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport");
                  bool use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1");

                  string unsuccesfulExports = string.Empty;

                  // In rare occasions, there may be two projects loaded into Revit with the same name.  This isn't supposed to be allowed, but can happen if,
                  // e.g., a user creates a new project, exports it to IFC, and then calls Open IFC.  In this case, if we export both projects, we will overwrite
                  // one of the exports.  Prevent that by keeping track of the exported file names.
                  ISet<string> exportedFileNames = new HashSet<string>();

                  foreach (Document document in mainWindow.DocumentsToExport)
                  {
                     TheDocument = document;

                     // Call this before the Export IFC transaction starts, as it has its own transaction.
                     IFCClassificationMgr.DeleteObsoleteSchemas(document);

                     Transaction transaction = new Transaction(document, "Export IFC");
                     transaction.Start();

                     FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
                     failureOptions.SetClearAfterRollback(false);
                     transaction.SetFailureHandlingOptions(failureOptions);

                     // Normally the transaction will be rolled back, but there are cases where we do update the document.
                     // There is no UI option for this, but these two options can be useful for debugging/investigating
                     // issues in specific file export.  The first one supports export of only one element
                     //exportOptions.AddOption("SingleElement", "174245");
                     // The second one supports export only of a list of elements
                     //exportOptions.AddOption("ElementsForExport", "174245;205427");

                     if (multipleFiles)
                     {
                        fileName = GenerateFileNameFromDocument(document, exportedFileNames) + "." + defaultExt;
                        fullName = path + "\\" + fileName;
                     }

                     // Prepare the export options
                     IFCExportOptions exportOptions = new IFCExportOptions();
                     
                     ElementId activeViewId = GenerateActiveViewIdFromDocument(document);
                     selectedConfig.UpdateOptions(exportOptions, activeViewId);
                     selectedConfig.ActiveViewId = selectedConfig.UseActiveViewGeometry ? activeViewId.IntegerValue : -1;

                     bool result = document.Export(path, fileName, exportOptions);

                     Dictionary<ElementId, string> linksGUIDsCache = new Dictionary<ElementId, string>();
                     if (result)
                     {
                        // Cache for links guids
                        if (selectedConfig.ExportLinkedFiles == true)
                        {
                           Autodesk.Revit.DB.FilteredElementCollector collector = new FilteredElementCollector(document);
                           collector.WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_RvtLinks);
                           System.Collections.Generic.ICollection<ElementId> rvtLinkInstanceIds = collector.ToElementIds();
                           foreach (ElementId linkId in rvtLinkInstanceIds)
                           {
                              Element linkInstance = document.GetElement(linkId);
                              if (linkInstance == null)
                                 continue;
                              Parameter parameter = linkInstance.get_Parameter(BuiltInParameter.IFC_GUID);
                              if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.String)
                              {
                                 String sGUID = parameter.AsString(), sGUIDlower = sGUID.ToLower();
                                 foreach (KeyValuePair<ElementId, string> value in linksGUIDsCache)
                                    if (value.Value.ToLower().IndexOf(sGUIDlower) == 0)
                                       sGUID += "-";
                                 linksGUIDsCache.Add(linkInstance.Id, sGUID);
                              }
                           }
                        }
                     }
                     else
                     {
                        unsuccesfulExports += fullName + "\n";
                     }

                     // Roll back the transaction started earlier, unless certain options are set.
                     if (result && (use2009BuildingStoreyGUIDs || selectedConfig.StoreIFCGUID))
                        transaction.Commit();
                     else
                        transaction.RollBack();

                     // Export links
                     if (selectedConfig.ExportLinkedFiles == true)
                     {
                        exportOptions.AddOption("ExportingLinks", true.ToString());
                        ExportLinkedDocuments(document, fullName, linksGUIDsCache, exportOptions);
                        exportOptions.AddOption("ExportingLinks", false.ToString());
                     }
                  }

                  if (!string.IsNullOrWhiteSpace(unsuccesfulExports))
                  {
                     using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
                     {
                        taskDialog.MainInstruction = string.Format(Properties.Resources.IFCExportProcessError, unsuccesfulExports);
                        taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
                        TaskDialogResult taskDialogResult = taskDialog.Show();
                     }
                  }

                  // Remember last successful export location
                  m_mruExportPath = path;
               }
            }

            // The cancel button should cancel the export, not any "OK"ed setup changes.
            if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings || mainWindow.Result == IFCExportResult.Cancel)
            {
               if (PotentiallyUpdatedConfigurations)
               {
                  configurationsMap = mainWindow.GetModifiedConfigurations();
                  configurationsMap.UpdateSavedConfigurations();
               }

               // Remember last selected configuration
               m_mruConfiguration = mainWindow.GetSelectedConfiguration().Name;
            }
         }
         catch (Exception e)
         {
            using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
            {
               taskDialog.MainInstruction = Properties.Resources.IFCExportProcessGenericError;
               taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
               taskDialog.ExpandedContent = e.ToString();
               TaskDialogResult result = taskDialog.Show();
            }
         }
      }
        public static TaskDialogResult LongRunningTask(Action longRunningTask, string title, Window owner, string content = null, string technicalInformation = null, bool allowHidingWindow = false, bool dirtyCancelationMode = false, bool allowSkip = false)
        {
            bool canceled = false;

            using (new ProfileSection("Long running task"))
            {
                ProfileSection.Argument("longRunningTask", longRunningTask);
                ProfileSection.Argument("title", title);
                ProfileSection.Argument("owner", owner);
                ProfileSection.Argument("content", content);
                ProfileSection.Argument("technicalInformation", technicalInformation);
                ProfileSection.Argument("allowHidingWindow", allowHidingWindow);
                ProfileSection.Argument("dirtyCancelationMode", dirtyCancelationMode);
                ProfileSection.Argument("allowSkip", allowSkip);

                bool isDone = false;
                var  thread = new Thread(() =>
                {
                    using (new ProfileSection("{0} (background thread)".FormatWith(title)))
                    {
                        try
                        {
                            if (!dirtyCancelationMode)
                            {
                                longRunningTask();
                            }
                            else
                            {
                                // this may be required when some of underlying code ignores ThreadAbortException
                                // so we just letting it to complete and just stop waiting
                                var innerDone = false;
                                var async     = new Action(() =>
                                {
                                    longRunningTask();
                                    innerDone = true;
                                });
                                async.BeginInvoke(null, null);

                                // waiting until it is done or ThreadAbortException is thrown
                                while (!innerDone)
                                {
                                    Thread.Sleep(100);
                                }
                            }
                        }
                        catch (ThreadAbortException ex)
                        {
                            Log.Warn(ex, $"Long running task \"{title}\" failed with exception");
                        }
                        catch (Exception ex)
                        {
                            HandleError("Long running task \"{0}\" failed with exception".FormatWith(title), true, ex);
                        }

                        isDone = true;
                    }
                });

                const string Inerrupt = "&Cancel";
                const string Skip     = "&Skip";

                var options = allowSkip ? new[]
                {
                    Inerrupt, Skip
                } : new[]
                {
                    Inerrupt
                };

                // const string hide = "&Hide";
                TaskDialogOptions config = new TaskDialogOptions
                {
                    Owner                   = owner,
                    Title                   = title,
                    MainInstruction         = content ?? title,
                    ExpandedInfo            = technicalInformation ?? string.Empty,
                    CustomButtons           = options, /* ButtonId=500; dialog.ClickCustomButton(0)  }, */ // allowHidingWindow ? new[] { hide /* ButtonId=501 */, inerrupt /* ButtonId=500; dialog.ClickCustomButton(0) */ } :
                    AllowDialogCancellation = true,
                    ShowMarqueeProgressBar  = true,
                    EnableCallbackTimer     = true,
                    Callback                = (dialog, args, obj) =>
                    {
                        switch (args.Notification)
                        {
                        // initialization
                        case VistaTaskDialogNotification.Created:
                            dialog.SetProgressBarMarquee(true, 0); // 0 is ignored
                            break;

                        // dialog is hidden
                        case VistaTaskDialogNotification.ButtonClicked:
                        case VistaTaskDialogNotification.Destroyed:

                            // do not shutdown thread if button Hide was clicked
                            if (thread.IsAlive)
                            {
                                switch (args.ButtonId)
                                {
                                case 500:
                                    thread.Abort();
                                    canceled = true;
                                    break;

                                case 501:
                                    thread.Abort();
                                    break;
                                }
                            }

                            break;

                        case VistaTaskDialogNotification.Timer:
                            dialog.SetContent($"Time elapsed: {TimeSpan.FromMilliseconds(args.TimerTickCount).ToString(@"h\:mm\:ss")}");
                            if (isDone)
                            {
                                dialog.ClickCustomButton(0);
                            }

                            break;
                        }

                        return(false);
                    }
                };

                try
                {
                    thread.Start();
                    var result = TaskDialog.Show(config);
                    return(canceled ? null : result);
                }
                catch (ThreadAbortException)
                {
                }
                catch (Exception ex)
                {
                    HandleError("The long running task caused an exception", true, ex);
                }

                return(null);
            }
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              Application app = uiapp.Application;
              Document doc = uiapp.ActiveUIDocument.Document;
              Categories categories = doc.Settings.Categories;

              int nCategories = categories.Size;

              Debug.Print(
            "{0} categories and their parents obtained "
            + "from the Categories collection:",
            nCategories );

              foreach( Category c in categories )
              {
            Category p = c.Parent;

            Debug.Print( "  {0} ({1}), parent {2}",
              c.Name, c.Id.IntegerValue,
              ( null == p ? "<none>" : p.Name ) );
              }

              Array bics = Enum.GetValues(
            typeof( BuiltInCategory ) );

              int nBics = bics.Length;

              Debug.Print( "{0} built-in categories and the "
            + "corresponding document ones:", nBics );

              Category cat;
              string s;

              List<BuiltInCategory> bics_null
            = new List<BuiltInCategory>();

              List<BuiltInCategory> bics_exception
            = new List<BuiltInCategory>();

              foreach( BuiltInCategory bic in bics )
              {
            try
            {
              cat = categories.get_Item( bic );

              if( null == cat )
              {
            bics_null.Add( bic );
            s = "<null>";
              }
              else
              {
            s = string.Format( "{0} ({1})",
              cat.Name, cat.Id.IntegerValue );
              }
            }
            catch( Exception ex )
            {
              bics_exception.Add( bic );

              s = ex.GetType().Name + " " + ex.Message;
            }
            Debug.Print( "  {0} --> {1}",
              bic.ToString(), s );
              }

              int nBicsNull = bics_null.Count;
              int nBicsException = bics_exception.Count;

            #if ACCESS_HIDDEN_CATEGORIES_THROUGH_FILTERED_ELEMENT_COLLECTOR
              // Trying to use OfClass( typeof( Category ) )
              // throws an ArgumentException exception saying
              // "Input type Category is not a recognized
              // Revit API type".

              IEnumerable<Category> cats
            = new FilteredElementCollector( doc )
              .WhereElementIsNotElementType()
              .WhereElementIsViewIndependent()
              .Cast<Category>();

              // Unable to cast object of type
              // 'Autodesk.Revit.DB.Element' to type
              // 'Autodesk.Revit.DB.Category':

              int nCategoriesFiltered = cats.Count<Category>();

              Debug.Print(
            "{0} categories obtained from a filtered "
            + "element collector:",
            nCategoriesFiltered );

              foreach( Category c in cats )
              {
            Debug.Print( "  {0}", c.Name );
              }
            #endif // ACCESS_HIDDEN_CATEGORIES_THROUGH_FILTERED_ELEMENT_COLLECTOR

              TaskDialog dlg = new TaskDialog(
            "Hidden Built-in Categories" );

              s = string.Format(
            "{0} categories obtained from the Categories collection;\r\n"
            + "{1} built-in categories;\r\n"
            + "{2} built-in categories retrieve null result;\r\n"
            + "{3} built-in categories throw an exception:\r\n",
            nCategories, nBics, nBicsNull, nBicsException );

              Debug.Print( s );

              dlg.MainInstruction = s;

              s = bics_exception
            .Aggregate<BuiltInCategory, string>(
              string.Empty,
              ( a, bic ) => a + "\n" + bic.ToString() );

              Debug.Print( s );

              dlg.MainContent = s;

              dlg.Show();

              return Result.Succeeded;
        }
Beispiel #38
0
        //Macro Command
        //Adds Project Parameters from Shared Parameter file to (Hard Coded) categories indicated
        public void C_AddProjectSharedParameters()
        {
            //Autodesk.Revit.ApplicationServices.Application app = new Autodesk.Revit.ApplicationServices.Application();

            Document      doc   = this.Document;
            UIApplication uiapp = this.Application;

            DefinitionFile defFile = uiapp.Application.OpenSharedParameterFile();

            // Create a category set and insert category "XX" to it
            CategorySet myCategories = uiapp.Application.Create.NewCategorySet();
            // Use BuiltInCategory to get relevant categories
            //Category myCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_ElectricalCircuit);
            Category myCategory1 = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Conduit);
            Category myCategory2 = doc.Settings.Categories.get_Item(BuiltInCategory.OST_ConduitFitting);

            myCategories.Insert(myCategory1);
            myCategories.Insert(myCategory2);

            //debug show the category
            foreach (Category cat in myCategories)
            {
                //TaskDialog.Show("Categories", cat.Name);
            }
            //Create an object of InstanceBinding according to the Categories
            InstanceBinding instanceBinding = uiapp.Application.Create.NewInstanceBinding(myCategories);

            // Get the BingdingMap of current document.
            BindingMap bindingMap = doc.ParameterBindings;

            //get the group
            //TODO: select this from a dialog later, hard coding not ideal.
            DefinitionGroup myGroup = GetOrCreateSharedParamsGroup(defFile, "FD_Conduit_Feeders");

            //get the definitions
            //Definition def = GetOrCreateSharedParamsDefinition(myGroup, ParameterType.Text, "FD_FEEDER DESIGNATOR");

            //Bind the definitions to the document
            //transaction
            Transaction trans = new Transaction(doc);

            trans.Start("Binding Project Shared Parameters");

            //bool typeBindOK = bindingMap.Insert(def, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
            bool typeBindOK = false;

            // iterate the defs in group
            foreach (Definition definition in myGroup.Definitions)
            {
                // get definition name
                //TaskDialog.Show("Definition Name: ", definition.Name);
                //add paremeters under the construction group in the Revti UI
                typeBindOK = bindingMap.Insert(definition, instanceBinding, BuiltInParameterGroup.PG_CONSTRUCTION);
            }

            trans.Commit();

            if (typeBindOK)
            {
                TaskDialog.Show("Type Binding", "Success, on creating Project Shared Parameters");
            }
            else
            {
                TaskDialog.Show("Type Binding", "No Shared Parameters added. Either they exist already or Shared Parameter file not created");
            }
        }
Beispiel #39
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument uidoc = app.ActiveUIDocument;
                Document   doc   = uidoc.Document;
                //Selection m_elementsToHide = uidoc.Selection; //SelElementSet.Create();

                List <ElementId> elementsToBeIsolated = new List <ElementId>();
                List <ElementId> elementsToBeHidden   = new List <ElementId>();
                List <ElementId> elementsToBeSelected = new List <ElementId>();



                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.ViewToWorldScale == null || v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = UnitUtils.ConvertToInternalUnits(v.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z);
                    var CameraViewPoint = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z);
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);


                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        View3D ActiveView3D = doc.ActiveView as View3D;
                        if (!ActiveView3D.IsPerspective)
                        {
                            orthoView = ActiveView3D;
                        }
                    }
                    if (orthoView == null)
                    {
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        //try to use default 3D view
                        if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").Any())
                        {
                            orthoView = viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").First();
                        }
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new 3d ortho view
                            if (orthoView == null)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = "BCFortho";
                            }

                            orthoView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            orthoView.SetOrientation(orient3d);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = touple.Item2
                    // **** CUSTOM VALUE FOR TEKLA **** //
                    double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;
                    double x       = zoom / customZoomValue;
                    XYZ    m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ    m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }

                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.FieldOfView == null || v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var    zoom   = v.PerspectiveCamera.FieldOfView;
                    double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                    double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                    double factor = z1 - z;

                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z);
                    XYZ oldO            = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z);
                    var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);



                    View3D perspView = null;

                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "BCFpersp").Any())
                    {
                        perspView = viewcollector3D.Where(o => o.Name == "BCFpersp").First();
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = "BCFpersp";
                            }

                            perspView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            perspView.SetOrientation(orient3d);

                            // turn on the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(1);
                            }
                            // reset far clip offset
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).HasValue)
                            {
                                Parameter m_farClipOffset = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR);
                                m_farClipOffset.SetValueString("35");
                            }
                            // turn off the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                else if (v.SheetCamera != null)//sheet
                {
                    //using (Transaction trans = new Transaction(uidoc.Document))
                    //{
                    //    if (trans.Start("Open sheet view") == TransactionStatus.Started)
                    //    {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("No Sheet with Id=" + v.SheetCamera.SheetID + " found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                    uidoc.RefreshActiveView();

                    //        trans.Commit();
                    //    }
                    //}
                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y,
                                          v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y,
                                          v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                else
                {
                    return;
                }

                //apply BCF clipping planes to Revit section box
                View3D view3D = doc.ActiveView as View3D;
                if (view3D != null)
                {
                    if (v.ClippingPlanes != null)
                    {
                        if (v.ClippingPlanes.Count() > 0)
                        {
                            var result = getBoundingBoxFromClippingPlanes(doc, v.ClippingPlanes);

                            if (result != null)
                            {
                                BoundingBoxXYZ computedBox = result.Item1;
                                Transform      rotate      = result.Item2;

                                using (Transaction trans = new Transaction(uidoc.Document))
                                {
                                    if (trans.Start("Apply Section Box") == TransactionStatus.Started)
                                    {
                                        view3D.IsSectionBoxActive = true;
                                        view3D.SetSectionBox(computedBox);

                                        if (rotate != null)
                                        {
                                            // Transform the View3D's section box with the rotation transform
                                            computedBox.Transform = computedBox.Transform.Multiply(rotate);

                                            // Set the section box back to the view (requires an open transaction)
                                            view3D.SetSectionBox(computedBox);
                                        }
                                    }
                                    trans.Commit();
                                }
                            }
                        }
                    }
                }

                //select/hide elements
                if (v.Components != null && v.Components.Any())
                {
                    if (v.Components.Count > 100)
                    {
                        var result = MessageBox.Show("Too many elements attached. It may take for a while to isolate/select them. Do you want to continue?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.No)
                        {
                            uidoc.RefreshActiveView();
                            return;
                        }
                    }

                    FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                    System.Collections.Generic.ICollection <ElementId> collection = collector.ToElementIds();
                    foreach (var e in v.Components)
                    {
                        var bcfguid         = IfcGuid.FromIfcGUID(e.IfcGuid);
                        int authoringToolId = string.IsNullOrWhiteSpace(e.AuthoringToolId) ? -1 : int.Parse(e.AuthoringToolId);
                        var ids             = collection.Where(o => bcfguid == ExportUtils.GetExportId(doc, o) | authoringToolId == Convert.ToInt32(doc.GetElement(o).UniqueId.Substring(37), 16));
                        if (ids.Any())
                        {
                            // handle visibility
                            if (e.Visible)
                            {
                                elementsToBeIsolated.Add(ids.First());
                            }
                            else
                            {
                                elementsToBeHidden.Add(ids.First());
                            }

                            // handle selection
                            if (e.Selected)
                            {
                                elementsToBeSelected.Add(ids.First());
                            }
                        }
                    }

                    if (elementsToBeHidden.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Hide Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.HideElementsTemporary(elementsToBeHidden);
                            }
                            trans.Commit();
                        }
                    }
                    else if (elementsToBeIsolated.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Isolate Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.IsolateElementsTemporary(elementsToBeIsolated);
                            }
                            trans.Commit();
                        }
                    }

                    if (elementsToBeSelected.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Select Elements") == TransactionStatus.Started)
                            {
                                uidoc.Selection.SetElementIds(elementsToBeSelected);
                            }
                            trans.Commit();
                        }
                    }
                }

                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
Beispiel #40
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Document doc = uidoc.Document;

              // Create dictionary of existing
              // materials keyed by their name.

              Dictionary<string, Material> materials
            = new FilteredElementCollector( doc )
              .OfClass( typeof( Material ) )
              .Cast<Material>()
              .ToDictionary<Material, string>(
            e => e.Name );

              // Ditto for fill patterns.

              Dictionary<string, FillPatternElement> fillPatterns
            = new FilteredElementCollector( doc )
              .OfClass( typeof( FillPatternElement ) )
              .Cast<FillPatternElement>()
              .ToDictionary<FillPatternElement, string>(
            e => e.Name );

              try
              {
            var materialsToImport = ReadMaterialsFromXlsx( materials, fillPatterns ).ToList();
            var browser = new MaterialBrowserViewModel { Materials = materialsToImport };
            var window = new MaterialsView { DataContext = browser };
            var res = window.ShowDialog();
            if( !res.HasValue || !res.Value )
              return Result.Cancelled;

            var materialsToAdd = browser.Materials.Where( x => x.AddToProject ).ToList();
            if( !materialsToAdd.Any() )
              return Result.Cancelled;

            using( var tx = new Transaction( doc ) )
            {
              tx.Start( "Add Materials" );
              foreach( var materialViewModel in materialsToAdd )
              {
            var materialCSI = materials[materialViewModel.BaseMaterialClass];
            var myMaterial = materialCSI.Duplicate( materialViewModel.Name );
            myMaterial.Color = materialViewModel.Color;
            myMaterial.Transparency = (int) materialViewModel.Transparency;
            if( materialViewModel.SurfacePattern != null )
              myMaterial.SurfacePatternId
                = fillPatterns[materialViewModel.SurfacePattern.Name].Id;
            if( materialViewModel.CutPattern != null )
              myMaterial.CutPatternId
                = fillPatterns[materialViewModel.CutPattern.Name].Id;
              }
              tx.Commit();
            }

            string msg = string.Format(
              "{0} row{1} successfully parsed and "
              + "{2} material{3} added:",
              materialsToImport.Count,
              PluralSuffix( materialsToImport.Count ),
              materialsToAdd.Count,
              PluralSuffix( materialsToAdd.Count ) );

            TaskDialog dlg = new TaskDialog(
            "Revit AddMaterials" );

            dlg.MainInstruction = msg;

            dlg.MainContent = string.Join( ", ",
              materialsToAdd.Select( x => x.Name ) ) + ".";

            dlg.Show();
              }
              catch( Exception ex )
              {
            message
              = "Revit AddMaterials Exception:\n" + ex;

            return Result.Failed;
              }
              return Result.Succeeded;
        }
Beispiel #41
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            // Extract and group the data from Revit in a
            // dictionary, where the key is the category
            // name and the value is a list of elements.

            Stopwatch sw = Stopwatch.StartNew();

            Dictionary <string, List <Element> > sortedElements
                = new Dictionary <string, List <Element> >();

            // Iterate over all elements, both symbols and
            // model elements, and them in the dictionary.

            ElementFilter f = new LogicalOrFilter(
                new ElementIsElementTypeFilter(false),
                new ElementIsElementTypeFilter(true));

            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .WherePasses(f);

            string name;

            foreach (Element e in collector)
            {
                Category category = e.Category;

                if (null != category)
                {
                    name = category.Name;

                    // If this category was not yet encountered,
                    // add it and create a new container for its
                    // elements.

                    if (!sortedElements.ContainsKey(name))
                    {
                        sortedElements.Add(name,
                                           new List <Element>());
                    }
                    sortedElements[name].Add(e);
                }
            }

            // Launch or access Excel via COM Interop:

            X.Application excel = new X.Application();

            if (null == excel)
            {
                LabUtils.ErrorMsg(
                    "Failed to get or start Excel.");

                return(Result.Failed);
            }
            excel.Visible = true;

            X.Workbook workbook = excel.Workbooks.Add(
                Missing.Value);

            X.Worksheet worksheet;

            // We cannot delete all work sheets,
            // Excel requires at least one.
            //
            //while( 1 < workbook.Sheets.Count )
            //{
            //  worksheet = workbook.Sheets.get_Item(1) as X.Worksheet;
            //  worksheet.Delete();
            //}

            // Loop through all collected categories and
            // create a worksheet for each except the first.
            // We sort the categories and work trough them
            // from the end, since the worksheet added last
            // shows up first in the Excel tab.

            List <string> keys = new List <string>(
                sortedElements.Keys);

            keys.Sort();
            keys.Reverse();

            bool first = true;

            int nElements   = 0;
            int nCategories = keys.Count;

            foreach (string categoryName in keys)
            {
                List <Element> elementSet
                    = sortedElements[categoryName];

                // Create and name the worksheet

                if (first)
                {
                    worksheet = workbook.Sheets.get_Item(1)
                                as X.Worksheet;

                    first = false;
                }
                else
                {
                    worksheet = excel.Worksheets.Add(
                        Missing.Value, Missing.Value,
                        Missing.Value, Missing.Value)
                                as X.Worksheet;
                }

                name = (31 < categoryName.Length)
          ? categoryName.Substring(0, 31)
          : categoryName;

                name = name
                       .Replace(':', '_')
                       .Replace('/', '_');

                worksheet.Name = name;

                // Determine the names of all parameters
                // defined for the elements in this set.

                List <string> paramNames = new List <string>();

                foreach (Element e in elementSet)
                {
                    ParameterSet parameters = e.Parameters;

                    foreach (Parameter parameter in parameters)
                    {
                        name = parameter.Definition.Name;

                        if (!paramNames.Contains(name))
                        {
                            paramNames.Add(name);
                        }
                    }
                }
                paramNames.Sort();

                // Add the header row in bold.

                worksheet.Cells[1, 1] = "ID";
                worksheet.Cells[1, 2] = "IsType";

                int column = 3;

                foreach (string paramName in paramNames)
                {
                    worksheet.Cells[1, column] = paramName;
                    ++column;
                }
                var range = worksheet.get_Range("A1", "Z1");

                range.Font.Bold = true;
                range.EntireColumn.AutoFit();

                int row = 2;

                foreach (Element e in elementSet)
                {
                    // First column is the element id,
                    // second a flag indicating type (symbol)
                    // or not, both displayed as an integer.

                    worksheet.Cells[row, 1] = e.Id.IntegerValue;

                    worksheet.Cells[row, 2] = (e is ElementType)
            ? 1
            : 0;

                    column = 3;

                    string paramValue;

                    foreach (string paramName in paramNames)
                    {
                        paramValue = "*NA*";

                        //Parameter p = e.get_Parameter( paramName ); // 2014

                        // Careful! This returns the first best param found.

                        Parameter p = e.LookupParameter(paramName); // 2015

                        if (null != p)
                        {
                            //try
                            //{
                            paramValue
                                = LabUtils.GetParameterValue(p);
                            //}
                            //catch( Exception ex )
                            //{
                            //  Debug.Print( ex.Message );
                            //}
                        }

                        worksheet.Cells[row, column++]
                            = paramValue;
                    } // column

                    ++nElements;
                    ++row;
                } // row
            }     // category == worksheet


            sw.Stop();

            TaskDialog.Show("Parameter Export",
                            string.Format(
                                "{0} categories and a total "
                                + "of {1} elements exported "
                                + "in {2:F2} seconds.",
                                nCategories, nElements,
                                sw.Elapsed.TotalSeconds));

            return(Result.Succeeded);
        }
Beispiel #42
0
        private void ModifyObjects(List<RevitObject> existingObjects, List<ElementId> existingElems, Document doc, Guid uniqueId, bool profileWarning, string nickName, int runId)
        {
            // Create new Revit objects.
            //List<LyrebirdId> newUniqueIds = new List<LyrebirdId>();

            // Determine what kind of object we're creating.
            RevitObject ro = existingObjects[0];


            #region Normal Origin based FamilyInstance
            // Modify origin based family instances
            if (ro.Origin != null)
            {
                // Find the FamilySymbol
                FamilySymbol symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc);

                LevelType lt = FindLevelType(ro.TypeName, doc);

                GridType gt = FindGridType(ro.TypeName, doc);

                if (symbol != null || lt != null)
                {
                    // Get the hosting ID from the family.
                    Family fam = null;
                    Parameter hostParam = null;
                    int hostBehavior = 0;

                    try
                    {
                        fam = symbol.Family;
                        hostParam = fam.get_Parameter(BuiltInParameter.FAMILY_HOSTING_BEHAVIOR);
                        hostBehavior = hostParam.AsInteger();
                    }
                    catch{}

                    //FamilyInstance existingInstance = doc.GetElement(existingElems[0]) as FamilyInstance;
                    
                    using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects"))
                    {
                        t.Start();
                        try
                        {
                            Schema instanceSchema = null;
                            try
                            {
                                instanceSchema = Schema.Lookup(instanceSchemaGUID);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                            if (instanceSchema == null)
                            {
                                SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID);
                                sb.SetWriteAccessLevel(AccessLevel.Vendor);
                                sb.SetReadAccessLevel(AccessLevel.Public);
                                sb.SetVendorId("LMNA");

                                // Create the field to store the data in the family
                                FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string));
                                guidFB.SetDocumentation("Component instance GUID from Grasshopper");
                                // Create a filed to store the run number
                                FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int));
                                runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data");
                                // Create a field to store the GH component nickname.
                                FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string));
                                nickNameFB.SetDocumentation("Component NickName from Grasshopper");

                                sb.SetSchemaName("LMNAInstanceGUID");
                                instanceSchema = sb.Finish();
                            }

                            FamilyInstance fi = null;
                            XYZ origin = XYZ.Zero;

                            if (lt != null)
                            {
                                for (int i = 0; i < existingObjects.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];
                                    Level lvl = doc.GetElement(existingElems[i]) as Level;

                                    if (lvl.ProjectElevation != (UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT)))
                                    {
                                        double offset = lvl.Elevation - lvl.ProjectElevation;
                                        lvl.Elevation = (UnitUtils.ConvertToInternalUnits(obj.Origin.Z + offset, lengthDUT));
                                    }

                                    SetParameters(lvl, obj.Parameters, doc);
                                }
                            }
                            else if (hostBehavior == 0)
                            {

                                for (int i = 0; i < existingObjects.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];
                                    fi = doc.GetElement(existingElems[i]) as FamilyInstance;

                                    // Change the family and symbol if necessary
                                    if (fi != null && (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name))
                                    {
                                        try
                                        {
                                            fi.Symbol = symbol;
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                    }

                                    try
                                    {
                                        // Move family
                                        origin = new XYZ(UnitUtils.ConvertToInternalUnits(obj.Origin.X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT));
                                        if (fi != null)
                                        {
                                            LocationPoint lp = fi.Location as LocationPoint;
                                            if (lp != null)
                                            {
                                                XYZ oldLoc = lp.Point;
                                                XYZ translation = origin.Subtract(oldLoc);
                                                ElementTransformUtils.MoveElement(doc, fi.Id, translation);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        TaskDialog.Show("Error", ex.Message);
                                    }

                                    // Rotate
                                    if (obj.Orientation != null)
                                    {
                                        if (Math.Round(Math.Abs(obj.Orientation.Z - 0), 10) < double.Epsilon)
                                        {
                                            XYZ orientation = fi.FacingOrientation;
                                            orientation = orientation.Multiply(-1);
                                            XYZ incomingOrientation = new XYZ(obj.Orientation.X, obj.Orientation.Y, obj.Orientation.Z);
                                            XYZ normalVector = new XYZ(0, -1, 0);

                                            double currentAngle = 0;
                                            if (orientation.X < 0 && orientation.Y < 0)
                                            {
                                                currentAngle = (2 * Math.PI) - normalVector.AngleTo(orientation);
                                            }
                                            else if (orientation.Y == 0 && orientation.X < 0)
                                            {
                                                currentAngle = 1.5 * Math.PI;
                                            }
                                            else if (orientation.X < 0)
                                            {
                                                currentAngle = (Math.PI - normalVector.AngleTo(orientation)) + Math.PI;
                                            }
                                            else
                                            {
                                                currentAngle = normalVector.AngleTo(orientation);
                                            }

                                            double incomingAngle = 0;
                                            if (incomingOrientation.X < 0 && incomingOrientation.Y < 0)
                                            {
                                                incomingAngle = (2 * Math.PI) - normalVector.AngleTo(incomingOrientation);
                                            }
                                            else if (incomingOrientation.Y == 0 && incomingOrientation.X < 0)
                                            {
                                                incomingAngle = 1.5 * Math.PI;
                                            }
                                            else if (incomingOrientation.X < 0)
                                            {
                                                incomingAngle = (Math.PI - normalVector.AngleTo(incomingOrientation)) + Math.PI;
                                            }
                                            else
                                            {
                                                incomingAngle = normalVector.AngleTo(incomingOrientation);
                                            }
                                            double angle = incomingAngle - currentAngle;
                                            //TaskDialog.Show("Test", "CurrentAngle: " + currentAngle.ToString() + "\nIncoming Angle: " + incomingAngle.ToString() + "\nResulting Rotation: " + angle.ToString() +
                                            //    "\nFacingOrientation: " + orientation.ToString() + "\nIncoming Orientation: " + incomingOrientation.ToString());
                                            Line axis = Line.CreateBound(origin, origin + XYZ.BasisZ);
                                            ElementTransformUtils.RotateElement(doc, fi.Id, axis, angle);
                                        }
                                    }

                                    SetParameters(fi, obj.Parameters, doc);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < existingObjects.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];
                                    fi = doc.GetElement(existingElems[i]) as FamilyInstance;

                                    // Change the family and symbol if necessary
                                    if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name)
                                    {
                                        try
                                        {
                                            fi.Symbol = symbol;
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                    }

                                    origin = new XYZ(UnitUtils.ConvertToInternalUnits(obj.Origin.X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT));

                                    // Find the level
                                    List<LyrebirdPoint> lbPoints = new List<LyrebirdPoint> { obj.Origin };
                                    Level lvl = GetLevel(lbPoints, doc);

                                    // Get the host
                                    if (hostBehavior == 5)
                                    {
                                        // Face based family.  Find the face and create the element
                                        XYZ normVector = new XYZ(obj.Orientation.X, obj.Orientation.Y, obj.Orientation.Z);
                                        XYZ faceVector;
                                        if (obj.FaceOrientation != null)
                                        {
                                            faceVector = new XYZ(obj.FaceOrientation.X, obj.FaceOrientation.Y, obj.FaceOrientation.Z);
                                        }
                                        else
                                        {
                                            faceVector = XYZ.BasisZ;
                                        }
                                        Face face = FindFace(origin, normVector, doc);
                                        if (face != null)
                                        {
                                            if (face.Reference.ElementId == fi.HostFace.ElementId)
                                            {
                                                //fi = doc.Create.NewFamilyInstance(face, origin, faceVector, symbol);
                                                // Just move the host and update the parameters as needed.
                                                LocationPoint lp = fi.Location as LocationPoint;
                                                if (lp != null)
                                                {
                                                    XYZ oldLoc = lp.Point;
                                                    XYZ translation = origin.Subtract(oldLoc);
                                                    ElementTransformUtils.MoveElement(doc, fi.Id, translation);
                                                }

                                                SetParameters(fi, obj.Parameters, doc);
                                            }
                                            else
                                            {
                                                FamilyInstance origInst = fi;
                                                fi = doc.Create.NewFamilyInstance(face, origin, faceVector, symbol);

                                                foreach (Parameter p in origInst.Parameters)
                                                {
                                                    try
                                                    {
                                                        Parameter newParam = fi.get_Parameter(p.GUID);
                                                        if (newParam != null)
                                                        {
                                                            switch (newParam.StorageType)
                                                            {
                                                                case StorageType.Double:
                                                                    newParam.Set(p.AsDouble());
                                                                    break;
                                                                case StorageType.ElementId:
                                                                    newParam.Set(p.AsElementId());
                                                                    break;
                                                                case StorageType.Integer:
                                                                    newParam.Set(p.AsInteger());
                                                                    break;
                                                                case StorageType.String:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                                default:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }
                                                // Delete the original instance of the family
                                                doc.Delete(origInst.Id);

                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);

                                                // Assign the GH InstanceGuid
                                                AssignGuid(fi, uniqueId, instanceSchema, runId, nickName);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // typical hosted family.  Can be wall, floor, roof or ceiling.
                                        ElementId host = FindHost(origin, hostBehavior, doc);
                                        if (host != null)
                                        {
                                            if (host.IntegerValue != fi.Host.Id.IntegerValue)
                                            {
                                                // We'll have to recreate the element
                                                FamilyInstance origInst = fi;
                                                fi = doc.Create.NewFamilyInstance(origin, symbol, doc.GetElement(host), lvl, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                                                foreach (Parameter p in origInst.Parameters)
                                                {
                                                    try
                                                    {
                                                        Parameter newParam = fi.LookupParameter(p.Definition.Name);
                                                        if (newParam != null)
                                                        {
                                                            switch (newParam.StorageType)
                                                            {
                                                                case StorageType.Double:
                                                                    newParam.Set(p.AsDouble());
                                                                    break;
                                                                case StorageType.ElementId:
                                                                    newParam.Set(p.AsElementId());
                                                                    break;
                                                                case StorageType.Integer:
                                                                    newParam.Set(p.AsInteger());
                                                                    break;
                                                                case StorageType.String:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                                default:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }
                                                // Delete the original instance of the family
                                                doc.Delete(origInst.Id);

                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);

                                                // Assign the GH InstanceGuid
                                                AssignGuid(fi, uniqueId, instanceSchema, runId, nickName);
                                            }

                                            else
                                            {
                                                // Just move the host and update the parameters as needed.
                                                LocationPoint lp = fi.Location as LocationPoint;
                                                if (lp != null)
                                                {
                                                    XYZ oldLoc = lp.Point;
                                                    XYZ translation = origin.Subtract(oldLoc);
                                                    ElementTransformUtils.MoveElement(doc, fi.Id, translation);
                                                }

                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);
                                            }
                                        }
                                    }

                                    // Assign the parameters
                                    SetParameters(fi, obj.Parameters, doc);
                                }
                                // delete the host finder
                                ElementId hostFinderFamily = hostFinder.Symbol.Family.Id;
                                doc.Delete(hostFinder.Id);
                                doc.Delete(hostFinderFamily);
                                hostFinder = null;
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }

                        t.Commit();
                    }
                }
            }

            #endregion


            #region Adaptive Components
            FamilyInstance adaptInst;
            try
            {
                adaptInst = doc.GetElement(existingElems[0]) as FamilyInstance;
            }
            catch
            {
                adaptInst = null;
            }
            if (adaptInst != null && AdaptiveComponentInstanceUtils.IsAdaptiveComponentInstance(adaptInst))
            {
                // Find the FamilySymbol
                FamilySymbol symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc);

                if (symbol != null)
                {
                    using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects"))
                    {
                        t.Start();
                        try
                        {
                            // Create the Schema for the instances to store the GH Component InstanceGUID and the path
                            Schema instanceSchema = null;
                            try
                            {
                                instanceSchema = Schema.Lookup(instanceSchemaGUID);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                            if (instanceSchema == null)
                            {
                                SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID);
                                sb.SetWriteAccessLevel(AccessLevel.Vendor);
                                sb.SetReadAccessLevel(AccessLevel.Public);
                                sb.SetVendorId("LMNA");

                                // Create the field to store the data in the family
                                FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string));
                                guidFB.SetDocumentation("Component instance GUID from Grasshopper");
                                // Create a filed to store the run number
                                FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int));
                                runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data");
                                // Create a field to store the GH component nickname.
                                FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string));
                                nickNameFB.SetDocumentation("Component NickName from Grasshopper");

                                sb.SetSchemaName("LMNAInstanceGUID");
                                instanceSchema = sb.Finish();
                            }

                            try
                            {
                                for (int i = 0; i < existingElems.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];

                                    FamilyInstance fi = doc.GetElement(existingElems[i]) as FamilyInstance;

                                    // Change the family and symbol if necessary
                                    if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name)
                                    {
                                        try
                                        {
                                            fi.Symbol = symbol;
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                    }

                                    IList<ElementId> placePointIds = new List<ElementId>();
                                    placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(fi);

                                    for (int ptNum = 0; ptNum < obj.AdaptivePoints.Count; ptNum++)
                                    {
                                        try
                                        {
                                            ReferencePoint rp = doc.GetElement(placePointIds[ptNum]) as ReferencePoint;
                                            XYZ pt = new XYZ(UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].Z, lengthDUT));
                                            XYZ vector = pt.Subtract(rp.Position);
                                            ElementTransformUtils.MoveElement(doc, rp.Id, vector);
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.WriteLine(ex.Message);
                                        }
                                    }

                                    // Assign the parameters
                                    SetParameters(fi, obj.Parameters, doc);
                                }

                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }
                        t.Commit();
                    }
                }

            }

            #endregion


            #region Curve based components
            if (ro.Curves != null && ro.Curves.Count > 0)
            {
                // Find the FamilySymbol
                FamilySymbol symbol = null;
                WallType wallType = null;
                FloorType floorType = null;
                RoofType roofType = null;
                GridType gridType = null;
                bool typeFound = false;

                FilteredElementCollector famCollector = new FilteredElementCollector(doc);

                if (ro.CategoryId == -2000011)
                {
                    famCollector.OfClass(typeof(WallType));
                    foreach (WallType wt in famCollector)
                    {
                        if (wt.Name == ro.TypeName)
                        {
                            wallType = wt;
                            typeFound = true;
                            break;
                        }
                    }
                }
                else if (ro.CategoryId == -2000032)
                {
                    famCollector.OfClass(typeof(FloorType));
                    foreach (FloorType ft in famCollector)
                    {
                        if (ft.Name == ro.TypeName)
                        {
                            floorType = ft;
                            typeFound = true;
                            break;
                        }
                    }
                }
                else if (ro.CategoryId == -2000035)
                {
                    famCollector.OfClass(typeof(RoofType));
                    foreach (RoofType rt in famCollector)
                    {
                        if (rt.Name == ro.TypeName)
                        {
                            roofType = rt;
                            typeFound = true;
                            break;
                        }
                    }
                }
                else if (ro.CategoryId == -2000220)
                {
                    famCollector.OfClass(typeof(GridType));
                    foreach (GridType gt in famCollector)
                    {
                        if (gt.Name == ro.TypeName)
                        {
                            gridType = gt;
                            typeFound = true;
                            break;
                        }
                    }
                }
                else
                {
                    symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc);
                    if (symbol != null)
                        typeFound = true;
                }



                if (typeFound)
                {
                    
                    using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects"))
                    {
                        t.Start();
                        try
                        {
                            // Create the Schema for the instances to store the GH Component InstanceGUID and the path
                            Schema instanceSchema = null;
                            try
                            {
                                instanceSchema = Schema.Lookup(instanceSchemaGUID);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
                            if (instanceSchema == null)
                            {
                                SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID);
                                sb.SetWriteAccessLevel(AccessLevel.Vendor);
                                sb.SetReadAccessLevel(AccessLevel.Public);
                                sb.SetVendorId("LMNA");

                                // Create the field to store the data in the family
                                FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string));
                                guidFB.SetDocumentation("Component instance GUID from Grasshopper");
                                // Create a filed to store the run number
                                FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int));
                                runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data");
                                // Create a field to store the GH component nickname.
                                FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string));
                                nickNameFB.SetDocumentation("Component NickName from Grasshopper");

                                sb.SetSchemaName("LMNAInstanceGUID");
                                instanceSchema = sb.Finish();
                            }
                            FamilyInstance fi = null;
                            Grid grid = null;
                            
                            try
                            {
                                bool supress = Properties.Settings.Default.suppressWarning;
                                bool supressedReplace = false;
                                bool supressedModify = true;
                                for (int i = 0; i < existingObjects.Count; i++)
                                {
                                    RevitObject obj = existingObjects[i];
                                    if (obj.CategoryId != -2000011 && obj.CategoryId != -2000032 && obj.CategoryId != -2000035 && obj.CategoryId != -2000220)
                                    {
                                        fi = doc.GetElement(existingElems[i]) as FamilyInstance;

                                        // Change the family and symbol if necessary
                                        if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name)
                                        {
                                            try
                                            {
                                                fi.Symbol = symbol;
                                            }
                                            catch (Exception ex)
                                            {
                                                Debug.WriteLine(ex.Message);
                                            }
                                        }
                                    }
                                    else if (obj.CategoryId == -2000220)
                                    {
                                        grid = doc.GetElement(existingElems[i]) as Grid;

                                        // Get the grid location and compare against the incoming curve
                                        Curve gridCrv = grid.Curve;
                                        LyrebirdCurve lbc = obj.Curves[0];
                                        try
                                        {
                                            Arc arc = gridCrv as Arc;
                                            if (arc != null && lbc.CurveType == "Arc")
                                            {
                                                // Test that the arcs are similar
                                                XYZ startPoint = arc.GetEndPoint(0);
                                                XYZ endPoint = arc.GetEndPoint(1);
                                                XYZ centerPoint = arc.Center;
                                                double rad = arc.Radius;

                                                XYZ lbcStartPt = new XYZ(lbc.ControlPoints[0].X, lbc.ControlPoints[0].Y, lbc.ControlPoints[0].Z);
                                                XYZ lbcEndPt = new XYZ(lbc.ControlPoints[1].X, lbc.ControlPoints[1].Y, lbc.ControlPoints[1].Z);
                                                XYZ lbcMidPt = new XYZ(lbc.ControlPoints[2].X, lbc.ControlPoints[2].Y, lbc.ControlPoints[2].Z);
                                                Arc lbcArc = Arc.Create(lbcStartPt, lbcEndPt, lbcMidPt);
                                                XYZ lbcCenterPt = lbcArc.Center;
                                                double lbcRad = lbcArc.Radius;

                                                if (centerPoint.DistanceTo(lbcCenterPt) < 0.001 && lbcRad == rad && startPoint.DistanceTo(lbcStartPt) < 0.001)
                                                {
                                                    // Do not create
                                                }
                                                else
                                                {
                                                    // Delete the grid and rebuild it with the new curve.
                                                }
                                            }
                                            else
                                            {
                                                // Probably need to rebuild the curve
                                            }
                                        }
                                        catch { }


                                        try
                                        {
                                            Line line = gridCrv as Line;
                                            if (line != null && lbc.CurveType == "Line")
                                            {
                                                // Test that the arcs are similar
                                                XYZ startPoint = line.GetEndPoint(0);
                                                XYZ endPoint = line.GetEndPoint(1);

                                                XYZ lbcStartPt = new XYZ(lbc.ControlPoints[0].X, lbc.ControlPoints[0].Y, lbc.ControlPoints[0].Z);
                                                XYZ lbcEndPt = new XYZ(lbc.ControlPoints[1].X, lbc.ControlPoints[1].Y, lbc.ControlPoints[1].Z);

                                                if (endPoint.DistanceTo(lbcEndPt) < 0.001 && startPoint.DistanceTo(lbcStartPt) < 0.001)
                                                {
                                                    // Do not create
                                                }
                                                else
                                                {
                                                    // Delete the grid and rebuild it with the new curve.
                                                }
                                            }
                                            else
                                            {
                                                // Probably need to rebuild the curve
                                            }
                                        }
                                        catch { }

                                        if (grid.GridType.Name != gridType.Name)
                                        {
                                            try
                                            {
                                                grid.GridType = gridType;
                                            }
                                            catch (Exception ex)
                                            {
                                                TaskDialog.Show("Error", ex.Message);
                                                Debug.WriteLine(ex.Message);
                                            }
                                        }
                                    }
                                    #region single line based family
                                    if (obj.Curves.Count == 1 && obj.Curves[0].CurveType != "Circle")
                                    {

                                        LyrebirdCurve lbc = obj.Curves[0];
                                        List<LyrebirdPoint> curvePoints = lbc.ControlPoints.OrderBy(p => p.Z).ToList();
                                        // linear
                                        // can be a wall or line based family.

                                        // Wall objects
                                        if (obj.CategoryId == -2000011)
                                        {
                                            // draw a wall
                                            Curve crv = null;
                                            if (lbc.CurveType == "Line")
                                            {
                                                XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                crv = Line.CreateBound(pt1, pt2);
                                            }
                                            else if (lbc.CurveType == "Arc")
                                            {
                                                XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                crv = Arc.Create(pt1, pt3, pt2);
                                            }

                                            if (crv != null)
                                            {

                                                // Find the level
                                                Level lvl = GetLevel(lbc.ControlPoints, doc);

                                                double offset = 0;
                                                if (Math.Abs(UnitUtils.ConvertToInternalUnits(curvePoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon)
                                                {
                                                    offset = lvl.Elevation - UnitUtils.ConvertToInternalUnits(curvePoints[0].Z, lengthDUT);
                                                }

                                                // Modify the wall
                                                Wall w = null;
                                                try
                                                {
                                                    w = doc.GetElement(existingElems[i]) as Wall;
                                                    LocationCurve lc = w.Location as LocationCurve;
                                                    lc.Curve = crv;

                                                    // Change the family and symbol if necessary
                                                    if (w.WallType.Name != wallType.Name)
                                                    {
                                                        try
                                                        {
                                                            w.WallType = wallType;
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Debug.WriteLine(ex.Message);
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    TaskDialog.Show("ERROR", ex.Message);
                                                }


                                                // Assign the parameters
                                                SetParameters(w, obj.Parameters, doc);
                                            }
                                        }
                                        // See if it's a structural column
                                        else if (obj.CategoryId == -2001330)
                                        {
                                            if (symbol != null && lbc.CurveType == "Line")
                                            {
                                                Curve crv = null;
                                                XYZ origin = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                crv = Line.CreateBound(origin, pt2);

                                                // Find the level
                                                //Level lvl = GetLevel(lbc.ControlPoints, doc);

                                                // Create the column
                                                //fi = doc.Create.NewFamilyInstance(origin, symbol, lvl, Autodesk.Revit.DB.Structure.StructuralType.Column);

                                                // Change it to a slanted column
                                                Parameter slantParam = fi.get_Parameter(BuiltInParameter.SLANTED_COLUMN_TYPE_PARAM);

                                                // SlantedOrVerticalColumnType has 3 options, CT_Vertical (0), CT_Angle (1), or CT_EndPoint (2)
                                                // CT_EndPoint is what we want for a line based column.
                                                slantParam.Set(2);

                                                // Set the location curve of the column to the line
                                                LocationCurve lc = fi.Location as LocationCurve;
                                                if (lc != null)
                                                {
                                                    lc.Curve = crv;
                                                }

                                                // Change the family and symbol if necessary
                                                if (fi.Symbol.Name != symbol.Name)
                                                {
                                                    try
                                                    {
                                                        fi.Symbol = symbol;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }

                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);
                                            }
                                        }

                                        else if (obj.CategoryId == -2000220)
                                        {
                                            // draw a grid
                                            Curve crv = null;
                                            if (lbc.CurveType == "Line")
                                            {
                                                XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                crv = Line.CreateBound(pt1, pt2);
                                            }
                                            else if (lbc.CurveType == "Arc")
                                            {
                                                XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                crv = Arc.Create(pt1, pt3, pt2);
                                            }

                                            if (crv != null && grid != null)
                                            {
                                                // Determine if it's possible to edit the grid curve or if it needs to be deleted/replaced.

                                                // Assign the parameters
                                                SetParameters(grid, obj.Parameters, doc);
                                            }
                                        }

                                        // Otherwise create a family it using the line
                                        else
                                        {
                                            if (symbol != null)
                                            {
                                                Curve crv = null;

                                                if (lbc.CurveType == "Line")
                                                {
                                                    XYZ origin = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                    XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                    crv = Line.CreateBound(origin, pt2);
                                                }
                                                else if (lbc.CurveType == "Arc")
                                                {
                                                    XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                    XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                    XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                    crv = Arc.Create(pt1, pt3, pt2);
                                                }

                                                // Change the family and symbol if necessary
                                                if (fi.Symbol.Name != symbol.Name)
                                                {
                                                    try
                                                    {
                                                        fi.Symbol = symbol;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }

                                                try
                                                {
                                                    LocationCurve lc = fi.Location as LocationCurve;
                                                    lc.Curve = crv;
                                                }
                                                catch (Exception ex)
                                                {
                                                    Debug.WriteLine(ex.Message);
                                                }
                                                // Assign the parameters
                                                SetParameters(fi, obj.Parameters, doc);
                                            }
                                        }
                                    }
                                    #endregion

                                    #region Closed Curve Family
                                    else
                                    {
                                        bool replace = false;
                                        if (supress)
                                        {
                                            if (supressedReplace)
                                            {
                                                replace = true;
                                            }
                                            else
                                            {
                                                replace = false;
                                            }
                                        }
                                        if (profileWarning && !supress)
                                        {
                                            TaskDialog warningDlg = new TaskDialog("Warning")
                                            {
                                                MainInstruction = "Profile based Elements warning",
                                                MainContent =
                                                  "Elements that require updates to a profile sketch may not be updated if the number of curves in the sketch differs from the incoming curves." +
                                                  "  In such cases the element and will be deleted and replaced with new elements." +
                                                  "  Doing so will cause the loss of any elements hosted to the original instance. How would you like to proceed"
                                            };

                                            warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Replace the existing elements, understanding hosted elements may be lost");
                                            warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Only updated parameter information and not profile or location information");
                                            warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Cancel");
                                            //warningDlg.VerificationText = "Supress similar warnings";

                                            TaskDialogResult result = warningDlg.Show();
                                            if (result == TaskDialogResult.CommandLink1)
                                            {
                                                replace = true;
                                                supressedReplace = true;
                                                supressedModify = true;
                                                //supress = warningDlg.WasVerificationChecked();
                                            }
                                            if (result == TaskDialogResult.CommandLink2)
                                            {
                                                supressedReplace = false;
                                                supressedModify = true;
                                                //supress = warningDlg.WasVerificationChecked();
                                            }
                                            if (result == TaskDialogResult.CommandLink3)
                                            {
                                                supressedReplace = false;
                                                supressedModify = false;
                                                //supress = warningDlg.WasVerificationChecked();
                                            }
                                        }
                                        // A list of curves.  These should equate a closed planar curve from GH.
                                        // Determine category and create based on that.
                                        #region walls
                                        if (obj.CategoryId == -2000011)
                                        {
                                            // Create line based wall
                                            // Find the level
                                            Level lvl = null;
                                            double offset = 0;
                                            List<LyrebirdPoint> allPoints = new List<LyrebirdPoint>();
                                            foreach (LyrebirdCurve lc in obj.Curves)
                                            {
                                                foreach (LyrebirdPoint lp in lc.ControlPoints)
                                                {
                                                    allPoints.Add(lp);
                                                }
                                            }
                                            allPoints.Sort((x, y) => x.Z.CompareTo(y.Z));

                                            lvl = GetLevel(allPoints, doc);

                                            if (Math.Abs(allPoints[0].Z - lvl.Elevation) > double.Epsilon)
                                            {
                                                offset = allPoints[0].Z - lvl.Elevation;
                                            }

                                            // Generate the curvearray from the incoming curves
                                            List<Curve> crvArray = new List<Curve>();
                                            try
                                            {
                                                foreach (LyrebirdCurve lbc in obj.Curves)
                                                {
                                                    if (lbc.CurveType == "Circle")
                                                    {
                                                        XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                        XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                        XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                        XYZ pt4 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].Z, lengthDUT));
                                                        XYZ pt5 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].Z, lengthDUT));
                                                        Arc arc1 = Arc.Create(pt1, pt3, pt2);
                                                        Arc arc2 = Arc.Create(pt3, pt5, pt4);
                                                        crvArray.Add(arc1);
                                                        crvArray.Add(arc2);
                                                    }
                                                    else if (lbc.CurveType == "Arc")
                                                    {
                                                        XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                        XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                        XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT));
                                                        Arc arc = Arc.Create(pt1, pt3, pt2);
                                                        crvArray.Add(arc);
                                                    }
                                                    else if (lbc.CurveType == "Line")
                                                    {
                                                        XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT));
                                                        XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT));
                                                        Line line = Line.CreateBound(pt1, pt2);
                                                        crvArray.Add(line);
                                                    }
                                                    else if (lbc.CurveType == "Spline")
                                                    {
                                                        List<XYZ> controlPoints = new List<XYZ>();
                                                        List<double> weights = lbc.Weights;
                                                        List<double> knots = lbc.Knots;

                                                        foreach (LyrebirdPoint lp in lbc.ControlPoints)
                                                        {
                                                            XYZ pt = new XYZ(UnitUtils.ConvertToInternalUnits(lp.X, lengthDUT), UnitUtils.ConvertToInternalUnits(lp.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lp.Z, lengthDUT));
                                                            controlPoints.Add(pt);
                                                        }

                                                        NurbSpline spline;
                                                        if (lbc.Degree < 3)
                                                            spline = NurbSpline.Create(controlPoints, weights);
                                                        else
                                                            spline = NurbSpline.Create(controlPoints, weights, knots, lbc.Degree, false, true);

                                                        crvArray.Add(spline);
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                TaskDialog.Show("ERROR", ex.Message);
                                            }

                                            // Create the wall
                                            Wall w = null;
                                            if (replace)
                                            {
                                                Wall origWall = doc.GetElement(existingElems[i]) as Wall;

                                                // Find the model curves for the original wall
                                                ICollection<ElementId> ids;
                                                using (SubTransaction st = new SubTransaction(doc))
                                                {
                                                    st.Start();
                                                    ids = doc.Delete(origWall.Id);
                                                    st.RollBack();
                                                }

                                                List<ModelCurve> mLines = new List<ModelCurve>();
                                                foreach (ElementId id in ids)
                                                {
                                                    Element e = doc.GetElement(id);
                                                    if (e is ModelCurve)
                                                    {
                                                        mLines.Add(e as ModelCurve);
                                                    }
                                                }

                                                // Walls don't appear to be updatable like floors and roofs
                                                //if (mLines.Count != crvArray.Count)
                                                //{

                                                w = Wall.Create(doc, crvArray, wallType.Id, lvl.Id, false);

                                                foreach (Parameter p in origWall.Parameters)
                                                {
                                                    try
                                                    {
                                                        Parameter newParam = w.LookupParameter(p.Definition.Name);
                                                        if (newParam != null)
                                                        {
                                                            switch (newParam.StorageType)
                                                            {
                                                                case StorageType.Double:
                                                                    newParam.Set(p.AsDouble());
                                                                    break;
                                                                case StorageType.ElementId:
                                                                    newParam.Set(p.AsElementId());
                                                                    break;
                                                                case StorageType.Integer:
                                                                    newParam.Set(p.AsInteger());
                                                                    break;
                                                                case StorageType.String:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                                default:
                                                                    newParam.Set(p.AsString());
                                                                    break;
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        //TaskDialog.Show("Errorsz", ex.Message);
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }

                                                if (Math.Abs(offset - 0) > double.Epsilon)
                                                {
                                                    Parameter p = w.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
                                                    p.Set(offset);
                                                }
                                                doc.Delete(origWall.Id);

                                                // Assign the parameters
                                                SetParameters(w, obj.Parameters, doc);

                                                // Assign the GH InstanceGuid
                                                AssignGuid(w, uniqueId, instanceSchema, runId, nickName);
                                            }
                                            else if (supressedModify) // Just update the parameters and don't change the wall
                                            {
                                                w = doc.GetElement(existingElems[i]) as Wall;

                                                // Change the family and symbol if necessary
                                                if (w.WallType.Name != wallType.Name)
                                                {
                                                    try
                                                    {
                                                        w.WallType = wallType;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }

                                                // Assign the parameters
                                                SetParameters(w, obj.Parameters, doc);
                                            }
                                        }
                                        #endregion

                                        #region floors
                                        else if (obj.CategoryId == -2000032)
                                        {
                                            // Create a profile based floor
                                            // Find the level
                                            Level lvl = GetLevel(obj.Curves[0].ControlPoints, doc);

                                            double offset = 0;
                                            if (Math.Abs(UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon)
                                            {
                                                offset = UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation;
                                            }

                                            // Generate the curvearray from the incoming curves
                                            CurveArray crvArray = GetCurveArray(obj.Curves);

                                            // Create the floor
                                            Floor flr = null;
                                            if (replace)
                                            {
                                                Floor origFloor = doc.GetElement(existingElems[i]) as Floor;

                                                // Find the model curves for the original wall
                                                ICollection<ElementId> ids;
                                                using (SubTransaction st = new SubTransaction(doc))
                                                {
                                                    st.Start();

                                                    ids = doc.Delete(origFloor.Id);
                                                    st.RollBack();
                                                }

                                                // Get only the modelcurves
                                                List<ModelCurve> mLines = new List<ModelCurve>();
                                                foreach (ElementId id in ids)
                                                {
                                                    Element e = doc.GetElement(id);
                                                    if (e is ModelCurve)
                                                    {
                                                        mLines.Add(e as ModelCurve);
                                                    }
                                                }

                                                // Floors have an extra modelcurve for the SpanDirection.  Remove the last Item to get rid of it.
                                                mLines.RemoveAt(mLines.Count - 1);
                                                if (mLines.Count != crvArray.Size) // The sketch is different from the incoming curves so floor is recreated
                                                {
                                                    if (obj.CurveIds != null && obj.CurveIds.Count > 0)
                                                    {
                                                        // get the main profile
                                                        int crvCount = obj.CurveIds[0];
                                                        List<LyrebirdCurve> primaryCurves = obj.Curves.GetRange(0, crvCount);
                                                        crvArray = GetCurveArray(primaryCurves);
                                                        flr = doc.Create.NewFloor(crvArray, floorType, lvl, false);
                                                    }
                                                    else
                                                    {
                                                        flr = doc.Create.NewFloor(crvArray, floorType, lvl, false);
                                                    }
                                                    foreach (Parameter p in origFloor.Parameters)
                                                    {
                                                        try
                                                        {
                                                            Parameter newParam = flr.LookupParameter(p.Definition.Name);
                                                            if (newParam != null)
                                                            {
                                                                switch (newParam.StorageType)
                                                                {
                                                                    case StorageType.Double:
                                                                        newParam.Set(p.AsDouble());
                                                                        break;
                                                                    case StorageType.ElementId:
                                                                        newParam.Set(p.AsElementId());
                                                                        break;
                                                                    case StorageType.Integer:
                                                                        newParam.Set(p.AsInteger());
                                                                        break;
                                                                    case StorageType.String:
                                                                        newParam.Set(p.AsString());
                                                                        break;
                                                                    default:
                                                                        newParam.Set(p.AsString());
                                                                        break;
                                                                }
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Debug.WriteLine(ex.Message);
                                                        }
                                                    }

                                                    if (Math.Abs(offset - 0) > double.Epsilon)
                                                    {
                                                        Parameter p = flr.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM);
                                                        p.Set(offset);
                                                    }
                                                    doc.Delete(origFloor.Id);

                                                    // Assign the parameters
                                                    SetParameters(flr, obj.Parameters, doc);

                                                    // Assign the GH InstanceGuid
                                                    AssignGuid(flr, uniqueId, instanceSchema, runId, nickName);
                                                }
                                                else // The curves coming in should match the floor sketch.  Let's modify the floor's locationcurves to edit it's location/shape
                                                {
                                                    try
                                                    {
                                                        int crvCount = 0;
                                                        foreach (ModelCurve l in mLines)
                                                        {
                                                            LocationCurve lc = l.Location as LocationCurve;
                                                            lc.Curve = crvArray.get_Item(crvCount);
                                                            crvCount++;
                                                        }

                                                        // Change the family and symbol if necessary
                                                        if (origFloor.FloorType.Name != floorType.Name)
                                                        {
                                                            try
                                                            {
                                                                origFloor.FloorType = floorType;
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                Debug.WriteLine(ex.Message);
                                                            }
                                                        }

                                                        // Set the incoming parameters
                                                        SetParameters(origFloor, obj.Parameters, doc);
                                                    }
                                                    catch // There was an error in trying to recreate it.  Just delete the original and recreate the thing.
                                                    {
                                                        flr = doc.Create.NewFloor(crvArray, floorType, lvl, false);

                                                        // Assign the parameters in the new floor to match the original floor object.
                                                        foreach (Parameter p in origFloor.Parameters)
                                                        {
                                                            try
                                                            {
                                                                Parameter newParam = flr.LookupParameter(p.Definition.Name);
                                                                if (newParam != null)
                                                                {
                                                                    switch (newParam.StorageType)
                                                                    {
                                                                        case StorageType.Double:
                                                                            newParam.Set(p.AsDouble());
                                                                            break;
                                                                        case StorageType.ElementId:
                                                                            newParam.Set(p.AsElementId());
                                                                            break;
                                                                        case StorageType.Integer:
                                                                            newParam.Set(p.AsInteger());
                                                                            break;
                                                                        case StorageType.String:
                                                                            newParam.Set(p.AsString());
                                                                            break;
                                                                        default:
                                                                            newParam.Set(p.AsString());
                                                                            break;
                                                                    }
                                                                }
                                                            }
                                                            catch (Exception exception)
                                                            {
                                                                Debug.WriteLine(exception.Message);
                                                            }
                                                        }

                                                        if (Math.Abs(offset - 0) > double.Epsilon)
                                                        {
                                                            Parameter p = flr.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM);
                                                            p.Set(offset);
                                                        }

                                                        doc.Delete(origFloor.Id);

                                                        // Set the incoming parameters
                                                        SetParameters(flr, obj.Parameters, doc);
                                                        // Assign the GH InstanceGuid
                                                        AssignGuid(flr, uniqueId, instanceSchema, runId, nickName);
                                                    }
                                                }
                                            }
                                            else if (supressedModify) // Just modify the floor and don't risk replacing it.
                                            {
                                                flr = doc.GetElement(existingElems[i]) as Floor;

                                                // Change the family and symbol if necessary
                                                if (flr.FloorType.Name != floorType.Name)
                                                {
                                                    try
                                                    {
                                                        flr.FloorType = floorType;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }
                                                // Assign the parameters
                                                SetParameters(flr, obj.Parameters, doc);
                                            }
                                        }
                                        #endregion
                                        else if (obj.CategoryId == -2000035)
                                        {
                                            // Create a RoofExtrusion
                                            // Find the level
                                            Level lvl = GetLevel(obj.Curves[0].ControlPoints, doc);

                                            double offset = 0;
                                            if (Math.Abs(UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon)
                                            {
                                                offset = UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation;
                                            }

                                            // Generate the curvearray from the incoming curves
                                            CurveArray crvArray = GetCurveArray(obj.Curves);

                                            // Create the roof
                                            FootPrintRoof roof = null;
                                            ModelCurveArray roofProfile = new ModelCurveArray();

                                            if (replace)  // Try to modify or create a new roof.
                                            {
                                                FootPrintRoof origRoof = doc.GetElement(existingElems[i]) as FootPrintRoof;

                                                // Find the model curves for the original wall
                                                ICollection<ElementId> ids;
                                                using (SubTransaction st = new SubTransaction(doc))
                                                {
                                                    st.Start();
                                                    ids = doc.Delete(origRoof.Id);
                                                    st.RollBack();
                                                }

                                                // Get the sketch curves for the roof object.
                                                List<ModelCurve> mLines = new List<ModelCurve>();
                                                foreach (ElementId id in ids)
                                                {
                                                    Element e = doc.GetElement(id);
                                                    if (e is ModelCurve)
                                                    {
                                                        mLines.Add(e as ModelCurve);
                                                    }
                                                }

                                                if (mLines.Count != crvArray.Size) // Sketch curves qty doesn't match up with the incoming cuves.  Just recreate the roof.
                                                {
                                                    roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile);

                                                    // Match parameters from the original roof to it's new iteration.
                                                    foreach (Parameter p in origRoof.Parameters)
                                                    {
                                                        try
                                                        {
                                                            Parameter newParam = roof.LookupParameter(p.Definition.Name);
                                                            if (newParam != null)
                                                            {
                                                                switch (newParam.StorageType)
                                                                {
                                                                    case StorageType.Double:
                                                                        newParam.Set(p.AsDouble());
                                                                        break;
                                                                    case StorageType.ElementId:
                                                                        newParam.Set(p.AsElementId());
                                                                        break;
                                                                    case StorageType.Integer:
                                                                        newParam.Set(p.AsInteger());
                                                                        break;
                                                                    case StorageType.String:
                                                                        newParam.Set(p.AsString());
                                                                        break;
                                                                    default:
                                                                        newParam.Set(p.AsString());
                                                                        break;
                                                                }
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Debug.WriteLine(ex.Message);
                                                        }
                                                    }

                                                    if (Math.Abs(offset - 0) > double.Epsilon)
                                                    {
                                                        Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM);
                                                        p.Set(offset);
                                                    }

                                                    doc.Delete(origRoof.Id);

                                                    // Set the new parameters
                                                    SetParameters(roof, obj.Parameters, doc);

                                                    // Assign the GH InstanceGuid
                                                    AssignGuid(roof, uniqueId, instanceSchema, runId, nickName);
                                                }
                                                else // The curves qty lines up, lets try to modify the roof sketch so we don't have to replace it.
                                                {
                                                    if (obj.CurveIds != null && obj.CurveIds.Count > 0)
                                                    {
                                                        // Just recreate the roof
                                                        roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile);

                                                        // Match parameters from the original roof to it's new iteration.
                                                        foreach (Parameter p in origRoof.Parameters)
                                                        {
                                                            try
                                                            {
                                                                Parameter newParam = roof.LookupParameter(p.Definition.Name);
                                                                if (newParam != null)
                                                                {
                                                                    switch (newParam.StorageType)
                                                                    {
                                                                        case StorageType.Double:
                                                                            newParam.Set(p.AsDouble());
                                                                            break;
                                                                        case StorageType.ElementId:
                                                                            newParam.Set(p.AsElementId());
                                                                            break;
                                                                        case StorageType.Integer:
                                                                            newParam.Set(p.AsInteger());
                                                                            break;
                                                                        case StorageType.String:
                                                                            newParam.Set(p.AsString());
                                                                            break;
                                                                        default:
                                                                            newParam.Set(p.AsString());
                                                                            break;
                                                                    }
                                                                }
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                Debug.WriteLine(ex.Message);
                                                            }
                                                        }

                                                        if (Math.Abs(offset - 0) > double.Epsilon)
                                                        {
                                                            Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM);
                                                            p.Set(offset);
                                                        }

                                                        // Set the parameters from the incoming data
                                                        SetParameters(roof, obj.Parameters, doc);

                                                        // Assign the GH InstanceGuid
                                                        AssignGuid(roof, uniqueId, instanceSchema, runId, nickName);

                                                        doc.Delete(origRoof.Id);
                                                    }
                                                    else
                                                    {
                                                        try
                                                        {
                                                            int crvCount = 0;
                                                            foreach (ModelCurve l in mLines)
                                                            {
                                                                LocationCurve lc = l.Location as LocationCurve;
                                                                lc.Curve = crvArray.get_Item(crvCount);
                                                                crvCount++;
                                                            }

                                                            // Change the family and symbol if necessary
                                                            if (origRoof.RoofType.Name != roofType.Name)
                                                            {
                                                                try
                                                                {
                                                                    origRoof.RoofType = roofType;
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    Debug.WriteLine(ex.Message);
                                                                }
                                                            }

                                                            SetParameters(origRoof, obj.Parameters, doc);
                                                        }
                                                        catch // Modificaiton failed, lets just create a new roof.
                                                        {
                                                            roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile);

                                                            // Match parameters from the original roof to it's new iteration.
                                                            foreach (Parameter p in origRoof.Parameters)
                                                            {
                                                                try
                                                                {
                                                                    Parameter newParam = roof.LookupParameter(p.Definition.Name);
                                                                    if (newParam != null)
                                                                    {
                                                                        switch (newParam.StorageType)
                                                                        {
                                                                            case StorageType.Double:
                                                                                newParam.Set(p.AsDouble());
                                                                                break;
                                                                            case StorageType.ElementId:
                                                                                newParam.Set(p.AsElementId());
                                                                                break;
                                                                            case StorageType.Integer:
                                                                                newParam.Set(p.AsInteger());
                                                                                break;
                                                                            case StorageType.String:
                                                                                newParam.Set(p.AsString());
                                                                                break;
                                                                            default:
                                                                                newParam.Set(p.AsString());
                                                                                break;
                                                                        }
                                                                    }
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    Debug.WriteLine(ex.Message);
                                                                }
                                                            }

                                                            if (Math.Abs(offset - 0) > double.Epsilon)
                                                            {
                                                                Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM);
                                                                p.Set(offset);
                                                            }

                                                            // Set the parameters from the incoming data
                                                            SetParameters(roof, obj.Parameters, doc);

                                                            // Assign the GH InstanceGuid
                                                            AssignGuid(roof, uniqueId, instanceSchema, runId, nickName);

                                                            doc.Delete(origRoof.Id);
                                                        }
                                                    }
                                                }
                                            }
                                            else if (supressedModify) // Only update the parameters
                                            {
                                                roof = doc.GetElement(existingElems[i]) as FootPrintRoof;

                                                // Change the family and symbol if necessary
                                                if (roof.RoofType.Name != roofType.Name)
                                                {
                                                    try
                                                    {
                                                        roof.RoofType = roofType;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Debug.WriteLine(ex.Message);
                                                    }
                                                }
                                                // Assign the parameters
                                                SetParameters(roof, obj.Parameters, doc);
                                            }
                                        }
                                    }
                                    #endregion
                                }
                            }
                            catch (Exception ex)
                            {
                                TaskDialog.Show("Error", ex.Message);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }
                        t.Commit();
                    }
                }


            }
            #endregion

            //return succeeded;
        }
        private static void ElevateIfRequired(IWin32Window window, int session, string actionName, Action action)
        {
            if (Settings.Instance.ElevationLevel == (int)ElevationLevel.Never)
            {
                return;
            }

            try
            {
                action();
            }
            catch (WindowsException ex)
            {
                if (ex.ErrorCode == Win32Error.AccessDenied && OSVersion.HasUac && Program.ElevationType == TokenElevationType.Limited)
                {
                    DialogResult result;

                    if (Settings.Instance.ElevationLevel == (int)ElevationLevel.Elevate)
                    {
                        result = DialogResult.Yes;
                    }
                    else
                    {
                        TaskDialog td = new TaskDialog
                        {
                            PositionRelativeToWindow = true,
                            WindowTitle     = "Process Hacker",
                            MainIcon        = TaskDialogIcon.Warning,
                            MainInstruction = "Do you want to elevate the action?",
                            Content         = "The action could not be performed in the current security context. " +
                                              "Do you want Process Hacker to prompt for the appropriate credentials and elevate the action?",
                            ExpandedInformation = "Error: " + ex.Message + " (0x" + ex.ErrorCode.ToString("x") + ")",
                            ExpandFooterArea    = true,
                            Buttons             = new TaskDialogButton[]
                            {
                                new TaskDialogButton((int)DialogResult.Yes, "Elevate\nPrompt for credentials and elevate the action.")
                            },
                            CommonButtons   = TaskDialogCommonButtons.Cancel,
                            UseCommandLinks = true,
                            Callback        = (taskDialog, args, userData) =>
                            {
                                if (args.Notification == TaskDialogNotification.Created)
                                {
                                    taskDialog.SetButtonElevationRequiredState((int)DialogResult.Yes, true);
                                }

                                return(false);
                            }
                        };

                        result = (DialogResult)td.Show(window);
                    }

                    if (result == DialogResult.Yes)
                    {
                        Program.StartProcessHackerAdmin(
                            "-e -type session -action " + actionName + " -obj \"" +
                            session.ToString() + "\" -hwnd " + window.Handle.ToString(), null, window.Handle);
                    }
                }
                else
                {
                    PhUtils.ShowException("Unable to " + actionName + " the session", ex);
                }
            }
        }
Beispiel #44
0
        //Helper method
        private void UpdateParameterValuesForElements(List <Element> combinedElements, bool isConduitRun)
        {
            Document doc = this.Document;

            string feederDesignatorParameterName = "";
            Dictionary <string, List <Tuple <string, string> > > dictXlFeederData = new Dictionary <string, List <Tuple <string, string> > >();

            dictXlFeederData = ReadDataFromExcelAndReturn();

            List <Tuple <string, string> > dictItem = dictXlFeederData[FEEDER_PARAMETER_DESIGNATOR_IN_REVIT_AND_EXCEL];

            foreach (Tuple <string, string> valueItem in dictItem)
            {
                feederDesignatorParameterName = valueItem.Item1;
            }


            TaskDialog.Show("data", dictXlFeederData.Count.ToString()
                            + "-Rows of Excel Feeder data read. "
                            + "\n" + "\n" + "Attempting to apply this data to "
                            + combinedElements.Count.ToString()
                            + " Elements");

            Transaction trans = new Transaction(doc);

            trans.Start("Updated Conduit Run Parameters");


            //string str = "";
            int feederDesignatorParameterCount = 0;
            int updatedElements = 0;
            int totalElements   = 0;
            //get feeder designator of selected conduit to be applied to conduit run
            //first element should be the selected element
            string feederDesignatorParameterValue = KPHelperClass.GetStringParameterValueFromName(combinedElements[0], feederDesignatorParameterName);

            foreach (Element e in combinedElements)
            {
                totalElements++;

                //use each elements feeder designator value if its not a conduit run
                if (isConduitRun == false)
                {
                    feederDesignatorParameterValue = KPHelperClass.GetStringParameterValueFromName(e, feederDesignatorParameterName);
                }

                if (feederDesignatorParameterValue != null && dictXlFeederData.ContainsKey(feederDesignatorParameterValue))
                {
                    //set the feeder designator value based on selected conduit
                    Autodesk.Revit.DB.Parameter p1 = KPHelperClass.GetParameterFromName(e, feederDesignatorParameterName);
                    if (p1 != null)
                    {
                        p1.Set(feederDesignatorParameterValue);
                    }

                    var value = dictXlFeederData[feederDesignatorParameterValue];

                    foreach (Tuple <string, string> t in value)
                    {
                        Autodesk.Revit.DB.Parameter p2 = KPHelperClass.GetParameterFromName(e, t.Item1);

                        if (p2 != null)
                        {
                            p2.Set(t.Item2);
                        }
                    }
                    updatedElements++;
                }
                else
                {
                    feederDesignatorParameterCount++;
                }
            }

            trans.Commit();

            TaskDialog.Show("Updated Parameters", "Out of " + totalElements.ToString() + " Elements: "
                            + "\n"
                            + "\n"
                            + feederDesignatorParameterCount.ToString()
                            + ": Element(s) did not have a Feeder Designator or did not match the Feeder Designator in the Excel Data"
                            + "\n"
                            + "\n"
                            + updatedElements.ToString()
                            + ": Element(s) were updated successfully");
        }
        public Result Execute(
            ExternalCommandData revit,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = revit.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Document doc = uidoc.Document;

              // Retrieve pre-selected elements.

              ICollection<ElementId> ids
            = uidoc.Selection.GetElementIds();

              if( 0 == ids.Count )
              {
            message = "Please pre-select some elements "
              + "before launching this command to list "
              + "the views displaying them.";

            return Result.Failed;
              }

              // Determine views displaying them.

              IEnumerable<Element> targets
            = from id in ids select doc.GetElement( id );

              IEnumerable<View> views = targets
            .FindAllViewsWhereAllElementsVisible();

              // Report results.

              string names = string.Join( ", ",
            ( from v in views select v.Name ) );

              int nElems = targets.Count<Element>();

              int nViews = names.Count<char>(
            c => ',' == c ) + 1;

              TaskDialog dlg = new TaskDialog( string.Format(
            "{0} element{1} are visible in {2} view{3}",
            nElems, Util.PluralSuffix( nElems ),
            nViews, Util.PluralSuffix( nViews ) ) );

              dlg.MainInstruction = names;

              dlg.Show();

              return Result.Succeeded;
        }
        /// <summary>
        /// Add a roof over the rectangular profile of the walls we created earlier.
        /// </summary>
        public void AddRoof(List <Wall> walls)
        {
            // Hard coding the roof type we will use.
            // E.g., "Basic Roof: Generic - 400mm"

            const string roofFamilyName        = "Basic Roof";
            const string roofTypeName          = Util.Constant.RoofTypeName; //  Util.Constant.RoofTypeName
            const string roofFamilyAndTypeName = roofFamilyName + ": " + roofTypeName;

            // Find the roof type

            RoofType roofType = (RoofType)ElementFiltering.FindFamilyType(_doc, typeof(RoofType), roofFamilyName, roofTypeName, null);

            if (roofType == null)
            {
                TaskDialog.Show(
                    "Add roof",
                    "Cannot find (" +
                    roofFamilyAndTypeName +
                    "). Maybe you use a different template? Try with DefaultMetric.rte.");
            }

            // Wall thickness to adjust the footprint of the walls
            // to the outer most lines.
            // Note: this may not be the best way,
            // but we will live with this for this exercise.

            //double wallThickness = walls[0].WallType.CompoundStructure.Layers.get_Item(0).Thickness; // 2011
            double wallThickness = walls[0].Width;

            double     dt  = wallThickness / 2.0;
            List <XYZ> dts = new List <XYZ>(5);

            dts.Add(new XYZ(-dt, -dt, 0.0));
            dts.Add(new XYZ(dt, -dt, 0.0));
            dts.Add(new XYZ(dt, dt, 0.0));
            dts.Add(new XYZ(-dt, dt, 0.0));
            dts.Add(dts[0]);

            // Set the profile from four walls

            CurveArray footPrint = new CurveArray();

            for (int i = 0; i <= 3; i++)
            {
                LocationCurve locCurve = (LocationCurve)walls[i].Location;
                XYZ           pt1      = locCurve.Curve.GetEndPoint(0) + dts[i];
                XYZ           pt2      = locCurve.Curve.GetEndPoint(1) + dts[i + 1];
                Line          line     = Line.CreateBound(pt1, pt2);
                footPrint.Append(line);
            }

            // Get the level2 from the wall

            ElementId idLevel2 = walls[0].get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId();
            //Level level2 = (Level)_doc.get_Element(idLevel2); // 2012
            Level level2 = (Level)_doc.GetElement(idLevel2); // since 2013

            // Footprint to model curve mapping

            ModelCurveArray mapping = new ModelCurveArray();

            // Create a roof.

            FootPrintRoof aRoof = _doc.Create.NewFootPrintRoof(
                footPrint, level2, roofType, out mapping);

            foreach (ModelCurve modelCurve in mapping)
            {
                aRoof.set_DefinesSlope(modelCurve, true);
                aRoof.set_SlopeAngle(modelCurve, 0.5);
            }
        }
      public void ExportLinkedDocuments(Autodesk.Revit.DB.Document document, string fileName, Dictionary<ElementId, string> linksGUIDsCache, IFCExportOptions exportOptions)
      {
         // get the extension
         int index = fileName.LastIndexOf('.');
         if (index <= 0)
            return;
         string sExtension = fileName.Substring(index);
         fileName = fileName.Substring(0, index);

         // get all the revit link instances
         FilteredElementCollector collector = new FilteredElementCollector(document);
         ElementFilter elementFilter = new ElementClassFilter(typeof(RevitLinkInstance));
         List<RevitLinkInstance> rvtLinkInstances = collector.WherePasses(elementFilter).Cast<RevitLinkInstance>().ToList();

         IDictionary<String, int> rvtLinkNamesDict = new Dictionary<String, int>();
         IDictionary<String, List<RevitLinkInstance>> rvtLinkNamesToInstancesDict = new Dictionary<String, List<RevitLinkInstance>>();

         try
         {
            // get the link types
            foreach (RevitLinkInstance rvtLinkInstance in rvtLinkInstances)
            {
               // get the instance
               if (rvtLinkInstance == null)
                  continue;

               // check the cache
               if (linksGUIDsCache.Keys.Contains(rvtLinkInstance.Id) == false)
                  continue;

               // get the link document
               Document linkDocument = rvtLinkInstance.GetLinkDocument();
               if (linkDocument == null)
                  continue;

               // get the link file path and name
               String linkPathName = "";
               Parameter originalFileNameParam = linkDocument.ProjectInformation.LookupParameter("Original IFC File Name");
               if (originalFileNameParam != null && originalFileNameParam.StorageType == StorageType.String)
                  linkPathName = originalFileNameParam.AsString();
               else
                  linkPathName = linkDocument.PathName;

               // get the link file name
               String linkFileName = "";
               index = linkPathName.LastIndexOf("\\");
               if (index > 0)
                  linkFileName = linkPathName.Substring(index + 1);
               else
                  linkFileName = linkDocument.Title;

               // remove the extension
               index = linkFileName.LastIndexOf('.');
               if (index > 0)
                  linkFileName = linkFileName.Substring(0, index);

               // add to names count dictionary
               if (!rvtLinkNamesDict.Keys.Contains(linkFileName))
                  rvtLinkNamesDict.Add(linkFileName, 0);
               rvtLinkNamesDict[linkFileName]++;

               // add to names instances dictionary
               if (!rvtLinkNamesToInstancesDict.Keys.Contains(linkPathName))
                  rvtLinkNamesToInstancesDict.Add(linkPathName, new List<RevitLinkInstance>());
               rvtLinkNamesToInstancesDict[linkPathName].Add(rvtLinkInstance);
            }
         }
         catch
         {
         }

         // get the link instances
         // We will keep track of the instances we can't export.
         // Reasons we can't export:
         // 1. The path for the linked instance doesn't exist.
         // 2. Couldn't create a temporary document for exporting the linked instance.
         // 3. The document for the linked instance can't be found.
         // 4. The linked instance is mirrored, non-conformal, or scaled.
         IList<string> pathDoesntExist = new List<string>();
         IList<string> noTempDoc = new List<string>();
         IList<ElementId> cantFindDoc = new List<ElementId>();
         IList<ElementId> nonConformalInst = new List<ElementId>();
         IList<ElementId> scaledInst = new List<ElementId>();
         IList<ElementId> instHasReflection = new List<ElementId>();

         foreach (String linkPathName in rvtLinkNamesToInstancesDict.Keys)
         {
            // get the name of the copy
            String linkPathNameCopy = System.IO.Path.GetTempPath();
            index = linkPathName.LastIndexOf("\\");
            if (index > 0)
               linkPathNameCopy += linkPathName.Substring(index + 1);
            else
               linkPathNameCopy += linkPathName;
            index = linkPathNameCopy.LastIndexOf('.');
            if (index <= 0)
               index = linkPathNameCopy.Length;
            linkPathNameCopy = linkPathNameCopy.Insert(index, " - Copy");
            int i = 1;
            while (File.Exists(linkPathNameCopy))
               linkPathNameCopy = linkPathNameCopy.Insert(index, "(" + (++i).ToString() + ")");

            // copy the file
            File.Copy(linkPathName, linkPathNameCopy);
            if (!File.Exists(linkPathNameCopy))
            {
               pathDoesntExist.Add(linkPathName);
               continue;
            }

            // open the document
            Document documentCopy = null;
            try
            {
               if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") ||
                   (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") ||
                   (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip"))
                  documentCopy = document.Application.OpenIFCDocument(linkPathNameCopy);
               else
                  documentCopy = document.Application.OpenDocumentFile(linkPathNameCopy);
            }
            catch
            {
               documentCopy = null;
            }

            if (documentCopy == null)
            {
               noTempDoc.Add(linkPathName);
               continue;
            }

            // get the link document unit scale
            DisplayUnitType dutLink = documentCopy.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;
            double lengthScaleFactorLink = UnitUtils.ConvertFromInternalUnits(1.0, dutLink);

            // get the link instances
            List<RevitLinkInstance> currRvtLinkInstances = rvtLinkNamesToInstancesDict[linkPathName];
            IList<string> serTransforms = new List<string>();
            IList<string> linkFileNames = new List<string>();

            foreach (RevitLinkInstance currRvtLinkInstance in currRvtLinkInstances)
            {
               // Nothing to report if the element itself is null.
               if (currRvtLinkInstance == null)
                  continue;

               // get the link document
               Document linkDocument = currRvtLinkInstance.GetLinkDocument();
               if (linkDocument == null)
               {
                  cantFindDoc.Add(currRvtLinkInstance.Id);
                  continue;
               }

               // get the link transform
               Transform tr = currRvtLinkInstance.GetTransform();

               // We can't handle non-conformal, scaled, or mirrored transforms.
               if (!tr.IsConformal)
               {
                  nonConformalInst.Add(currRvtLinkInstance.Id);
                  continue;
               }

               if (tr.HasReflection)
               {
                  instHasReflection.Add(currRvtLinkInstance.Id);
                  continue;
               }

               if (!MathUtil.IsAlmostEqual(tr.Determinant, 1.0))
               {
                  scaledInst.Add(currRvtLinkInstance.Id);
                  continue;
               }

               // get the link file path and name
               String linkFileName = "";
               index = linkPathName.LastIndexOf("\\");
               if (index > 0)
                  linkFileName = linkPathName.Substring(index + 1);
               else
                  linkFileName = linkDocument.Title;

               // remove the extension
               index = linkFileName.LastIndexOf('.');
               if (index > 0)
                  linkFileName = linkFileName.Substring(0, index);

               //if link was an IFC file then make a different formating to the file name
               if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") ||
                   (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") ||
                   (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip"))
               {
                  String fName = fileName;

                  //get output path and add to the new file name 
                  index = fName.LastIndexOf("\\");
                  if (index > 0)
                     fName = fName.Substring(0, index + 1);
                  else
                     fName = "";

                  //construct IFC file name
                  linkFileName = fName + linkFileName + "-";

                  //add guid
                  linkFileName += linksGUIDsCache[currRvtLinkInstance.Id];
               }
               else
               {
                  // check if there are multiple instances with the same name
                  bool bMultiple = (rvtLinkNamesDict[linkFileName] > 1);

                  // add the path
                  linkFileName = fileName + "-" + linkFileName;

                  // add the guid
                  if (bMultiple)
                  {
                     linkFileName += "-";
                     linkFileName += linksGUIDsCache[currRvtLinkInstance.Id];
                  }
               }

               // add the extension
               linkFileName += sExtension;

               linkFileNames.Add(linkFileName);

               // scale the transform origin
               tr.Origin *= lengthScaleFactorLink;

               // serialize transform
               serTransforms.Add(SerializeTransform(tr));
            }

            // IFC export requires an open transaction, although no changes should be made
            Transaction transaction = new Transaction(documentCopy, "Export IFC Link");
            transaction.Start();
            FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
            failureOptions.SetClearAfterRollback(false);
            transaction.SetFailureHandlingOptions(failureOptions);

            // export
            try
            {
               int numLinkInstancesToExport = linkFileNames.Count;
               exportOptions.AddOption("NumberOfExportedLinkInstances", numLinkInstancesToExport.ToString());

               for (int ii = 0; ii < numLinkInstancesToExport; ii++)
               {
                  string optionName = (ii == 0) ? "ExportLinkInstanceTransform" : "ExportLinkInstanceTransform" + (ii + 1).ToString();
                  exportOptions.AddOption(optionName, serTransforms[ii]);

                  // Don't pass in file name for the first link instance.
                  if (ii == 0)
                     continue;

                  optionName = "ExportLinkInstanceFileName" + (ii + 1).ToString();
                  exportOptions.AddOption(optionName, linkFileNames[ii]);
               }

               // Pass in the first value; the rest will  be in the options.
               String path_ = Path.GetDirectoryName(linkFileNames[0]);
               String fileName_ = Path.GetFileName(linkFileNames[0]);
               bool result = documentCopy.Export(path_, fileName_, exportOptions); // pass in the options here
            }
            catch
            {
            }

            // rollback the transaction
            transaction.RollBack();

            // close the document
            documentCopy.Close(false);

            // delete the copy
            try
            {
               File.Delete(linkPathNameCopy);
            }
            catch
            {
            }

            // Show user errors, if any.
            int numBadInstances = pathDoesntExist.Count + noTempDoc.Count + cantFindDoc.Count + nonConformalInst.Count
                + scaledInst.Count + instHasReflection.Count;
            if (numBadInstances > 0)
            {
               using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
               {
                  taskDialog.MainInstruction = string.Format(Properties.Resources.LinkInstanceExportErrorMain, numBadInstances);
                  taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
                  taskDialog.TitleAutoPrefix = false;

                  string expandedContent = "";
                  AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportErrorPath, pathDoesntExist);
                  AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantCreateDoc, noTempDoc);
                  AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantFindDoc, cantFindDoc);
                  AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportNonConformal, nonConformalInst);
                  AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportScaled, scaledInst);
                  AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportHasReflection, instHasReflection);

                  taskDialog.ExpandedContent = expandedContent;
                  TaskDialogResult result = taskDialog.Show();
               }
            }
         }
      }
Beispiel #48
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // Get access to the top most objects. (we may not use them all in this specific lab.)
            _uiApp = commandData.Application;
            _uiDoc = _uiApp.ActiveUIDocument;

            // (1) pre-seleceted element is under UIDocument.Selection.Elemens. Classic method.
            // You can also modify this selection set.

            //SelElementSet selSet = _uiDoc.Selection.Elements;
            //ShowElementList(selectedElementIds, "Pre-selection: ");

            // 'Autodesk.Revit.UI.Selection.SelElementSet' is obsolete:
            // 'This class is deprecated in Revit 2015. Use Selection.SetElementIds()
            // and Selection.GetElementIds() instead.'

            // 'Autodesk.Revit.UI.Selection.Selection.Elements' is obsolete:
            // 'This property is deprecated in Revit 2015.
            // Use GetElementIds() and SetElementIds instead.'

            /// Following part is modified code for Revit 2015
            ///

            ICollection <ElementId> selectedElementIds = _uiDoc.Selection.GetElementIds();

            // Display current number of selected elements
            TaskDialog.Show("Revit", "Number of selected elements: " + selectedElementIds.Count.ToString());

            // We need to re-write the following function

            ShowElementList(selectedElementIds, "Pre-selection: ");


            /// End of modified code for Revit 2015



            try
            {
                // (2.1) pick methods basics.
                // there are four types of pick methods: PickObject, PickObjects, PickElementByRectangle, PickPoint.
                // Let's quickly try them out.

                PickMethodsBasics();

                // (2.2) selection object type
                // in addition to selecting objects of type Element, the user can pick faces, edges, and point on element.

                PickFaceEdgePoint();

                // (2.3) selection filter
                // if you want additional selection criteria, such as only to pick a wall, you can use selection filter.

                ApplySelectionFilter();
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                TaskDialog.Show("UI selection", "You have canceled selection.");
            }
            catch (Exception)
            {
                TaskDialog.Show("UI selection", "Some other exception caught in CancelSelection()");
            }

            // (2.4) canceling selection
            // when the user cancel or press [Esc] key during the selection, OperationCanceledException will be thrown.

            CancelSelection();

            // (3) apply what we learned to our small house creation
            // we put it as a separate command. See at the bottom of the code.
            // CreateHouseUI

            return(Result.Succeeded);
        }
        /// <summary>
        /// Implementation of the command binding event for the IFC export command.
        /// </summary>
        /// <param name="sender">The event sender (Revit UIApplication).</param>
        /// <param name="args">The arguments (command binding).</param>
        public void OnIFCExport(object sender, CommandEventArgs args)
        {
            try
            {
                // Prepare basic objects
                UIApplication uiApp = sender as UIApplication;
                UIDocument uiDoc = uiApp.ActiveUIDocument;
                Document doc = uiDoc.Document;

                TheDocument = doc;

                IFCExportConfigurationsMap configurationsMap = new IFCExportConfigurationsMap();
                configurationsMap.Add(IFCExportConfiguration.GetInSession());
                configurationsMap.AddBuiltInConfigurations();
                configurationsMap.AddSavedConfigurations();

                String mruSelection = null;
                if (m_mruConfiguration != null && configurationsMap.HasName(m_mruConfiguration))
                    mruSelection =  m_mruConfiguration;

                PotentiallyUpdatedConfigurations = false;

                IFCExport mainWindow = new IFCExport(doc, configurationsMap, mruSelection);
                mainWindow.ShowDialog();

                // If user chose to continue
                if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings)
                {
                    // change options
                    IFCExportConfiguration selectedConfig = mainWindow.GetSelectedConfiguration();

                    // Prepare the export options
                    IFCExportOptions exportOptions = new IFCExportOptions();
                    selectedConfig.UpdateOptions(exportOptions, uiDoc.ActiveView.Id);  

                    // prompt for the file name
                    SaveFileDialog fileDialog = new SaveFileDialog();
                    fileDialog.AddExtension = true;

                    String defaultDirectory = m_mruExportPath != null ? m_mruExportPath : null;
                    
                    if (defaultDirectory == null)
                    {
                        String revitFilePath = doc.PathName;
                        if (!String.IsNullOrEmpty(revitFilePath))
                        {
                            defaultDirectory = Path.GetDirectoryName(revitFilePath);
                        }
                    }

                    if (defaultDirectory == null)
                    {
                        defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    }

                    String defaultFileName = doc.Title;
                    if (String.IsNullOrEmpty(defaultFileName))
                    {
                        defaultFileName = "Project";
                    }
                    else
                    {
                        defaultFileName = Path.GetFileNameWithoutExtension(defaultFileName);
                    }
                    String defaultExtension = mainWindow.GetFileExtension();

                    fileDialog.FileName = defaultFileName;
                    fileDialog.DefaultExt = defaultExtension;
                    fileDialog.Filter = mainWindow.GetFileFilter();
                    fileDialog.InitialDirectory = defaultDirectory;
                    bool? fileDialogResult = fileDialog.ShowDialog();
                
                    // If user chose to continue
                    if (fileDialogResult.HasValue && fileDialogResult.Value)
                    {
                        // Prompt the user for the file location and path
                        String fullName = fileDialog.FileName;
                        String path = Path.GetDirectoryName(fullName);
                        String fileName = Path.GetFileName(fullName);

                        // IFC export requires an open transaction, although no changes should be made
                        Transaction transaction = new Transaction(doc, "Export IFC");
                        transaction.Start();
                        FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
                        failureOptions.SetClearAfterRollback(false);
                        transaction.SetFailureHandlingOptions(failureOptions);

                        // There is no UI option for this, but these two options can be useful for debugging/investigating
                        // issues in specific file export.  The first one supports export of only one element
                        //exportOptions.AddOption("SingleElement", "174245");
                        // The second one supports export only of a list of elements
                        //exportOptions.AddOption("ElementsForExport", "174245;205427");

                        // This option should be rarely used, and is only for consistency with old files.  As such, it is set by environment variable only.
                        String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport");
                        bool use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1");

                        // Roll back the transaction started earlier, unless certain options are set.
                        bool commitTransaction = (use2009BuildingStoreyGUIDs || selectedConfig.StoreIFCGUID);
                        
                        if (commitTransaction)
                            IFCStoredGUID.Clear();

                        bool result = doc.Export(path, fileName, exportOptions); // pass in the options here

                        if (!result)
                        {
                            //TODO localization
                            TaskDialog taskDialog = new TaskDialog("Error exporting IFC file");
                            taskDialog.MainInstruction = "The IFC export process encountered an error.";
                            taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
                            taskDialog.Show();
                        }

                        // Roll back the transaction started earlier, unless certain options are set.
                        if (commitTransaction)
                        {
                            foreach (KeyValuePair<ElementId, string> elementIdToGUID in IFCStoredGUID.ElementIdToGUID)
                            {
                                Element element = doc.GetElement(elementIdToGUID.Key);
                                if (element == null)
                                    continue;

                                BuiltInParameter builtInParameter = (element is ElementType) ? BuiltInParameter.IFC_TYPE_GUID : BuiltInParameter.IFC_GUID;
                                SetGUIDParameter(element, builtInParameter, elementIdToGUID.Value);
                            }

                            ProjectInfo projectInfo = doc.ProjectInformation;
                            if (projectInfo != null)
                            {
                                foreach (KeyValuePair<BuiltInParameter, string> elementIdToGUID in IFCStoredGUID.ProjectInfoParameterGUID)
                                {
                                    SetGUIDParameter(projectInfo, elementIdToGUID.Key, elementIdToGUID.Value);
                                }
                            }

                            transaction.Commit();
                        }
                        else
                            transaction.RollBack();
                        
                        // Remember last successful export location
                        m_mruExportPath = path;
                    }   
                }

                // The cancel button should cancel the export, not any "OK"ed setup changes.
                if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings || mainWindow.Result == IFCExportResult.Cancel)
                {
                    if (PotentiallyUpdatedConfigurations)
                    {
                        configurationsMap = mainWindow.GetModifiedConfigurations();
                        configurationsMap.UpdateSavedConfigurations();
                    }

                    // Remember last selected configuration
                    m_mruConfiguration = mainWindow.GetSelectedConfiguration().Name;
                }
            }
            catch (Exception e)
            {
                //TODO localization
                TaskDialog taskDialog = new TaskDialog("Error exporting IFC file");
                taskDialog.MainInstruction = "The IFC export process encountered an error.";
                taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
                taskDialog.ExpandedContent = e.ToString();
                taskDialog.Show();
            }
        }
Beispiel #50
0
        /// <summary>
        /// There are five override methods for creating walls.
        /// We assume you are using metric template, where you have
        /// "Level 1" and "Level 2"
        /// cf. Developer Guide page 117
        /// </summary>
        public List <Wall> CreateWalls_v1()
        {
            // Hard coding the size of the house for simplicity
            double width = 16;
            double depth = 16;

            // Get the levels we want to work on.
            // Note: hard coding for simplicity. Modify here you use a different template.
            Level level1 = ElementFiltering.FindElement(_doc, typeof(Level), "Level 1", null) as Level;

            if (level1 == null)
            {
                TaskDialog.Show("Create walls",
                                "Cannot find (Level 1). Maybe you use a different template? Try with DefaultMetric.rte.");
                return(null);
            }

            Level level2 = ElementFiltering.FindElement(_doc, typeof(Level), "Level 2", null) as Level;

            if (level2 == null)
            {
                TaskDialog.Show("Create walls",
                                "Cannot find (Level 2). Maybe you use a different template? Try with DefaultMetric.rte.");
                return(null);
            }

            // Set four corner of walls.
            // 5th point is for combenience to loop through.
            double dx = width / 2.0;
            double dy = depth / 2.0;

            List <XYZ> pts = new List <XYZ>(5);

            pts.Add(new XYZ(-dx, -dy, 0.0));
            pts.Add(new XYZ(dx, -dy, 0.0));
            pts.Add(new XYZ(dx, dy, 0.0));
            pts.Add(new XYZ(-dx, dy, 0.0));
            pts.Add(pts[0]);

            // Flag for structural wall or not.
            bool isStructural = false;

            // Save walls we create.
            List <Wall> walls = new List <Wall>(4);

            // Loop through list of points and define four walls.
            for (int i = 0; i <= 3; i++)
            {
                // Define a base curve from two points.
                Line baseCurve = Line.CreateBound(pts[i], pts[i + 1]);
                // Create a wall using the one of overloaded methods.

                //Wall aWall = _doc.Create.NewWall(baseCurve, level1, isStructural); // 2012
                Wall aWall = Wall.Create(_doc, baseCurve, level1.Id, isStructural); // since 2013

                // Set the Top Constraint to Level 2
                aWall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).Set(level2.Id);
                // Save the wall.
                walls.Add(aWall);
            }

            // This is important. we need these lines to have shrinkwrap working.
            _doc.Regenerate();
            _doc.AutoJoinElements();

            return(walls);
        }
Beispiel #51
0
        /// <summary>
        /// Get the Data
        /// </summary>
        private void ProcessData()
        {
            foreach (Autodesk.Revit.DB.View v in _s.Views)
              {
            try
            {
              this.progressBar1.Increment(1);
            }
            catch { }
            _s.ActiveUIDoc.ActiveView = v;
            try
            {
              List<Group> m_groups = _s.GetGroupsByView(v, this.checkBoxGroupsDetail.Checked, this.checkBoxGroupsModel.Checked);
              if (m_groups.Count > 0)
              {
            _s.GroupsByView.Add(v.Id.IntegerValue, m_groups);
              }
            }
            catch { }
            foreach (UIView x in _s.ActiveUIDoc.GetOpenUIViews())
            {
              try
              {
            if (x.ViewId.IntegerValue != v.Id.IntegerValue) x.Close();
              }
              catch { }
            }
              }
              if (_s.GroupsByView.Count > 0)
              {
            if (this.saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
              // Save the Data to File
              if (!string.IsNullOrEmpty(this.saveFileDialog1.FileName))
              {
            _s.SaveDataToCSV(this.saveFileDialog1.FileName);
              }
            }
              }
              else
              {
            using (TaskDialog x = new TaskDialog("No Results"))
            {
              x.TitleAutoPrefix = false;
              x.MainContent = "No views found in any views";
              x.MainInstruction = "Nothing to Report";
              x.Show();
            }
              }

              // Close
              this.Close();
        }
Beispiel #52
0
        /// <summary>
        /// Create walls with a rectangular profile from two coner points.
        /// </summary>
        public static List <Wall> CreateWalls(Document rvtDoc, XYZ pt1, XYZ pt2)
        {
            // Set the lower-left (x1, y1) and upper-right (x2, y2) corners of a house.
            double x1 = pt1.X;
            double x2 = pt2.X;

            if (pt1.X > pt2.X)
            {
                x1 = pt2.X;
                x2 = pt1.X;
            }

            double y1 = pt1.Y;
            double y2 = pt2.Y;

            if (pt1.Y > pt2.X)
            {
                y1 = pt2.Y;
                y2 = pt1.Y;
            }

            // Set four corner of walls from two croner point.
            // 5th point is for combenience to loop through.
            List <XYZ> pts = new List <XYZ>(5);

            pts.Add(new XYZ(x1, y1, pt1.Z));
            pts.Add(new XYZ(x2, y1, pt1.Z));
            pts.Add(new XYZ(x2, y2, pt1.Z));
            pts.Add(new XYZ(x1, y2, pt1.Z));
            pts.Add(pts[0]);

            // Get the levels we want to work on.
            // Note: hard coding for simplicity. Modify here you use a different template.
            Level level1 = ElementFiltering.FindElement(rvtDoc, typeof(Level), "Level 1", null) as Level;

            if (level1 == null)
            {
                TaskDialog.Show(
                    "Create walls", "Cannot find (Level 1). Maybe you use a different template? Try with DefaultMetric.rte."
                    );
                return(null);
            }

            Level level2 = ElementFiltering.FindElement(rvtDoc, typeof(Level), "Level 2", null) as Level;

            if (level2 == null)
            {
                TaskDialog.Show(
                    "Create walls", "Cannot find (Level 2). Maybe you use a different template? Try with DefaultMetric.rte."
                    );
                return(null);
            }

            // Flag for structural wall or not.
            bool isStructural = false;

            // Save walls we create.
            List <Wall> walls = new List <Wall>(4);

            // Loop through list of points and define four walls.
            for (int i = 0; i <= 3; i++)
            {
                // define a base curve from two points.
                Line baseCurve = Line.CreateBound(pts[i], pts[i + 1]);
                // create a wall using the one of overloaded methods.
                //Wall aWall = rvtDoc.Create.NewWall(baseCurve, level1, isStructural); // 2012
                Wall aWall = Wall.Create(rvtDoc, baseCurve, level1.Id, isStructural); // since 2013
                                                                                      // set the Top Constraint to Level 2
                aWall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).Set(level2.Id);
                // save the wall.
                walls.Add(aWall);
            }
            // This is important. we need these lines to have shrinkwrap working.
            rvtDoc.Regenerate();
            rvtDoc.AutoJoinElements();

            return(walls);
        }
Beispiel #53
0
        bool ILyrebirdService.CreateOrModify(List<RevitObject> incomingObjs, Guid uniqueId, string nickName)
        {
            lock (_locker)
            {
                TaskContainer.Instance.EnqueueTask(uiApp =>
                {
                    try
                    {
                        // Set the DisplayUnitTypes
                        Units units = uiApp.ActiveUIDocument.Document.GetUnits();
                        FormatOptions fo = units.GetFormatOptions(UnitType.UT_Length);
                        lengthDUT = fo.DisplayUnits;
                        fo = units.GetFormatOptions(UnitType.UT_Area);
                        areaDUT = fo.DisplayUnits;
                        fo = units.GetFormatOptions(UnitType.UT_Volume);
                        volumeDUT = fo.DisplayUnits;

                        // Find existing elements
                        List<ElementId> existing = FindExisting(uiApp.ActiveUIDocument.Document, uniqueId, incomingObjs[0].CategoryId, -1);
                        
                        // find if there's more than one run existing
                        Schema instanceSchema = Schema.Lookup(instanceSchemaGUID);
                        List<int> runIds = new List<int>();
                        List<Runs> allRuns = new List<Runs>();
                        if (instanceSchema != null)
                        {
                            foreach (ElementId eid in existing)
                            {
                                Element e = uiApp.ActiveUIDocument.Document.GetElement(eid);
                                // Find the run ID
                                Entity entity = e.GetEntity(instanceSchema);
                                if (entity.IsValid())
                                {
                                    Field f = instanceSchema.GetField("RunID");
                                    int tempId = entity.Get<int>(f);
                                    if (!runIds.Contains(tempId))
                                    {
                                        runIds.Add(tempId);
                                        string familyName = string.Empty;
                                        if (e.Category.Id.IntegerValue == -2000011)
                                        {
                                            Wall w = e as Wall;
                                            familyName = w.Category.Name + " : " + w.WallType.Name;
                                        }
                                        else if (e.Category.Id.IntegerValue == -2000032)
                                        {
                                            Floor flr = e as Floor;
                                            familyName = flr.Category.Name + " : " + flr.FloorType.Name;
                                        }
                                        else if (e.Category.Id.IntegerValue == -2000035)
                                        {
                                            RoofBase r = e as RoofBase;
                                            familyName = r.Category.Name + " : " + r.RoofType.Name;
                                        }
                                        else if (e.Category.Id.IntegerValue == -2000240)
                                        {
                                            Level lvl = e as Level;
                                            familyName = lvl.Category.Name + " : " + lvl.LevelType.Name;
                                        }
                                        else if (e.Category.Id.IntegerValue == -2000220)
                                        {
                                            Grid g = e as Grid;
                                            familyName = g.Category.Name + " : " + g.GridType.Name;
                                        }
                                        else
                                        {
                                            FamilyInstance famInst = e as FamilyInstance;
                                            familyName = famInst.Symbol.Family.Name + " : " + famInst.Symbol.Name;
                                        }
                                        Runs run = new Runs(tempId, "Run" + tempId.ToString(), familyName);
                                        allRuns.Add(run);
                                    }
                                }
                            }
                        }


                        if (runIds != null && runIds.Count > 0)
                        {
                            runIds.Sort((x, y) => x.CompareTo(y));
                            int lastId = 0;
                            lastId = runIds.Last();
                            ModifyForm mform = new ModifyForm(this, allRuns);
                            mform.ShowDialog();

                            // Get the set of existing elements to reflect the run choice.
                            List<ElementId> existingRunEID = FindExisting(uiApp.ActiveUIDocument.Document, uniqueId, incomingObjs[0].CategoryId, runId);

                            // modBehavior = 0, Modify the selected run
                            if (modBehavior == 0)
                            {
                                if (existingRunEID.Count == incomingObjs.Count)
                                {
                                    // just modify
                                    ModifyObjects(incomingObjs, existingRunEID, uiApp.ActiveUIDocument.Document, uniqueId, true, nickName, runId);
                                }
                                else if (existingRunEID.Count > incomingObjs.Count)
                                {
                                    // Modify and Delete
                                    List<ElementId> modObjects = new List<ElementId>();
                                    List<ElementId> removeObjects = new List<ElementId>();

                                    int i = 0;
                                    while (i < incomingObjs.Count)
                                    {
                                        modObjects.Add(existingRunEID[i]);
                                        i++;
                                    }
                                    while (existingRunEID != null && i < existingRunEID.Count)
                                    {
                                        Element e = uiApp.ActiveUIDocument.Document.GetElement(existing[i]);
                                        // Find the run ID
                                        Entity entity = e.GetEntity(instanceSchema);
                                        if (entity.IsValid())
                                        {
                                            removeObjects.Add(existingRunEID[i]);
                                            //Field f = instanceSchema.GetField("RunID");
                                            //int tempId = entity.Get<int>(f);
                                            //if (tempId == runId)
                                            //{
                                            //    removeObjects.Add(existing[i]);
                                            //}
                                        }
                                        i++;
                                    }
                                    try
                                    {
                                        ModifyObjects(incomingObjs, modObjects, uiApp.ActiveUIDocument.Document, uniqueId, true, nickName, runId);
                                        DeleteExisting(uiApp.ActiveUIDocument.Document, removeObjects);
                                    }
                                    catch (Exception ex)
                                    {
                                        Debug.WriteLine(ex.Message);
                                    }
                                }
                                else if (existingRunEID.Count < incomingObjs.Count)
                                {
                                    // modify and create
                                    // create and modify
                                    List<RevitObject> existingObjects = new List<RevitObject>();
                                    List<RevitObject> newObjects = new List<RevitObject>();

                                    int i = 0;
                                    Debug.Assert(existing != null, "existing != null");
                                    while (i < existingRunEID.Count)
                                    {
                                        existingObjects.Add(incomingObjs[i]);
                                        i++;
                                    }
                                    while (i < incomingObjs.Count)
                                    {
                                        newObjects.Add(incomingObjs[i]);
                                        i++;
                                    }
                                    try
                                    {
                                        ModifyObjects(existingObjects, existingRunEID, uiApp.ActiveUIDocument.Document, uniqueId, true, nickName, runId);
                                        CreateObjects(newObjects, uiApp.ActiveUIDocument.Document, uniqueId, runId, nickName);
                                    }
                                    catch (Exception ex)
                                    {
                                        Debug.WriteLine(ex.Message);
                                    }
                                }
                            }
                            // modBehavior = 1, Create a new run
                            else if (modBehavior == 1)
                            {
                                // Just send everything to create a new Run.
                                try
                                {
                                    CreateObjects(incomingObjs, uiApp.ActiveUIDocument.Document, uniqueId, lastId + 1, nickName);
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine("Error", ex.Message);
                                }
                            }

                            // modBehavior = 3, cancel/ignore
                        }
                        else
                        {
                            TaskDialog dlg = new TaskDialog("Warning") { MainInstruction = "Incoming Data" };
                            RevitObject existingObj1 = incomingObjs[0];
                            bool profileWarning1 = (existingObj1.CategoryId == -2000011 && existingObj1.Curves.Count > 1) || existingObj1.CategoryId == -2000032 || existingObj1.CategoryId == -2000035;
                            if (existing == null || existing.Count == 0)
                            {
                                dlg.MainContent = "Data is being sent to Revit from another application using Lyrebird." +
                                    " This data will be used to create " + incomingObjs.Count.ToString(CultureInfo.InvariantCulture) + " elements.  How would you like to proceed?";
                                dlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Create new elements");
                                dlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel");
                            }

                            TaskDialogResult result1 = dlg.Show();
                            if (result1 == TaskDialogResult.CommandLink1)
                            {
                                // Create new
                                try
                                {
                                    CreateObjects(incomingObjs, uiApp.ActiveUIDocument.Document, uniqueId, 0, nickName);
                                }
                                catch (Exception ex)
                                {
                                    TaskDialog.Show("Error", ex.Message);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        TaskDialog.Show("Test", ex.Message);
                        Debug.WriteLine(ex.Message);
                    }
                    finally
                    {
                        Monitor.Pulse(_locker);
                    }
                });
                Monitor.Wait(_locker, Properties.Settings.Default.infoTimeout);
            }
            return true;
        }
Beispiel #54
0
        /// <summary>
        /// Add a roof over the rectangular profile of the walls we created earlier.
        /// </summary>
        public static void AddRoof(Document rvtDoc, List <Wall> walls)
        {
            // Hard coding the roof type we will use.
            // e.g., "Basic Roof: Generic - 400mm"
            const string roofFamilyName        = "Basic Roof";
            const string roofTypeName          = Util.Constant.RoofTypeName;
            const string roofFamilyAndTypeName = roofFamilyName + ": " + roofTypeName;

            // Find the roof type
            RoofType roofType =
                ElementFiltering.FindFamilyType(
                    rvtDoc, typeof(RoofType), roofFamilyName, roofTypeName, null
                    ) as RoofType;

            if (roofType == null)
            {
                TaskDialog.Show(
                    "Add roof", "Cannot find (" + roofFamilyAndTypeName +
                    "). Maybe you use a different template? Try with DefaultMetric.rte.");
            }

            // Wall thickness to adjust the footprint of the walls
            // to the outer most lines.
            // Note: this may not be the best way.
            // but we will live with this for this exercise.
            //Dim wallThickness As Double = _
            //walls(0).WallType.CompoundStructure.Layers.Item(0).Thickness() ' 2011
            double wallThickness = walls[0].WallType.GetCompoundStructure().GetLayers()[0].Width;

            // 2012
            double     dt  = wallThickness / 2.0;
            List <XYZ> dts = new List <XYZ>(5);

            dts.Add(new XYZ(-dt, -dt, 0.0));
            dts.Add(new XYZ(dt, -dt, 0.0));
            dts.Add(new XYZ(dt, dt, 0.0));
            dts.Add(new XYZ(-dt, dt, 0.0));
            dts.Add(dts[0]);

            // Set the profile from four walls
            CurveArray footPrint = new CurveArray();

            for (int i = 0; i <= 3; i++)
            {
                LocationCurve locCurve = (LocationCurve)walls[i].Location;
                XYZ           pt1      = locCurve.Curve.GetEndPoint(0) + dts[i];
                XYZ           pt2      = locCurve.Curve.GetEndPoint(1) + dts[i + 1];
                Line          line     = Line.CreateBound(pt1, pt2);
                footPrint.Append(line);
            }

            // Get the level2 from the wall.

            ElementId idLevel2 = walls[0].get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId();

            //Level level2 = (Level)_doc.get_Element(idLevel2); // 2012
            Level level2 = rvtDoc.GetElement(idLevel2) as Level; // since 2013

            // Footprint to model curve mapping.

            ModelCurveArray mapping = new ModelCurveArray();

            // Create a roof.

            FootPrintRoof aRoof = rvtDoc.Create.NewFootPrintRoof(
                footPrint, level2, roofType, out mapping);

            // Set the slope.

            /////////////////////////////////////////////////
            ///new mapping
            /////////////////////////////////////////////////
            //find double slope A use pythagorum theroum
            // set lines a and b, find c

            //double b = 4.00; // height should be 4' from center
            ////
            //LocationCurve wallCurv = (LocationCurve)walls[3].Location;
            //double a = wallCurv.Curve.Length / 2.00;
            ////

            //double c = Math.Sqrt(a * a + b * b);
            //double angleB = Math.Acos(c);


            // set the gable roof slope

            ModelCurveArray mappingNew  = new ModelCurveArray();
            ModelCurve      gableCurve1 = mapping.get_Item(1);
            ModelCurve      gableCurve2 = mapping.get_Item(3);
            ModelCurve      aLine       = mapping.get_Item(0);

            //double a = Math.Truncate(gableCurve1.GeometryCurve.Length / 2.00 * 100) / 100;
            double a             = aLine.GeometryCurve.Length / 2.00;
            double b             = 4.00;
            double angleBRadians = Math.Atan(b / a);
            double angleB        = Math.Tan(angleBRadians);

            TaskDialog.Show("Tests",
                            "lenght a: " + a +
                            " length b: " + b +
                            " Radians: " + angleBRadians +
                            " angle B: " + angleB);


            aRoof.set_DefinesSlope(gableCurve1, true);
            aRoof.set_SlopeAngle(gableCurve1, angleB);
            aRoof.set_DefinesSlope(gableCurve2, true);
            aRoof.set_SlopeAngle(gableCurve2, angleB);

            #region Notes
            //foreach (ModelCurve modelCurve in mapping)
            //{
            //  aRoof.set_DefinesSlope(modelCurve, true);
            //  aRoof.set_SlopeAngle(modelCurve, 0.5);
            //}


            // Performed automatically by transaction commit.
            //rvtDoc.Regenerate();
            //rvtDoc.AutoJoinElements();
            #endregion
        }
Beispiel #55
0
        public void Execute( UpdaterData data )
        {
            // we need to modify something here, or the
              // updater requirement will not be saved in
              // the document.

              Document doc = data.GetDocument();

              //Transaction t = new Transaction( doc,
              //  "Dummy Updater Transaction" );

              //t.Start();
              //t.Commit();

              //if( 0 < data.GetModifiedElementIds().Count )
              //{
              //  foreach( ElementId id in data.GetModifiedElementIds() )
              //  {
              //    Element e = doc.get_Element( id );
              //    Parameter p = e.get_Parameter( BuiltInParameter.ALL_MODEL_MARK );
              //    string s = p.AsString();
              //    p.Set( s + " modified by " + ToString() );
              //  }
              //}

              ProjectInfo a
            = new FilteredElementCollector( doc )
              .OfClass( typeof( ProjectInfo ) )
              .FirstElement() as ProjectInfo;

              try
              {

              Parameter p = a.get_Parameter(BuiltInParameter.PROJECT_STATUS);
              string s = p.AsString();
              if (s == null) s = string.Empty;
              if (0 < s.Length)
              {
              s += " ";
              }
              p.Set(s + "modified by " + ToString());

              Debug.Print("DummyUpdater.Execute: "
                      + GetUpdaterName() + " "
                      + GetUpdaterId());
              }
              catch (Exception ex)
              {
              var td = new TaskDialog("Error");
              td.MainInstruction = ex.Message;
              td.ExpandedContent = ex.ToString();
              td.Show();
              }
        }
Beispiel #56
0
        public KeyValuePair <List <ElementId>, List <double> > Graph(Document doc, IList <ElementId> RoomForbid)
        {
            var levelid = ViewLevel(doc);
            var rooms   = GetRoomsOnLevel(doc, levelid);
            var doors   = GetAllDoors(doc, levelid);
            var exits   = GetExits(doc);
            var RoomIDs = new List <ElementId>();
            var DoorIDs = new List <ElementId>();
            var AllIDs  = new List <ElementId>();

            foreach (ElementId d in doors)
            {
                DoorIDs.Add(d);
                AllIDs.Add(d);
            }
            foreach (Room r in rooms)
            {
                RoomIDs.Add(r.Id);
                AllIDs.Add(r.Id);
            }


            var mat_dim = RoomIDs.Count + DoorIDs.Count;

            int[,] mat = new int[100, 100];
            for (int i = 0; i < 100; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    mat[i, j] = 0;
                }
            }

            foreach (ElementId id in DoorIDs)
            {
                int            count   = 0;
                Element        door    = doc.GetElement(id);
                FamilyInstance doorfam = door as FamilyInstance;
                Room           temp1   = doorfam.FromRoom;
                Room           temp2   = doorfam.ToRoom;
                int            offset  = DoorIDs.Count;
                int            dindex  = DoorIDs.FindIndex(a => a.IntegerValue == id.IntegerValue);
                foreach (ElementId rid in RoomIDs)
                {
                    int rindex = RoomIDs.FindIndex(a => a.IntegerValue == rid.IntegerValue);
                    if (temp1 != null && temp1.Id == rid)
                    {
                        mat[dindex, offset + rindex] = 1; count++;
                        continue;
                    }
                    if (temp2 != null && temp2.Id == rid)
                    {
                        mat[dindex, offset + rindex] = 1; count++;
                        continue;
                    }
                }
            }


            var RoomLocs   = new List <XYZ>();
            var DoorLocs   = new List <XYZ>();
            var AllLocs    = new List <XYZ>();
            var LocsForbid = new List <XYZ>();

            foreach (ElementId id in DoorIDs)
            {
                Element       r   = doc.GetElement(id);
                LocationPoint loc = r.Location as LocationPoint;
                XYZ           xyz = loc.Point;
                DoorLocs.Add(xyz);
                AllLocs.Add(xyz);
            }
            foreach (ElementId id in RoomIDs)
            {
                Element       r   = doc.GetElement(id);
                LocationPoint loc = r.Location as LocationPoint;
                XYZ           xyz = loc.Point;
                RoomLocs.Add(xyz);
                AllLocs.Add(xyz);
                if (RoomForbid.Contains(id))
                {
                    LocsForbid.Add(xyz);
                }
            }

            double[,] ajm = new double[100, 100];
            for (int i = 0; i < mat_dim; i++)
            {
                for (int j = 0; j < mat_dim; j++)
                {
                    ajm[i, j] = -1;
                }
            }
            IList <Curve>[,] pathMap = new IList <Curve> [mat_dim, mat_dim];
            using (Transaction trans = new Transaction(doc))
            {
                trans.Start("CAL");
                int  offset = DoorIDs.Count;
                View view   = doc.ActiveView;
                for (int i = 0; i < mat_dim; i++)
                {
                    for (int j = 0; j < mat_dim; j++)
                    {
                        if (mat[i, j] == 0)
                        {
                            continue;
                        }
                        if (LocsForbid.Contains(RoomLocs[j - offset]))
                        {
                            continue;
                        }
                        PathOfTravel p = PathOfTravel.Create(view, DoorLocs[i], RoomLocs[j - offset]);
                        if (p == null)
                        {
                            continue;
                        }
                        var crs = p.GetCurves();
                        pathMap[i, j] = crs;
                        ajm[i, j]     = calDis(crs);
                        ajm[j, i]     = ajm[i, j];
                    }
                }
                trans.Commit();
            }

            //for (int i = DoorIDs.Count; i < mat_dim; i++) {
            //    int tmp = 0;
            //    for (int j = 0; j < mat_dim; j++)
            //        if (ajm[i, j] > 0) tmp++;
            //    if(tmp==0) TaskDialog.Show("Revit", RoomIDs[i-DoorIDs.Count].ToString());
            //}

            foreach (ElementId fid in RoomForbid)
            {
                Element tmp = doc.GetElement(fid);
                if (!tmp.Category.Name.ToLower().Contains("room"))
                {
                    continue;
                }
                int index = AllIDs.FindIndex(a => a.IntegerValue == fid.IntegerValue);
                for (int i = 0; i < AllIDs.Count; i++)
                {
                    ajm[index, i] = -1;
                    ajm[i, index] = -1;
                }
                TaskDialog.Show("revit", "delete a room");
            }
            for (int i = 0; i < AllIDs.Count; i++)
            {
                for (int j = 0; j < AllIDs.Count; j++)
                {
                    if (i == j)
                    {
                        ajm[i, j] = 0;
                        continue;
                    }
                    if (ajm[i, j] < 0)
                    {
                        ajm[i, j] = MAX_NUM;
                    }
                }
            }
            //string ttt = "";
            //for (int i = 0; i < AllIDs.Count; i++) {
            //    for (int j = 0; j < AllIDs.Count; j++)
            //        ttt += ajm[i, j].ToString() + "  ";

            //    ttt += "\n";
            //}
            //TaskDialog.Show("revit", ttt);
            var dis       = GetFloyd(ajm, mat_dim);
            var final_rel = new List <double>();
            var final_des = new List <int>();

            foreach (ElementId rid in RoomIDs)
            {
                double len      = MAX_NUM;
                int    des_node = -1;
                int    x        = AllIDs.FindIndex(a => a.IntegerValue == rid.IntegerValue);
                foreach (ElementId did in exits)
                {
                    int    y       = AllIDs.FindIndex(a => a.IntegerValue == did.IntegerValue);
                    double tmp_len = dis[x, y].length;
                    if (len >= tmp_len)
                    {
                        len      = tmp_len;
                        des_node = y;
                    }
                }
                final_rel.Add(len);
                final_des.Add(des_node);
            }

            var Final_path = new List <List <int> >();

            for (int i = 0; i < RoomIDs.Count; i++)
            {
                var rid = RoomIDs[i];
                if (final_rel[i] > MAX_NUM - 1)
                {
                    Final_path.Add(null);
                    continue;
                }
                var nodes = new List <int>();
                var dst   = final_des[i];
                int x     = AllIDs.FindIndex(a => a.IntegerValue == rid.IntegerValue);
                nodes.Add(dst);
                int pre = dis[x, dst].pre;
                while (true)
                {
                    nodes.Add(pre);
                    if (pre == x)
                    {
                        break;
                    }
                    pre = dis[x, pre].pre;
                }
                nodes.Reverse();
                Final_path.Add(nodes);
            }

            return(new KeyValuePair <List <ElementId>, List <double> >(RoomIDs, final_rel));
        }
Beispiel #57
0
 public Result Execute( ExternalCommandData cmdData, ref string msg, ElementSet elems )
 {
     Assembly a = Assembly.GetExecutingAssembly();
       string version = a.GetName().Version.ToString();
       TaskDialog helloDlg = new TaskDialog( "Autodesk Revit" );
       helloDlg.MainContent = "Hello World from " + a.Location + " v" + version;
       helloDlg.Show();
       return Result.Cancelled;
 }
Beispiel #58
0
        public static bool OpenOrCreateParameter(Document doc, string paramName, string paramGroup, CategorySet categorySet)
        {
            Transaction trans = new Transaction(doc);

            trans.Start("Creating shared parameter " + paramName);

            // Check on one element if the parameter already exist
            FilteredElementCollector coll = new FilteredElementCollector(doc);

            coll.OfClass(typeof(Wall));
            Element ele = coll.FirstElement();

            if (ele != null)
            {
                if (ele.GetParameters(paramName).Count > 0)
                {
                    return(true);
                }
            }

            // Create if not exist
            try
            {
                if (!System.IO.File.Exists(SharedParameterFilePath))
                {
                    System.IO.File.Create(SharedParameterFilePath).Close();
                }
            }
            catch
            {
                TaskDialog.Show("Unable to create Shared Parameter file",
                                "The plug-in could not create the required shared " +
                                "parameter file at " + SharedParameterFilePath +
                                ". Command cancelled.");
                return(false);
            }

            // Open the shared parameter file
            doc.Application.SharedParametersFilename = SharedParameterFilePath;
            DefinitionFile sharedParamDefFile = doc.Application.OpenSharedParameterFile();

            // Create a category set to apply the parameter
            //CategorySet categorySet = doc.Application.Create.NewCategorySet();
            //categorySet.Insert(doc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls));
            Binding binding = doc.Application.Create.NewInstanceBinding(categorySet);

            // Create a shared parameter group
            string          groupName           = paramGroup;
            DefinitionGroup sharedParamDefGroup = sharedParamDefFile.Groups.get_Item(groupName);

            if (sharedParamDefGroup == null)
            {
                sharedParamDefGroup = sharedParamDefFile.Groups.Create(groupName);
            }

            // Create the parameter definition for small openings
            // Check if exists, create if required
            Definition paramSmallOpeningDef = sharedParamDefGroup.Definitions.get_Item(paramName);

            if (paramSmallOpeningDef == null)
            {
                ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions(paramName, ParameterType.Text);
                paramSmallOpeningDef = sharedParamDefGroup.Definitions.Create(options);
            }

            // Apply parameter for small openings to walls
            doc.ParameterBindings.Insert(paramSmallOpeningDef, binding);

            trans.Commit();

            return(true);
        }
        public static TaskDialogResult postWarning(string title, string instruction, string content = null)
        {
            if (title == null || instruction == null)
            return TaskDialogResult.None;

             TaskDialog tdlg = new TaskDialog(title);
             tdlg.MainInstruction = instruction;
             tdlg.MainContent = content;
             tdlg.AllowCancellation = true;
             tdlg.CommonButtons = TaskDialogCommonButtons.Close;
             tdlg.DefaultButton = TaskDialogResult.Close;
             tdlg.TitleAutoPrefix = false;
             return tdlg.Show();
        }
        } // end of PopulateProjectParameterData

        #endregion // Private helper methods

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

            if (doc.IsFamilyDocument)
            {
                message = "The document must be a project document.";
                return(Result.Failed);
            }

            // Get the (singleton) element that is the
            // ProjectInformation object.  It can only have
            // instance parameters bound to it, and it is
            // always guaranteed to exist.

            Element projectInfoElement
                = new FilteredElementCollector(doc)
                  .OfCategory(BuiltInCategory.OST_ProjectInformation)
                  .FirstElement();

            // Get the first wall type element.  It can only
            // have type parameters bound to it, and there is
            // always guaranteed to be at least one of these.

            Element firstWallTypeElement
                = new FilteredElementCollector(doc)
                  .OfCategory(BuiltInCategory.OST_Walls)
                  .WhereElementIsElementType()
                  .FirstElement();

            CategorySet categories     = null;
            Parameter   foundParameter = null;

            // Get the list of information about all project
            // parameters, calling our helper method, below.

            List <ProjectParameterData> projectParametersData
                = GetProjectParameterData(doc);

            // In order to be able to query whether or not a
            // project parameter is shared or not, and if it
            // is shared then what it's GUID is, we must ensure
            // it exists in the Parameters collection of an
            // element.
            // This is because we cannot query this information
            // directly from the project parameter bindings
            // object.
            // So each project parameter will attempt to be
            // temporarily bound to a known object so a
            // Parameter object created from it will exist
            // and can be queried for this additional
            // information.

            foreach (ProjectParameterData projectParameterData
                     in projectParametersData)
            {
                if (projectParameterData.Definition != null)
                {
                    categories = projectParameterData.Binding.Categories;
                    if (!categories.Contains(projectInfoElement.Category))
                    {
                        // This project parameter is not already
                        // bound to the ProjectInformation category,
                        // so we must temporarily bind it so we can
                        // query that object for it.

                        using (Transaction tempTransaction
                                   = new Transaction(doc))
                        {
                            tempTransaction.Start("Temporary");

                            // Try to bind the project parameter do
                            // the project information category,
                            // calling our helper method, below.

                            if (AddProjectParameterBinding(
                                    doc, projectParameterData,
                                    projectInfoElement.Category))
                            {
                                // successfully bound
                                foundParameter
                                    = projectInfoElement.get_Parameter(
                                          projectParameterData.Definition);

                                if (foundParameter == null)
                                {
                                    // Must be a shared type parameter,
                                    // which the API reports that it binds
                                    // to the project information category
                                    // via the API, but doesn't ACTUALLY
                                    // bind to the project information
                                    // category.  (Sheesh!)

                                    // So we must use a different, type
                                    // based object known to exist, and
                                    // try again.

                                    if (!categories.Contains(
                                            firstWallTypeElement.Category))
                                    {
                                        // Add it to walls category as we
                                        // did with project info for the
                                        // others, calling our helper
                                        // method, below.

                                        if (AddProjectParameterBinding(
                                                doc, projectParameterData,
                                                firstWallTypeElement.Category))
                                        {
                                            // Successfully bound
                                            foundParameter
                                                = firstWallTypeElement.get_Parameter(
                                                      projectParameterData.Definition);
                                        }
                                    }
                                    else
                                    {
                                        // The project parameter was already
                                        // bound to the Walls category.
                                        foundParameter
                                            = firstWallTypeElement.get_Parameter(
                                                  projectParameterData.Definition);
                                    }

                                    if (foundParameter != null)
                                    {
                                        PopulateProjectParameterData(
                                            foundParameter,
                                            projectParameterData);
                                    }
                                    else
                                    {
                                        // Wouldn't bind to the walls
                                        // category or wasn't found when
                                        // already bound.
                                        // This should probably never happen?

                                        projectParameterData.IsSharedStatusKnown
                                            = false; // Throw exception?
                                    }
                                }
                                else
                                {
                                    // Found the correct parameter
                                    // instance on the Project
                                    // Information object, so use it.

                                    PopulateProjectParameterData(
                                        foundParameter,
                                        projectParameterData);
                                }
                            }
                            else
                            {
                                // The API reports it couldn't bind
                                // the parameter to the ProjectInformation
                                // category.
                                // This only happens with non-shared
                                // Project parameters, which have no
                                // GUID anyway.

                                projectParameterData.IsShared            = false;
                                projectParameterData.IsSharedStatusKnown = true;
                            }
                            tempTransaction.RollBack();
                        }
                    }
                    else
                    {
                        // The project parameter was already bound
                        // to the Project Information category.

                        foundParameter
                            = projectInfoElement.get_Parameter(
                                  projectParameterData.Definition);

                        if (foundParameter != null)
                        {
                            PopulateProjectParameterData(
                                foundParameter, projectParameterData);
                        }
                        else
                        {
                            // This will probably never happen.

                            projectParameterData.IsSharedStatusKnown
                                = false; // Throw exception?
                        }
                    }
                } // Whether or not the Definition object could be found
            }     // For each original project parameter definition

            StringBuilder sb = new StringBuilder();

            // Build column headers

            sb.AppendLine("PARAMETER NAME\tIS SHARED?\tGUID");

            // Add each row.

            foreach (ProjectParameterData projectParameterData
                     in projectParametersData)
            {
                sb.Append(projectParameterData.Name);
                sb.Append("\t");

                if (projectParameterData.IsSharedStatusKnown)
                {
                    sb.Append(projectParameterData.IsShared.ToString());
                }
                else
                {
                    sb.Append("<Unknown>");
                }

                if (projectParameterData.IsSharedStatusKnown &&
                    projectParameterData.IsShared)
                {
                    sb.Append("\t");
                    sb.Append(projectParameterData.GUID);
                }
                sb.AppendLine();
            }

            System.Windows.Clipboard.Clear();
            System.Windows.Clipboard.SetText(sb.ToString());

            TaskDialog resultsDialog = new TaskDialog(
                "Results are in the Clipboard");

            resultsDialog.MainInstruction
                = "Results are in the Clipboard";

            resultsDialog.MainContent
                = "Paste the clipboard into a spreadsheet "
                  + "program to see the results.";

            resultsDialog.Show();

            return(Result.Succeeded);
        }