示例#1
0
        public static int CheckUse(string famname)
        {
            if (File.Exists(famname))
            {
                TaskDialog d = new TaskDialog("File Exists!");
                d.MainInstruction = "The File Exists!";
                d.MainContent     = "The family '" + famname.Split('\\').Last() + "' already exists! Would you like to replace it?";
                d.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Yes");
                d.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "No");
                d.CommonButtons = TaskDialogCommonButtons.Close;
                d.DefaultButton = TaskDialogResult.Close;

                TaskDialogResult tResult = d.Show();

                if (TaskDialogResult.CommandLink1 == tResult)
                {
                    return(1);
                }
                else
                {
                    return(2);
                }
            }
            return(0);
        }
示例#2
0
        public void About(UIDocument uidoc)
        {
            TaskDialog about = new TaskDialog("About...");

            about.MainContent = "Lame Duck - 2020";
            about.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Made by Pierpaolo Canini");
            about.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Lame Duck GitHub");
            about.MainInstruction = "Hi!";

            TaskDialogResult tdResult = about.Show();

            bool Yes = true;

            if (TaskDialogResult.CommandLink1 == tdResult)
            {
                Yes = true;
            }
            else if (TaskDialogResult.CommandLink2 == tdResult)
            {
                Yes = false;
            }
            else
            {
                return;
            }

            if (Yes)
            {
                System.Diagnostics.Process.Start("https://www.linkedin.com/in/pierpaolocanini/");
            }
            if (!Yes)
            {
                System.Diagnostics.Process.Start("https://github.com/pierpaolo-canini/");
            }
        }
        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);
        }
示例#4
0
        private Selection inputeDialog()
        {
            // An option window for the user
            TaskDialog taskWindow = new TaskDialog("Choose a geometry: ");

            taskWindow.MainContent = "Which geometry would you like to draw?";

            // Add commmandLink options to task dialog
            taskWindow.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Sphere");
            taskWindow.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Pyramid");

            // Set common buttons and default button. If no CommonButton or CommandLink is added,
            // task dialog will show a Close button by default
            taskWindow.CommonButtons = TaskDialogCommonButtons.Close;
            taskWindow.DefaultButton = TaskDialogResult.Close;

            TaskDialogResult tResult = taskWindow.Show();

            if (TaskDialogResult.CommandLink1 == tResult)
            {
                return(Selection.Sphere);
            }
            else if (TaskDialogResult.CommandLink2 == tResult)
            {
                return(Selection.Pyramid);
            }
            else
            {
                return(Selection.dummy);
            }
        }
        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;

            TaskDialog cuadro = new TaskDialog("Sincronizar Ids");//, "Esta herramienta permite rellenar un parámetro de ejemplar llamado 'id' con el valor del Id del elemento");

            cuadro.MainInstruction = "Sincronizar Ids de ejemplares de familia";
            cuadro.MainContent     = "Esta herramienta permite rellenar un parámetro de ejemplar llamado 'id' con el valor del Id del elemento. Nota: el parámetro debe ser de tipo ENTERO ¿Desea continuar?";
            cuadro.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Continuar");
            cuadro.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancelar");
            //cuadro.CommonButtons = TaskDialogCommonButtons.Cancel;
            //cuadro.DefaultButton = TaskDialogResult.Cancel;
            TaskDialogResult resultado = cuadro.Show();

            if (TaskDialogResult.CommandLink1 == resultado)
            {
                List <Element> instancias = Tools.GetInstances(doc);
                Tools.SincronizarIdsEjemplares(doc, instancias);
                TaskDialog.Show("Sincronizar Ids", "Proceso terminado con éxito");
            }

            return(Result.Succeeded);
        }
示例#6
0
        public static void ManageFileAssociations()
        {
            using (var td = new TaskDialog <string>())
            {
                td.MainInstruction = "Choose an option.";
                td.MainIcon        = MsgIcon.Shield;

                td.AddCommandLink("Register video file extensions", "video");
                td.AddCommandLink("Register audio file extensions", "audio");
                td.AddCommandLink("Register audio file extensions", "image");
                td.AddCommandLink("Unregister file extensions", "unreg");

                string result = td.Show();

                if (!string.IsNullOrEmpty(result))
                {
                    using (var proc = new Process())
                    {
                        proc.StartInfo.FileName  = System.Windows.Forms.Application.ExecutablePath;
                        proc.StartInfo.Arguments = "--reg-file-assoc " + result;
                        proc.StartInfo.Verb      = "runas";
                        try { proc.Start(); } catch { }
                    }
                }
            }
        }
        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;
        }
示例#8
0
        public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
        {
            using
            (
                var taskDialog = new TaskDialog(MethodBase.GetCurrentMethod().DeclaringType.FullName)
            {
                Title = "About",
                MainIcon = TaskDialogIcons.IconInformation,
                TitleAutoPrefix = true,
                AllowCancellation = true,
                MainInstruction = "Rhino.Inside© for Revit",
                MainContent = $"Version {Addin.DisplayVersion}",
                CommonButtons = TaskDialogCommonButtons.Ok,
                DefaultButton = TaskDialogResult.Ok
            }
            )
            {
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Read license");
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "See source code");
                switch (taskDialog.Show())
                {
                case TaskDialogResult.CommandLink1:
                    using (System.Diagnostics.Process.Start(@"https://github.com/mcneel/rhino.inside-revit/blob/master/LICENSE")) { }
                    break;

                case TaskDialogResult.CommandLink2:
                    using (System.Diagnostics.Process.Start(@"https://github.com/mcneel/rhino.inside-revit/blob/master/README.md")) { }
                    break;
                }
            }

            return(Result.Succeeded);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            _uiDoc = commandData.Application.ActiveUIDocument;
            var doc = _uiDoc.Document;

            if (doc.ActiveView.ViewType != ViewType.ProjectBrowser)
            {
                using (var trg = new TransactionGroup(doc, "Копирование значений имя системы"))
                {
                    trg.Start();
                    foreach (var cat in GetDuctCategories())
                    {
                        var elementsByCat = new FilteredElementCollector(doc)
                                            .OfCategory(cat)
                                            .WhereElementIsNotElementType()
                                            .ToList();
                        if (elementsByCat.Count > 0)
                        {
                            RevitFunctions.CopySystemNameValue(doc, elementsByCat);
                        }
                    }

                    trg.Assimilate();
                }

                var td = new TaskDialog("Copy views")
                {
                    Id                = "ID_TaskDialog_Copy_Views",
                    MainIcon          = TaskDialogIcon.TaskDialogIconInformation,
                    Title             = "Создание копий видов с применением фильтра",
                    TitleAutoPrefix   = false,
                    AllowCancellation = true,
                    MainInstruction   =
                        "Данные из параметра Имя системы для всех элементов систем воздуховодов скопированы",
                    MainContent = "Хотите создать копии текущего вида с применением фильтров по системам?"
                };

                td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Да, создать фильтры и виды");
                td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Нет");
                var tdRes = td.Show();
                if (tdRes != TaskDialogResult.CommandLink1)
                {
                    return(Result.Cancelled);
                }
                var sysNameParamElement = new FilteredElementCollector(doc)
                                          .OfClass(typeof(ParameterElement))
                                          .FirstOrDefault(p => p.Name == "ИмяСистемы");
                var sysNameParam = sysNameParamElement as ParameterElement;
                foreach (var systemName in GetDuctSystemNames(doc))
                {
                    CreateFilterForDuctSystem(doc, sysNameParam, systemName);
                }
            }
            else
            {
                TaskDialog.Show("Предупреждение", "Не активирован вид для создания копий с применением фильтра");
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// The DocumentSaving callback.  This callback checks if at least one new revision has been added, and if not
        /// shows instructions to the user to deal with the situation.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void OnSavingPromptForRevisions(object sender, DocumentSavingEventArgs args)
        {
            Document      doc   = (Document)sender;
            UIApplication uiApp = new UIDocument(doc).Application;

            if (doc.IsModified)
            {
                // Compare number of revisions with saved count
                int revisionCount = GetRevisionCount(doc);
                if (revisionCount <= storedRevisionCount)
                {
                    // Show dialog with explanation and options
                    TaskDialog td = new TaskDialog("Revisions not created.");
                    td.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                    td.MainInstruction = "Changes have been made to this document, but no new revision has been created.";
                    td.ExpandedContent = "Because the document has been released, it is typically required to issue a new " +
                                         "revision number with any change.";
                    td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Add revision now");
                    td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel save");
                    td.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Proceed with save (not recommended).");
                    td.TitleAutoPrefix   = false;
                    td.AllowCancellation = false;
                    TaskDialogResult result = td.Show();

                    switch (result)
                    {
                    case TaskDialogResult.CommandLink1:      // Add revision now
                    {
                        // cancel first save
                        args.Cancel();

                        // add event to hide the default "Document not saved" dialog
                        uiApp.DialogBoxShowing += HideDocumentNotSaved;

                        // post command for editing revisions
                        PromptToEditRevisionsAndResave(uiApp);
                        break;
                    }

                    case TaskDialogResult.CommandLink2:      // Cancel save
                    {
                        // cancel saving only
                        args.Cancel();
                        break;
                    }

                    case TaskDialogResult.CommandLink3:      // Proceed with save
                    {
                        // do nothing
                        break;
                    }
                    }
                }
                else
                {
                    storedRevisionCount = revisionCount;
                }
            }
        }
示例#11
0
        public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
        {
            var details = new StringBuilder();

            var rhino = Addin.RhinoVersionInfo;

            details.AppendLine($"Rhino: {rhino.ProductVersion} ({rhino.FileDescription})");

            var revit = data.Application.Application;

#if REVIT_2019
            details.AppendLine($"Revit: {revit.SubVersionNumber} ({revit.VersionBuild})");
#else
            details.AppendLine($"Revit: {revit.VersionNumber} ({revit.VersionBuild})");
#endif

            details.AppendLine($"CLR: {ErrorReport.CLRVersion}");
            details.AppendLine($"OS: {Environment.OSVersion}");

            using
            (
                var taskDialog = new TaskDialog("About")
            {
                Id = MethodBase.GetCurrentMethod().DeclaringType.FullName,
                MainIcon = External.UI.TaskDialogIcons.IconInformation,
                TitleAutoPrefix = true,
                AllowCancellation = true,
                MainInstruction = $"Rhino.Inside© for Revit",
                MainContent = $"Rhino.Inside Revit: {Addin.DisplayVersion}",
                ExpandedContent = details.ToString(),
                CommonButtons = TaskDialogCommonButtons.Ok,
                DefaultButton = TaskDialogResult.Ok,
                FooterText = "Press CTRL+C to copy this information to Clipboard"
            }
            )
            {
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Web site");
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Read license");
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "See source code");

                switch (taskDialog.Show())
                {
                case TaskDialogResult.CommandLink1:
                    using (System.Diagnostics.Process.Start(@"https://www.rhino3d.com/inside/revit/beta/")) { }
                    break;

                case TaskDialogResult.CommandLink2:
                    using (System.Diagnostics.Process.Start(@"https://github.com/mcneel/rhino.inside-revit/blob/master/LICENSE")) { }
                    break;

                case TaskDialogResult.CommandLink3:
                    using (System.Diagnostics.Process.Start(@"https://github.com/mcneel/rhino.inside-revit/tree/master/src")) { }
                    break;
                }
            }

            return(Result.Succeeded);
        }
示例#12
0
        private void OnSavingPromptForRevisions(object sender, DocumentSavingEventArgs args)
        {
            Document      doc   = (Document)sender;
            UIApplication uiApp = new UIDocument(doc).Application;

            if (doc.IsModified)
            {
                // Compare number of revisions with saved count
                int revisionCount = GetRevisionCount(doc);
                if (revisionCount <= storedRevisionCount)
                {
                    // Show dialog with explanation and options
                    TaskDialog td = new TaskDialog("Revisions not created.");
                    td.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                    td.MainInstruction = "此文件已经修改,但还未添加新修订。";
                    td.ExpandedContent = "因为文档已经修改,所以通常需要发布一个新的修订版本号。";
                    td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "添加修订");
                    td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "取消保存");
                    td.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "继续保存(不推荐)");
                    td.TitleAutoPrefix   = false;
                    td.AllowCancellation = false;
                    TaskDialogResult result = td.Show();

                    switch (result)
                    {
                    case TaskDialogResult.CommandLink1:      // Add revision now
                    {
                        // cancel first save
                        args.Cancel();

                        // 注册DialogBoxShowing事件 用于隐藏"Document not saved" dialog
                        uiApp.DialogBoxShowing += HideDocumentNotSaved;

                        // post command for editing revisions
                        PromptToEditRevisionsAndResave(uiApp);
                        break;
                    }

                    case TaskDialogResult.CommandLink2:      // Cancel save
                    {
                        // cancel saving only
                        args.Cancel();
                        break;
                    }

                    case TaskDialogResult.CommandLink3:      // Proceed with save
                    {
                        // do nothing
                        break;
                    }
                    }
                }
                else
                {
                    storedRevisionCount = revisionCount;
                }
            }
        }
示例#13
0
        private void AttachRelatedPdbs(IList <string> pdb, bool addToRecent)
        {
            if (pdb == null)
            {
                return;
            }

            TaskDialogResult allResult = TaskDialogResult.None;

            foreach (string s in pdb)
            {
                if (!File.Exists(s))
                {
                    continue;
                }

                TaskDialogResult result = allResult;

                if (result == TaskDialogResult.None)
                {
                    using (TaskDialog dialog = TaskDialogHelper.ConstructTaskDialog(
                               Handle,
                               "Attach PDB File",
                               "Attach related PDB file?",
                               s,
                               TaskDialogStandardIcon.Information
                               ))
                    {
                        dialog.AddCommandLink(TaskDialogResult.Yes, "Attach");
                        dialog.AddCommandLink(TaskDialogResult.Yes, "Don't attach");
                        dialog.FooterCheckBoxText    = "Do this for other PDBs of this mapping.";
                        dialog.FooterCheckBoxChecked = false;

                        result = dialog.Show();
                        if (dialog.FooterCheckBoxChecked.Value)
                        {
                            allResult = result;
                        }
                    }
                }

                switch (result)
                {
                case TaskDialogResult.Yes:
                    if (AttachPDB(s, this) && addToRecent)
                    {
                        Configs.Instance.AddRecentPdb(mapping.Filename, s);
                    }
                    break;

                case TaskDialogResult.No:
                    break;

                default:
                    return;
                }
            }
        }
        private IEnumerable <string> GetFilesNames()
        {
            var fbd = new FolderBrowserDialog();

            // Выбрать семейства
            var taskDialog = new TaskDialog(Language.GetItem(_langItem, "h1"));

            // Выбрать файлы
            taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, Language.GetItem(_langItem, "h20"));

            // Выбрать папку
            taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, Language.GetItem(_langItem, "h21"));

            // Выбрать папку включая вложенные
            taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, Language.GetItem(_langItem, "h22"));
            var taskDialogResult = taskDialog.Show();

            switch (taskDialogResult)
            {
            case TaskDialogResult.CommandLink1:
                var ofd = new Microsoft.Win32.OpenFileDialog
                {
                    Multiselect = true,

                    // Семейства Revit
                    Filter = $"{Language.GetItem(_langItem, "h23")} (*.rfa) | *.rfa"
                };

                if (ofd.ShowDialog() == true)
                {
                    return(ofd.FileNames);
                }

                break;

            case TaskDialogResult.CommandLink2:
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    return(Directory.EnumerateFiles(fbd.SelectedPath, "*.rfa", SearchOption.TopDirectoryOnly));
                }

                break;

            case TaskDialogResult.CommandLink3:
                fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    return(Directory.EnumerateFiles(fbd.SelectedPath, "*.rfa", SearchOption.AllDirectories));
                }

                break;
            }

            return(new List <string>());
        }
示例#15
0
        static TaskDialog CreateCustomTaskDialog()
        {
            TaskDialog taskDialog = new TaskDialog("Choice");

            taskDialog.MainInstruction = "Please select how to split the element.";
            taskDialog.CommonButtons   = TaskDialogCommonButtons.Cancel;
            taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Select elements manually");
            taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Automatically detect all intruding elements");

            return(taskDialog);
        }
        /// <summary>
        /// Return Result Has Select Element Current Or Not
        /// </summary>
        /// <param name="Caption">Title Question</param>
        /// <returns></returns>
        public static bool QuestionMsg(string Caption)
        {
            var dialog = new TaskDialog(Caption);

            dialog.MainIcon        = TaskDialogIcon.TaskDialogIconNone;
            dialog.MainInstruction = Caption;

            dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Element Current");
            dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Element In RvtLinked");

            return(dialog.Show() == TaskDialogResult.CommandLink1);
        }
示例#17
0
        Result ShowLoadError(ExternalCommandData data)
        {
            using
            (
                var taskDialog = new TaskDialog("Oops! Something went wrong :(")
            {
                Id = $"{MethodBase.GetCurrentMethod().DeclaringType}.{MethodBase.GetCurrentMethod().Name}",
                MainIcon = UIX.TaskDialogIcons.IconError,
                TitleAutoPrefix = true,
                AllowCancellation = true,
                MainInstruction = "Rhino.Inside failed to load",
                MainContent = $"Please run some tests before reporting.{Environment.NewLine}Those tests would help us figure out what happened.",
                ExpandedContent = "This problem use to be due an incompatibility with other installed add-ins.\n\n" +
                                  "While running on these modes you may see other add-ins errors and it may take longer to load, don't worry about that no persistent change will be made on your computer.",
                VerificationText = "Exclude installed add-ins list from the report.",
                FooterText = "Current version: " + Addin.DisplayVersion
            }
            )
            {
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "1. Run Revit without other Addins…", "Good for testing if Rhino.Inside would load if no other add-in were installed.");
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "2. Run Rhino.Inside in verbose mode…", "Enables all logging mechanisms built in Rhino for support purposes.");
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "3. Send report…", "Reports this problem by email to [email protected]");
                taskDialog.DefaultButton = TaskDialogResult.CommandLink3;

                while (true)
                {
                    switch (taskDialog.Show())
                    {
                    case TaskDialogResult.CommandLink1: RunWithoutAddIns(data); break;

                    case TaskDialogResult.CommandLink2: RunVerboseMode(data); break;

                    case TaskDialogResult.CommandLink3:
                        ErrorReport.SendEmail
                        (
                            data.Application,
                            "Rhino.Inside Revit failed to load",
                            !taskDialog.WasVerificationChecked(),
                            new string[]
                        {
                            data.Application.Application.RecordingJournalFilename,
                            RhinoDebugMessages_txt,
                            RhinoAssemblyResolveLog_txt
                        }
                        );
                        return(Result.Succeeded);

                    default: return(Result.Cancelled);
                    }
                }
            }
        }
示例#18
0
        private IReadOnlyCollection <string> GetFilesNames()
        {
            var result = new List <string>();

            var fbd = new FolderBrowserDialog();

            var taskDialog = new TaskDialog("Выбор файлов");

            taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Выбрать файлы");
            taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Выбрать папку");
            taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Выбрать папку включая вложенные");
            var taskDialogResult = taskDialog.Show();

            switch (taskDialogResult)
            {
            case TaskDialogResult.CommandLink1:
                var ofd = new OpenFileDialog
                {
                    Multiselect = true,
                    Filter      = "Revit families (*.rfa) | *.rfa"
                };

                if (ofd.ShowDialog() == true)
                {
                    result.AddRange(ofd.FileNames);
                }

                break;

            case TaskDialogResult.CommandLink2:
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    result.AddRange(Directory.EnumerateFiles(fbd.SelectedPath, "*.rfa",
                                                             SearchOption.TopDirectoryOnly));
                }

                break;

            case TaskDialogResult.CommandLink3:
                fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    result.AddRange(Directory.EnumerateFiles(fbd.SelectedPath, "*.rfa",
                                                             SearchOption.AllDirectories));
                }

                break;
            }

            return(result);
        }
示例#19
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application app       = commandData.Application.Application;
            Document    activeDoc = commandData.Application.ActiveUIDocument.Document;

            // Creates a Revit task dialog to communicate information to the user.
            TaskDialog mainDialog = new TaskDialog("holo-blok");

            mainDialog.MainInstruction = "what's in the blok?";
            mainDialog.MainContent     =
                "We believe the act of building buildings should be more efficient."
                + "So we built So we built holo - blok to do just that";

            // Add commmandLink options to task dialog
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Contact");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Build Version");

            // Set common buttons and default button. If no CommonButton or CommandLink is added,
            // task dialog will show a Close button by default
            mainDialog.CommonButtons = TaskDialogCommonButtons.Close;
            mainDialog.DefaultButton = TaskDialogResult.Close;

            // Set footer text. Footer text is usually used to link to the help document.
            //mainDialog.FooterText = "" + "Click here for the Revit API Developer Center";

            TaskDialogResult tResult = mainDialog.Show();

            // If the user clicks the first command link, a simple Task Dialog
            // with only a Close button shows information about the Revit installation.
            if (TaskDialogResult.CommandLink1 == tResult)
            {
                TaskDialog dialog_CommandLink1 = new TaskDialog("Contact");
                dialog_CommandLink1.MainInstruction =
                    "http://holo-blok.com/";

                dialog_CommandLink1.Show();
            }

            // If the user clicks the second command link, a simple Task Dialog
            // created by static method shows information about the active document
            else if (TaskDialogResult.CommandLink2 == tResult)
            {
                TaskDialog.Show("Build Version",
                                "Version 1.00" + "\n"
                                + "Complied Dec. 16 2019" + "\n"
                                + "*****@*****.**");
            }

            return(Result.Succeeded);
        }
示例#20
0
        public void OnIdling(object sender, IdlingEventArgs e)
        {
            if (receiverActivated)
            {
                UIApplication uiapp = sender as UIApplication;
                Document      doc   = uiapp.ActiveUIDocument.Document;

                e.SetRaiseWithoutDelay();

                string value = RegistryKeyManager.GetRegistryKeyValue("RhinoOutgoing");
                if (!string.IsNullOrEmpty(value))
                {
                    if (value.ToLower() == "true")
                    {
                        TaskDialog dialog = new TaskDialog("Rhino Receiver");
                        dialog.MainInstruction = "Rhino Data";
                        dialog.MainContent     = "Analysis data from Rhino is being sent to Revit.";
                        dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Visualize Analysis Results");
                        dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel");

                        TaskDialogResult result = dialog.Show();
                        if (result == TaskDialogResult.CommandLink1)
                        {
                            //AVF
                            string   tempDirectory = RegistryKeyManager.GetRegistryKeyValue("DivaTempDirectory");
                            string[] gridFiles     = Directory.GetFiles(tempDirectory, "*-AnalysisGrid.obj");
                            if (gridFiles.Length > 0)
                            {
                                List <ObjMesh> objMeshes   = new List <ObjMesh>();
                                bool           objImported = ObjImporter.ReadObjFile(gridFiles[0], out objMeshes);

                                string dataPath         = RegistryKeyManager.GetRegistryKeyValue("RhinoOutgoingPath");
                                AnalysisDataManager avf = new AnalysisDataManager(uiapp, objMeshes, dataPath);
                                if (avf.ReadResults())
                                {
                                    if (avf.CreateGeometry())
                                    {
                                        if (avf.VisualizeData())
                                        {
                                            MessageBox.Show("Result data from Rhino was successfully visualized.");
                                        }
                                    }
                                }
                            }
                        }
                        RegistryKeyManager.SetRegistryKeyValue("RhinoOutgoing", "False");
                    }
                }
            }
        }
示例#21
0
    {   /// <summary>
        ///
        /// </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)
        {
            Application app       = commandData.Application.Application;
            Document    activeDoc = commandData.Application.ActiveUIDocument.Document;

            TaskDialog mainDialog = new TaskDialog("Hello Reivt");

            mainDialog.MainInstruction = "Hello Revit";
            mainDialog.MainContent     = "这个例子可以演示一个外部命令是怎样加载到Revit用户界面的"
                                         + "它使用Revit任务对话框与用户交流信息\n"
                                         + "点击下面链接获取更多帮助";
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "关于Revit版本信息");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "关于此文档的信息");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "关于开发此Command的作者");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink4, "关于软件日志");

            //设置常见按钮和默认按钮,如果不需要设置按钮,显示框不会展现按钮
            mainDialog.CommonButtons = TaskDialogCommonButtons.Close;
            mainDialog.DefaultButton = TaskDialogResult.Close;


            mainDialog.FooterText = "<a href=\"http://www.google.com \">"
                                    + "Click here for the Revit API Developer Center</a>";

            TaskDialogResult tResult = mainDialog.Show();

            if (TaskDialogResult.CommandLink1 == tResult)
            {
                TaskDialog dialog_CommandLink1 = new TaskDialog("Revit Build Information");
                dialog_CommandLink1.MainInstruction = "Revit Version Name is:" + "\t" + app.VersionName + "\n"
                                                      + "Revit Version Number is:" + "\t" + app.VersionNumber + "\n"
                                                      + "Revit Version Build is:" + "\t" + app.VersionBuild
                                                      + "Revit Username is" + "\t" + app.Username;
                dialog_CommandLink1.Show();
            }
            else if (TaskDialogResult.CommandLink2 == tResult)
            {
                TaskDialog.Show("Active Document Information", "Active document:" + activeDoc.Title + "\n"
                                + "Active view name:" + activeDoc.ActiveView.Name);
            }
            else if (TaskDialogResult.CommandLink3 == tResult)
            {
                TaskDialog.Show("Hello Baby", "This is just a test command XDDD");
            }
            else
            {
                TaskDialog.Show("日志", app.RecordingJournalFilename);
            }
            return(Result.Succeeded);
        }
示例#22
0
        /// <summary>
        /// MessageBox wrapper for question message.
        /// </summary>
        public static bool QuestionMsg(string msg)
        {
            Debug.WriteLine(msg);

            var dialog = new TaskDialog(Caption);

            dialog.MainIcon        = TaskDialogIcon.TaskDialogIconNone;
            dialog.MainInstruction = msg;

            dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Instance parameters");
            dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Type parameters");

            return(dialog.Show() == TaskDialogResult.CommandLink1);
        }
示例#23
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) create an instance of task dialog to set more options.

            TaskDialog houseDialog = new TaskDialog("Revit UI Labs - Create House Dialog");

            houseDialog.MainInstruction = "Create a house";
            houseDialog.MainContent     = "There are two options to create a house.";
            houseDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Interactive", "You will pick two corners of rectangular footprint of a house, and choose where you want to add a front door.");
            houseDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Automatic", "This is will automatically place a house with a default settings.");
            houseDialog.CommonButtons = TaskDialogCommonButtons.Cancel;
            houseDialog.DefaultButton = TaskDialogResult.CommandLink1;

            // Show the dialog to the user.

            TaskDialogResult res = houseDialog.Show();

            //TaskDialog.Show( "Create house dialog", "The last action was: " + res.ToString());

            // (2) pause the result and create a house with the method that use has chosen.
            //
            // Create a house interactively.
            if (res == TaskDialogResult.CommandLink1)
            {
                UICreateHouse.CreateHouseInteractive(_uiDoc);
                return(Result.Succeeded);
            }

            // Create a house automatically with the default settings.
            if (res == TaskDialogResult.CommandLink2)
            {
                IntroCs.ModelCreationExport.CreateHouse(_uiDoc.Document);
                return(Result.Succeeded);
            }

            // Request canceled.
            if (res == TaskDialogResult.Cancel)
            {
                return(Result.Cancelled);
            }
            return(Result.Succeeded);
        }
示例#24
0
        private bool UserDecidedToUpdateGeometry(out bool deleteExisting)
        {
            TaskDialog decide = new TaskDialog("Pipe Data Received");

            decide.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Replace Objects",
                                  "Objects in the scene will be deleted and replaced with the new objects");
            decide.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Update Geometry",
                                  "The objects will not be deleted, but their geometry will be updated.");
            decide.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Append New Geometry",
                                  "New geometry will be added to the document without changing the existing geometry.");
            TaskDialogResult result = decide.Show();

            deleteExisting = result == TaskDialogResult.CommandLink1;
            return(result == TaskDialogResult.CommandLink2);
        }
示例#25
0
        public void UpdateAll()
        {
            Families = GetFamilies();

            if (Families.Count() > 0)
            {
                var currentFamily = Families.FirstOrDefault();

                CurrentFamilyId = currentFamily.Id;

                Symbols = GetSymbols(currentFamily);

                if (Symbols.Count() > 0)
                {
                    CurrentSymbolId = Symbols.FirstOrDefault().Id;
                }

                windowBasedExternalEventHandler.MinWindowWidth  = _minWindowWidth;
                windowBasedExternalEventHandler.MinWindowHeight = _minWindowHeight;
            }
            else
            {
                var td = new TaskDialog("Warning");

                td.MainInstruction = "Families is required";
                td.MainContent     = "There are no families in the project. Do you want to load it?";
                td.MainIcon        = TaskDialogIcon.TaskDialogIconInformation;

                td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Yes, load families into the project");
                td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "No, don't load it");

                TaskDialogResult tdres = td.Show();

                switch (tdres)
                {
                case TaskDialogResult.CommandLink1:
                    FamilyLoader.LoadFamilies(doc);
                    UpdateAll();
                    break;

                case TaskDialogResult.CommandLink2:
                    break;

                default:
                    break;
                }
            }
        }
示例#26
0
        internal static Result CheckSetup()
        {
            if (RhinoVersion >= MinimumRhinoVersion)
            {
                return(IsExpired() ? Result.Cancelled : Result.Succeeded);
            }

            using
            (
                var taskDialog = new TaskDialog(MethodBase.GetCurrentMethod().DeclaringType.FullName)
            {
                Title = "Update Rhino",
                MainIcon = TaskDialogIcons.IconInformation,
                TitleAutoPrefix = true,
                AllowCancellation = true,
                MainInstruction = "Unsupported Rhino WIP version",
                MainContent = $"Expected Rhino version is ({MinimumRhinoVersion}) or above",
                FooterText = $"Current Rhino WIP version: {RhinoVersion}"
            }
            )
            {
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Download latest Rhino WIP...");
                if (taskDialog.Show() == TaskDialogResult.CommandLink1)
                {
                    using (Process.Start(@"https://www.rhino3d.com/download/rhino/wip")) { }
                }
            }

            return(Result.Failed);
        }
示例#27
0
        public static bool IsExpired(bool quiet = true)
        {
            if (DaysUntilExpiration > 0 && quiet)
            {
                return(false);
            }

            using
            (
                var taskDialog = new TaskDialog(MethodBase.GetCurrentMethod().DeclaringType.FullName)
            {
                Title = "Days left",
                MainIcon = TaskDialogIcons.IconInformation,
                TitleAutoPrefix = true,
                AllowCancellation = true,
                MainInstruction = DaysUntilExpiration < 1 ?
                                  "This WIP build has expired" :
                                  $"This WIP build expires in {DaysUntilExpiration} days",
                FooterText = "Current version: " + DisplayVersion
            }
            )
            {
                taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Check for updates...");
                if (taskDialog.Show() == TaskDialogResult.CommandLink1)
                {
                    using (Process.Start(@"https://www.rhino3d.com/download/rhino.inside-revit/7/wip")) { }
                }
            }

            return(DaysUntilExpiration < 1);
        }
示例#28
0
 static public void Show(bool showEmpty = false)
 {
     foreach (var error in Stack)
     {
         if (!showEmpty && error.FailedElementIds.Count() == 0)
         {
             continue;
         }
         string     allErrorIds = String.Join(", ", error.FailedElementIds);
         TaskDialog dialog      = new TaskDialog("Результат");
         if (error.AllElementIds != null)
         {
             dialog.MainInstruction = String.Format("Операция: {0}\nТип ошибки: {1}\nНеудачно: {2} из {3}",
                                                    error.Operation, error.ErrorType, error.FailedElementIds.Count(), error.AllElementIds.Count());
         }
         else
         {
             dialog.MainInstruction = String.Format("Операция: {0}\nТип ошибки: {1}\nНеудачно: {2}",
                                                    error.Operation, error.ErrorType, error.FailedElementIds.Count());
         }
         dialog.MainContent = "Перечень id элементов:\n"
                              + allErrorIds;
         dialog.FooterText = error.Tip;
         dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Скопировать ID элементов в буфер обмена");
         TaskDialogResult result = dialog.Show();
         if (result == TaskDialogResult.CommandLink1)
         {
             System.Windows.Forms.Clipboard.SetText(allErrorIds);
             TaskDialog.Show("Результат", "Данные успешно скопированы в буфер обмена");
         }
     }
     LoggingMachine.Reset();
 }
示例#29
0
        static void ShowShortcutHelp(object sender, EventArgs e)
        {
            if (sender is IExternalCommand)
            {
                External.ActivationGate.Exit -= ShowShortcutHelp;

                using
                (
                    var taskDialog = new TaskDialog("New Shortcut")
                {
                    Id = $"{MethodBase.GetCurrentMethod().DeclaringType}.{MethodBase.GetCurrentMethod().Name}",
                    MainIcon = UIX.TaskDialogIcons.IconInformation,
                    TitleAutoPrefix = true,
                    AllowCancellation = true,
                    MainInstruction = $"Keyboard shortcut 'R' is now assigned to Rhino",
                    MainContent = $"You can use R key to restore previously visible Rhino windows over Revit window every time you need them.",
                    FooterText = "This is a one time message",
                }
                )
                {
                    taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Customize keyboard shortcuts…");
                    if (taskDialog.Show() == TaskDialogResult.CommandLink1)
                    {
                        Revit.ActiveUIApplication.PostCommand(RevitCommandId.LookupPostableCommandId(PostableCommand.KeyboardShortcuts));
                    }
                }
            }
        }
示例#30
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;

            }
        }
示例#31
0
        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;

            IList <Element> curtainWallPanels = new FilteredElementCollector(doc, doc.ActiveView.Id).OfCategory(BuiltInCategory.OST_CurtainWallPanels).WhereElementIsNotElementType().ToElements();

            var w = new List <PanelData>();

            foreach (Element panel in curtainWallPanels)
            {
                w.Add(new PanelData
                {
                    ElementId = panel.Id.ToString(),
                    Type      = "Type ???",
                    Width     = panel.LookupParameter("Width").AsValueString(),
                    Height    = panel.LookupParameter("Height").AsValueString(),
                    Angle     = panel.LookupParameter("Anglecalc").AsValueString(),
                    Area      = panel.LookupParameter("Area").AsValueString(),
                    Material  = ""
                });
            }

            string m_finalPath = @"C:\Temp\modelData.json";

            using (StreamWriter sw = new StreamWriter(m_finalPath, false))
            {
                sw.WriteLine("{\"Items\":");
                sw.WriteLine(JsonConvert.SerializeObject(w));
                sw.WriteLine("}");
            }

            TaskDialog myDialog = new TaskDialog("Summary");

            myDialog.MainIcon    = TaskDialogIcon.TaskDialogIconNone;
            myDialog.MainContent = "Operation completed";

            myDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink4, $"Json file saved here {m_finalPath}");

            TaskDialogResult res = myDialog.Show();

            if (TaskDialogResult.CommandLink4 == res)
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
                {
                    FileName        = @"C:\Temp\",
                    UseShellExecute = true,
                    Verb            = "open"
                });
            }

            return(Result.Succeeded);
        }//close Execute
        public OverrideViewDepth(UIApplication uiapp)
        {
            m_app       = uiapp;
            m_doc       = m_app.ActiveUIDocument.Document;
            currentView = m_doc.ActiveView;
            try
            {
                bool viewOverriden = ViewDepthDataStorageUtil.GetOverridenViews(m_doc, currentView.Id);

                if (viewOverriden)
                {
                    TaskDialog mainDialog = new TaskDialog("View Depth - Override Graphics");
                    mainDialog.MainInstruction = "The current view has already applied graphics overriden by the View Depth tool.\n";
                    mainDialog.MainContent     = "Select an option below.";

                    mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Override Graphics");
                    mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Clear All Overrides");

                    TaskDialogResult tResult = mainDialog.Show();
                    if (TaskDialogResult.CommandLink1 == tResult)
                    {
                        bool overriden      = OverrideGraphics(currentView);
                        bool updatedStorage = ViewDepthDataStorageUtil.UpdateDataStorage(m_doc, currentView.Id, overriden);
                    }
                    else if (TaskDialogResult.CommandLink2 == tResult)
                    {
                        bool cleared = ClearAllOverrides(currentView);
                        if (cleared)
                        {
                            bool updatedStorage = ViewDepthDataStorageUtil.UpdateDataStorage(m_doc, currentView.Id, false);
                        }
                    }
                }
                else
                {
                    bool overriden      = OverrideGraphics(currentView);
                    bool updatedStorage = ViewDepthDataStorageUtil.UpdateDataStorage(m_doc, currentView.Id, overriden);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to override the depth of view.\n" + ex.Message, "ViewDepthOverride", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
示例#33
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;
 }
示例#34
0
        /// <summary>
        /// MessageBox wrapper for question message.
        /// </summary>
        public static bool QuestionMsg( string msg )
        {
            Debug.WriteLine( msg );

              //bool rc = WinForms.DialogResult.Yes
              //  == WinForms.MessageBox.Show( msg, Caption, WinForms.MessageBoxButtons.YesNo, WinForms.MessageBoxIcon.Question );
              //Debug.WriteLine( rc ? "Yes" : "No" );
              //return rc;

              TaskDialog d = new TaskDialog( Caption );
              d.MainIcon = TaskDialogIcon.TaskDialogIconNone;
              d.MainInstruction = msg;
              //d.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;
              d.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Instance parameters");
              d.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Type parameters");
              //d.DefaultButton = TaskDialogResult.Yes;
              //return TaskDialogResult.Yes == d.Show();
              return d.Show() == TaskDialogResult.CommandLink1;
        }
    /// <summary>
    /// Task Dialog - create an instance of task dialog gives you more options. 
    /// cf. Developer guide, Figure 223 (on pp 405) has a image of all the components visible. 
    /// This function is to visulize what kind of contents you can add with TaskDialog. 
    /// Note: actual interpretation of 
    /// </summary>
    public void ShowTaskDialogInstance( bool stepByStep )
    {
      // (0) create an instance of task dialog to set more options. 
      TaskDialog myDialog = new TaskDialog( "Revit UI Labs - Task Dialog Options" );
      if( stepByStep ) myDialog.Show();

      // (1) set the main area. these appear at the upper portion of the dialog. 
       
      myDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
      // or TaskDialogIcon.TaskDialogIconNone. 
      if( stepByStep ) myDialog.Show();

      myDialog.MainInstruction = "Main instruction: This is Revit UI Lab 3 Task Dialog";
      if( stepByStep ) myDialog.Show();

      myDialog.MainContent = "Main content: You can add detailed description here.";
      if( stepByStep ) myDialog.Show();

      // (2) set the bottom area 
       
      myDialog.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel;
      myDialog.DefaultButton = TaskDialogResult.Yes;
      if( stepByStep ) myDialog.Show();

      myDialog.ExpandedContent = "Expanded content: the visibility of this portion is controled by Show/Hide button.";
      if( stepByStep ) myDialog.Show();

      myDialog.VerificationText = "Verification: Do not show this message again comes here";
      if( stepByStep ) myDialog.Show();

      myDialog.FooterText = "Footer: <a href=\"http://www.autodesk.com/developrevit\">Revit Developer Center</a>";
      if( stepByStep ) myDialog.Show();

      // (4) add command links. you can add up to four links 
       
      myDialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink1, "Command Link 1", "description 1" );
      if( stepByStep ) myDialog.Show();
      myDialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink2, "Command Link 2", "description 2" );
      if( stepByStep ) myDialog.Show();
      myDialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink3, "Command Link 3", "you can add up to four command links" );
      if( stepByStep ) myDialog.Show();
      myDialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink4, "Command Link 4", "Can also have URLs e.g. Revit Product Online Help" );
      //if (stepByStep) myDialog.Show(); 

      // Show it. 
      TaskDialogResult res = myDialog.Show();
      if( TaskDialogResult.CommandLink4 == res )
      {
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        // process.StartInfo.FileName = "http://docs.autodesk.com/REVIT/2011/ENU/landing.html";
        //process.StartInfo.FileName = "http://wikihelp.autodesk.com/Revit/enu/2012";
        process.StartInfo.FileName = "http://wikihelp.autodesk.com/Revit/enu/2013";
        process.Start();
      }

      TaskDialog.Show("Show task dialog", "The last action was: " + res.ToString());
    }
    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) create an instance of task dialog to set more options. 
       
      TaskDialog houseDialog = new TaskDialog( "Revit UI Labs - Create House Dialog" );
      houseDialog.MainInstruction = "Create a house";
      houseDialog.MainContent = "There are two options to create a house.";
      houseDialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink1, "Interactive", "You will pick two corners of rectangular footprint of a house, and choose where you want to add a front door." );
      houseDialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink2, "Automatic", "This is will automatically place a house with a default settings." );
      houseDialog.CommonButtons = TaskDialogCommonButtons.Cancel;
      houseDialog.DefaultButton = TaskDialogResult.CommandLink1;

      // Show the dialog to the user. 
       
      TaskDialogResult res = houseDialog.Show();

      //TaskDialog.Show( "Create house dialog", "The last action was: " + res.ToString()); 

      // (2) pause the result and create a house with the method that use has chosen. 
      // 
      // Create a house interactively. 
      if( res == TaskDialogResult.CommandLink1 )
      {
        UICreateHouse.CreateHouseInteractive( _uiDoc );
        return Result.Succeeded;
      }

      // Create a house automatically with the default settings. 
      if( res == TaskDialogResult.CommandLink2 )
      {
        IntroCs.ModelCreationExport.CreateHouse( _uiDoc.Document );
        return Result.Succeeded;
      }

      // Request canceled. 
      if( res == TaskDialogResult.Cancel )
      {
        return Result.Cancelled;
      }
      return Result.Succeeded;
    }
示例#37
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;
        }
示例#38
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;
        }
示例#39
0
文件: CancelSave.cs 项目: AMEE/revit
        /// <summary>
        /// Deal with the case that the project status wasn't updated.
        /// If the event is Cancellable, cancel it and inform user else just inform user the status.
        /// </summary>
        /// <param name="args">Event arguments that contains the event data.</param>
        private static void DealNotUpdate(RevitAPIPreDocEventArgs args)
        {
            string mainMessage;
            string additionalText;
            TaskDialog taskDialog = new TaskDialog("CancelSave Sample");

            if (args.Cancellable)
            {
                args.Cancel(); // cancel this event if it is cancellable.

                mainMessage = "CancelSave sample detected that the Project Status parameter on Project Info has not been updated. The file will not be saved."; // prompt to user.
            }
            else
            {
                // will not cancel this event since it isn't cancellable.
               mainMessage = "The file is about to save. But CancelSave sample detected that the Project Status parameter on Project Info has not been updated."; // prompt to user.
            }

            // taskDialog will not show when do regression test.
            if (!LogManager.RegressionTestNow)
            {
               additionalText = "You can disable this permanently by uninstaling the CancelSave sample from Revit. Remove or rename CancelSave.addin from the addins directory.";

               // use one taskDialog to inform user current situation.
               taskDialog.MainInstruction = mainMessage;
               taskDialog.MainContent     = additionalText;
               taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Open the addins directory");
               taskDialog.CommonButtons = TaskDialogCommonButtons.Close;
               taskDialog.DefaultButton = TaskDialogResult.Close;
               TaskDialogResult tResult = taskDialog.Show();
               if (TaskDialogResult.CommandLink1 == tResult)
               {
                  System.Diagnostics.Process.Start("explorer.exe", DetectAddinFileLocation(args.Document.Application));
               }
            }

            // write log file.
            LogManager.WriteLog("   Project Status is not updated, taskDialog informs user: " + mainMessage);
        }
示例#40
0
文件: Command.cs 项目: AMEE/revit
        /// <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 commandData,
            ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // NOTES: Anything can be done in this method, such as create a message box,
            // a task dialog or fetch some information from revit and so on.
            // We mainly use the task dialog for example.

            // Get the application and document from external command data.
            Application app = commandData.Application.Application;
            Document activeDoc = commandData.Application.ActiveUIDocument.Document;

            #region Task Dialog Sample
            // Study how to create a revit style dialog using task dialog API by following
            // code snippet.

            // Creates a Revit task dialog to communicate information to the interactive user.
            TaskDialog mainDialog = new TaskDialog("Hello, Revit!");
            mainDialog.MainInstruction = "Hello, Revit!";
            mainDialog.MainContent =
                "This sample shows how a basic ExternalCommand can be added to the Revit user interface."
                + " It uses a Revit task dialog to communicate information to the interactive user.\n"
                + "The command links below open additional task dialogs with more information.";

            // Add commmandLink to task dialog
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1,
                                      "View information about the Revit installation");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2,
                                      "View information about the active document");

            // Set common buttons and default button. If no CommonButton or CommandLink is added,
            // task dialog will show a Close button by default.
            mainDialog.CommonButtons = TaskDialogCommonButtons.Close;
            mainDialog.DefaultButton = TaskDialogResult.Close;

            // Set footer text. Footer text is usually used to link to the help document.
            mainDialog.FooterText =
                "<a href=\"http://usa.autodesk.com/adsk/servlet/index?siteID=123112&id=2484975 \">"
                + "Click here for the Revit API Developer Center</a>";

            TaskDialogResult tResult = mainDialog.Show();

            // If the user clicks the first command link, a simple Task Dialog
            // with only a Close button shows information about the Revit installation.
            if (TaskDialogResult.CommandLink1 == tResult)
            {
                TaskDialog dialog_CommandLink1 = new TaskDialog("Revit Build Information");
                dialog_CommandLink1.MainInstruction =
                    "Revit Version Name is: " + app.VersionName + "\n"
                    + "Revit Version Number is: " + app.VersionNumber + "\n"
                    + "Revit Version Build is: " + app.VersionBuild;

                dialog_CommandLink1.Show();

            }

            // If the user clicks the second command link, a simple Task Dialog
            // created by static method shows information about the active document.
            else if (TaskDialogResult.CommandLink2 == tResult)
            {
                TaskDialog.Show("Active Document Information",
                    "Active document: " + activeDoc.Title + "\n"
                    + "Active view name: " + activeDoc.ActiveView.Name);
            }
            #endregion

            return Autodesk.Revit.UI.Result.Succeeded;
        }