public bool IsCommandAvailable(UIApplication a, CategorySet b)
 {
     if (a.ActiveUIDocument == null) return false;
     if (a.ActiveUIDocument.Document == null) return false;
     if (a.ActiveUIDocument.Document.IsFamilyDocument) return false;
     return true;
 }
Exemplo n.º 2
0
        public bool IsCommandAvailable(
          UIApplication applicationData,
          CategorySet selectedCategories
        )
        {
            UIDocument uiDoc = applicationData.ActiveUIDocument;

            if (uiDoc == null || uiDoc.Document.IsFamilyDocument)
                return false;

            switch (uiDoc.Document.ActiveView.ViewType)
            {
                case ViewType.AreaPlan:
                case ViewType.CeilingPlan:
                case ViewType.EngineeringPlan:
                case ViewType.FloorPlan:
                    return true;
            }

            return false;
        }
        /// <summary>
        /// This method provides the control over whether an
        /// external command is enabled or disabled.
        /// </summary>
        /// <param name="applicationData">An
        /// ApplicationServices.Application object which
        /// contains reference to Application needed by
        /// external command.</param>
        /// <param name="selectedCategories">An list of
        /// categories of the elements which have been selected
        /// in Revit in the active document, or an empty set if
        /// no elements are selected or there is no active
        /// document.</param>
        /// <returns>Indicates whether Revit should enable or
        /// disable the corresponding external command.
        /// </returns>
        bool IExternalCommandAvailability.IsCommandAvailable(
            UIApplication applicationData,
            CategorySet selectedCategories)
        {
            ResourceManager res_mng = new ResourceManager(
                GetType());
            ResourceManager def_res_mng = new ResourceManager(
                typeof(Properties.Resources));

            bool result = false;

            try
            {
                // ============================================
                // TODO: delete these code rows and put your code
                // here.
                if (applicationData.ActiveUIDocument != null &&
                    !selectedCategories.IsEmpty)
                {
                    result = true;
                }
                // ============================================
            }
            catch (Exception ex)
            {
                TaskDialog.Show(def_res_mng.GetString("_Error")
                                , ex.Message);

                result = false;
            }
            finally
            {
                res_mng.ReleaseAllResources();
                def_res_mng.ReleaseAllResources();
            }

            return(result);
        }
Exemplo n.º 4
0
        public Result CreateElementBindings(ExternalCommandData commandData)
        {
            Document    doc = commandData.Application.ActiveUIDocument.Document;
            Application app = doc.Application;

            Autodesk.Revit.Creation.Application ca = doc.Application.Create;

            Category pipeCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_PipeCurves);
            //Category fittingCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_PipeFitting);
            //Category accessoryCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_PipeAccessory);

            CategorySet pipeSet = ca.NewCategorySet();

            pipeSet.Insert(pipeCat);

            //CategorySet elemSet = ca.NewCategorySet();
            //elemSet.Insert(fittingCat);
            //elemSet.Insert(accessoryCat);

            string ExecutingAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string oriFile  = app.SharedParametersFilename;
            string tempFile = ExecutingAssemblyPath + "Temp.txt";

            StringBuilder sbFeedback = new StringBuilder();

            string domain = "PIPE";

            CreateBinding(domain, tempFile, app, doc, pipeSet, sbFeedback);

            //domain = "ELEM";
            //CreateBinding(domain, tempFile, app, doc, elemSet, sbFeedback);

            //ut.InfoMsg(sbFeedback.ToString());

            app.SharedParametersFilename = oriFile;

            return(Result.Succeeded);
        }
Exemplo n.º 5
0
        bool CreateKeyParameter(Category category, Document document, string parameterName, ParameterType parameterType, BuiltInParameterGroup parameterGroup, Guid guid)
        {
            Application application = document.Application;
            string      temShareDefinitionFilePath      = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"/temSharpParam.txt";
            string      originalShareDefinitionFilePath = application.SharedParametersFilename;

            if (File.Exists(temShareDefinitionFilePath))
            {
                File.Delete(temShareDefinitionFilePath);
            }
            FileStream fileStream = File.Create(temShareDefinitionFilePath);

            fileStream.Close();

            application.SharedParametersFilename = temShareDefinitionFilePath;
            DefinitionFile  definitionFile = application.OpenSharedParameterFile();
            DefinitionGroup shareParaGroup = definitionFile.Groups.Create("mySharePara");
            ExternalDefinitionCreationOptions definitionOpt = new ExternalDefinitionCreationOptions(parameterName, parameterType);

            if (guid != null)
            {
                definitionOpt.GUID = guid;
            }
            Definition definition = shareParaGroup.Definitions.Create(definitionOpt);

            CategorySet categorySet = new CategorySet();

            categorySet.Insert(category);
            bool result = document.ParameterBindings.Insert(definition, new TypeBinding(categorySet), parameterGroup);

            if (!String.IsNullOrEmpty(originalShareDefinitionFilePath))
            {
                application.SharedParametersFilename = originalShareDefinitionFilePath;
            }
            File.Delete(temShareDefinitionFilePath);

            return(result);
        }
Exemplo n.º 6
0
        public bool IsCommandAvailable(
            UIApplication applicationData,
            CategorySet selectedCategories
            )
        {
            UIDocument uiDoc = applicationData.ActiveUIDocument;

            if (uiDoc == null || uiDoc.Document.IsFamilyDocument)
            {
                return(false);
            }

            switch (uiDoc.Document.ActiveView.ViewType)
            {
            case ViewType.AreaPlan:
            case ViewType.CeilingPlan:
            case ViewType.EngineeringPlan:
            case ViewType.FloorPlan:
                return(true);
            }

            return(false);
        }
Exemplo n.º 7
0
        public bool BindParameter(Document document)
        {
            DefinitionFile definitionFile = document.Application.OpenSharedParameterFile();

            DefinitionGroup definitionGroup = definitionFile.Groups.get_Item("BROWNIE");

            if (definitionGroup == null)
            {
                return(false);
            }
            Definition definition = this.GetDefinition(definitionGroup);

            CategorySet categorySet = document.Application.Create.NewCategorySet();
            Category    category    = document.Settings.Categories.get_Item(BuiltInCategory.OST_Rooms);

            categorySet.Insert(category);

            Binding binding;

            if (this.InstanceBinding)
            {
                binding = document.Application.Create.NewInstanceBinding(categorySet);
                document.ParameterBindings.Insert(definition, binding, BuiltInParameterGroup.PG_DATA);
            }
            else
            {
                binding = document.Application.Create.NewTypeBinding(categorySet);
            }
            bool flag = document.ParameterBindings.Insert(definition, binding);

            if (!flag)
            {
                flag = document.ParameterBindings.ReInsert(definition, binding);
            }
            return(flag);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Method to check if Instance Binding is of a specific category
        /// </summary>
        /// <param name="insBinding"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public static bool IsInstBindingOfCategory(InstanceBinding insBinding, string categoryName)
        {
            CategorySet         catSet   = insBinding.Categories;
            CategorySetIterator catSetIt = catSet.ForwardIterator();

            catSetIt.Reset();

            string cat = "";

            while (catSetIt.MoveNext())
            {
                Category category1 = catSetIt.Current as Category;
                cat = category1.Name;
            }

            if (cat != "" && cat == categoryName)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 9
0
        static public bool AddSharedParameter(
            Document doc,
            string parameterName,
            BuiltInCategory[] categories,
            BuiltInParameterGroup group = BuiltInParameterGroup.PG_ADSK_MODEL_PROPERTIES,
            bool isIntance = true
            )
        {
            // Проверка параметра на наличие
            List <bool> check = new List <bool>();

            foreach (BuiltInCategory cat in categories)
            {
                check.Add(IsParameterInProject(doc, parameterName, cat));
            }

            if (check.All(x => x == true))
            {
                return(true);
            }
            else
            {
                CategorySet catSet = doc.Application.Create.NewCategorySet();
                foreach (BuiltInCategory c in categories)
                {
                    catSet.Insert(doc.Settings.Categories.get_Item(c));
                }

                try
                {
                    doc.Application.SharedParametersFilename = sharedParameterFilePath;
                    DefinitionFile     spFile    = doc.Application.OpenSharedParameterFile();
                    ExternalDefinition sharedDef = null;
                    foreach (DefinitionGroup gr in spFile.Groups)
                    {
                        foreach (Definition def in gr.Definitions)
                        {
                            if (def.Name == parameterName)
                            {
                                sharedDef = (ExternalDefinition)def;
                            }
                        }
                    }
                    if (sharedDef == null)
                    {
                        TaskDialog.Show("Ошибка", String.Format("Параметр \"{0}\" отсутствует в файле общих параметров", parameterName));
                        return(false);
                    }

                    ElementBinding bind;
                    if (isIntance)
                    {
                        bind = doc.Application.Create.NewInstanceBinding(catSet);
                    }
                    else
                    {
                        bind = doc.Application.Create.NewTypeBinding(catSet);
                    }
                    bool result = doc.ParameterBindings.Insert(sharedDef, bind, group);
                    // Если параметр уже существует, но данная категория отсутствует в сете - обновляем сет
                    if (!result)
                    {
                        string realName = GetRealParameterName(doc, sharedDef);
                        bind = GetParameterBinding(doc, realName);
                        foreach (Category c in catSet)
                        {
                            bind.Categories.Insert(c);
                        }
                        bool result2 = doc.ParameterBindings.ReInsert(sharedDef, bind, group);
                        if (!result2)
                        {
                            TaskDialog.Show("Ошибка", String.Format("Произошла ошибка при редактировании привязок существующего параметра \"{0}\"", parameterName));
                            return(false);
                        }
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    TaskDialog td = new TaskDialog("Ошибка");
                    td.MainInstruction = String.Format("Произошла ошибка добавления общего параметра \"{0}\"", parameterName);
                    td.MainContent     = e.ToString();
                    td.Show();
                    return(false);
                }
            }
        }
        /// <summary>
        /// create project parameter
        /// source :http://spiderinnet.typepad.com/blog/2011/05/parameter-of-revit-api-31-create-project-parameter.html
        /// </summary>
        /// <param name="app">revit application</param>
        /// <param name="name">revit ui application</param>
        /// <param name="type">parameter type</param>
        /// <param name="cats">category set</param>
        /// <param name="group">parameter group</param>
        /// <param name="inst">is instance variable</param>
        public  void CreateProjectParameter(Application app, string name, ParameterType type,  CategorySet cats, BuiltInParameterGroup group, bool instance)
        {
    

            string oriFile = app.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";
            using (File.Create(tempFile)) { }
            app.SharedParametersFilename = tempFile;
    
             ExternalDefinitionCreationOptions edc=new ExternalDefinitionCreationOptions(name, type);
             ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create("TemporaryDefintionGroup").Definitions.Create(edc) as ExternalDefinition;

            app.SharedParametersFilename = oriFile;
            File.Delete(tempFile);

            Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats);
            if (instance) binding = app.Create.NewInstanceBinding(cats);
            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;
            map.Insert(def, binding, group);
        }
Exemplo n.º 11
0
 /// <inheritdoc />
 public bool IsCommandAvailable([NotNull] UIApplication applicationData, [NotNull][ItemNotNull] CategorySet selectedCategories) => true;
Exemplo n.º 12
0
 public bool IsCommandAvailable(UIApplication applicationData, CategorySet selectedCategories)
 {
     return(true);
 }
Exemplo n.º 13
0
 /// <summary>
 /// Command Availability
 /// </summary>
 /// <param name="applicationData"></param>
 /// <param name="selectedCategories"></param>
 /// <returns></returns>
 public bool IsCommandAvailable(UIApplication applicationData, CategorySet selectedCategories)
 {
     return(applicationData.ActiveUIDocument != null);
 }
        /// <summary>
        /// This method takes a category and information
        /// about a project parameter and adds a binding
        /// to the category for the parameter.  It will
        /// throw an exception if the parameter is already
        /// bound to the desired category.  It returns
        /// whether or not the API reports that it
        /// successfully bound the parameter to the
        /// desired category.
        /// </summary>
        /// <param name="doc">The project document in which the project parameter has been defined</param>
        /// <param name="projectParameterData">Information about the project parameter</param>
        /// <param name="category">The additional category to which to bind the project parameter</param>
        /// <returns></returns>
        static bool AddProjectParameterBinding(
            Document doc,
            ProjectParameterData projectParameterData,
            Category category)
        {
            // Following good SOA practices, first validate incoming parameters

            if (doc == null)
            {
                throw new ArgumentNullException("doc");
            }

            if (doc.IsFamilyDocument)
            {
                throw new Exception(
                          "doc can not be a family document.");
            }

            if (projectParameterData == null)
            {
                throw new ArgumentNullException(
                          "projectParameterData");
            }

            if (category == null)
            {
                throw new ArgumentNullException("category");
            }

            bool result = false;

            CategorySet cats = projectParameterData.Binding
                               .Categories;

            if (cats.Contains(category))
            {
                // It's already bound to the desired category.
                // Nothing to do.
                string errorMessage = string.Format(
                    "The project parameter '{0}' is already bound to the '{1}' category.",
                    projectParameterData.Definition.Name,
                    category.Name);

                throw new Exception(errorMessage);
            }

            cats.Insert(category);

            // See if the parameter is an instance or type parameter.

            InstanceBinding instanceBinding
                = projectParameterData.Binding as InstanceBinding;

            if (instanceBinding != null)
            {
                // Is an Instance parameter

                InstanceBinding newInstanceBinding
                    = doc.Application.Create
                      .NewInstanceBinding(cats);

                if (doc.ParameterBindings.ReInsert(
                        projectParameterData.Definition,
                        newInstanceBinding))
                {
                    result = true;
                }
            }
            else
            {
                // Is a type parameter
                TypeBinding typeBinding
                    = doc.Application.Create
                      .NewTypeBinding(cats);

                if (doc.ParameterBindings.ReInsert(
                        projectParameterData.Definition, typeBinding))
                {
                    result = true;
                }
            }
            return(result);
        }
Exemplo n.º 15
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIDocument  uiDoc = commandData.Application.ActiveUIDocument;
            Application app   = commandData.Application.Application;
            Document    doc   = uiDoc.Document;

            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("PerDocParameter");

                // get the current shared params definition file
                DefinitionFile sharedParamsFile = SharedParameter.GetSharedParamsFile(app);
                if (null == sharedParamsFile)
                {
                    TaskDialog.Show("Per document parameter", "Error getting the shared params file.");
                    return(Result.Failed);
                }
                // get or create the shared params group
                DefinitionGroup sharedParamsGroup = SharedParameter.GetOrCreateSharedParamsGroup(sharedParamsFile, kParamGroupName);
                if (null == sharedParamsGroup)
                {
                    TaskDialog.Show("Per document parameter", "Error getting the shared params group.");
                    return(Result.Failed);
                }
                // visible param
                Definition docParamDefVisible = SharedParameter.GetOrCreateSharedParamsDefinition(sharedParamsGroup, new ForgeTypeId(SpecTypeId.Number.ToString()), kParamNameVisible, true);
                if (null == docParamDefVisible)
                {
                    TaskDialog.Show("Per document parameter", "Error creating visible per-doc parameter.");
                    return(Result.Failed);
                }
                // invisible param
                Definition docParamDefInvisible = SharedParameter.GetOrCreateSharedParamsDefinition(sharedParamsGroup, new ForgeTypeId(SpecTypeId.Number.ToString()), kParamNameInvisible, false);
                if (null == docParamDefInvisible)
                {
                    TaskDialog.Show("Per document parameter", "Error creating invisible per-doc parameter.");
                    return(Result.Failed);
                }
                // bind the param
                try
                {
                    CategorySet catSet = app.Create.NewCategorySet();
                    catSet.Insert(doc.Settings.Categories.get_Item(BuiltInCategory.OST_ProjectInformation));
                    Binding binding = app.Create.NewInstanceBinding(catSet);
                    doc.ParameterBindings.Insert(docParamDefVisible, binding);
                    doc.ParameterBindings.Insert(docParamDefInvisible, binding);
                }
                catch (Exception e)
                {
                    TaskDialog.Show("Per document parameter", "Error binding shared parameter: " + e.Message);
                    return(Result.Failed);
                }
                // set the initial values
                // get the singleton project info element
                Element projInfoElem = GetProjectInfoElem(doc);

                if (null == projInfoElem)
                {
                    TaskDialog.Show("Per document parameter", "No project info elem found. Aborting command...");
                    return(Result.Failed);
                }
                // for simplicity, access params by name rather than by GUID:
                //projInfoElem.get_Parameter(kParamNameVisible).Set(55);
                //projInfoElem.get_Parameter(kParamNameInvisible).Set(0);

                // 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete:
                // 'This property is obsolete in Revit 2015, as more than one parameter can have the same name on a given element.
                // Use Element.Parameters to obtain a complete list of parameters on this Element,
                // or Element.GetParameters(String) to get a list of all parameters by name,
                // or Element.LookupParameter(String) to return the first available parameter with the given name.

                // modified code for Revit 2015
                projInfoElem.LookupParameter(kParamNameVisible).Set(55);
                projInfoElem.LookupParameter(kParamNameInvisible).Set(0);
                transaction.Commit();
            }


            return(Result.Succeeded);
        }
        /// <summary>
        /// Create a new shared parameter
        /// </summary>
        /// <param name="doc">Document</param>
        /// <param name="cat">Category to bind the parameter definition</param>
        /// <param name="nameSuffix">Parameter name suffix</param>
        /// <param name="typeParameter">Create a type parameter? If not, it is an instance parameter.</param>
        /// <returns></returns>
        bool CreateSharedParameter(
            Document doc,
            Category cat,
            int nameSuffix,
            bool typeParameter)
        {
            Application app = doc.Application;

            Autodesk.Revit.Creation.Application ca
                = app.Create;

            // get or set the current shared params filename:

            string filename
                = app.SharedParametersFilename;

            if (0 == filename.Length)
            {
                string       path = _filename;
                StreamWriter stream;
                stream = new StreamWriter(path);
                stream.Close();
                app.SharedParametersFilename = path;
                filename = app.SharedParametersFilename;
            }

            // get the current shared params file object:

            DefinitionFile file
                = app.OpenSharedParameterFile();

            if (null == file)
            {
                Util.ErrorMsg(
                    "Error getting the shared params file.");

                return(false);
            }

            // get or create the shared params group:

            DefinitionGroup group
                = file.Groups.get_Item(_groupname);

            if (null == group)
            {
                group = file.Groups.Create(_groupname);
            }

            if (null == group)
            {
                Util.ErrorMsg(
                    "Error getting the shared params group.");

                return(false);
            }

            // set visibility of the new parameter:

            // Category.AllowsBoundParameters property
            // indicates if a category can have user-visible
            // shared or project parameters. If it is false,
            // it may not be bound to visible shared params
            // using the BindingMap. Please note that
            // non-user-visible parameters can still be
            // bound to these categories.

            bool visible = cat.AllowsBoundParameters;

            // get or create the shared params definition:

            string defname = _defname + nameSuffix.ToString();

            Definition definition = group.Definitions.get_Item(
                defname);

            if (null == definition)
            {
                //definition = group.Definitions.Create( defname, _deftype, visible ); // 2014

                ExternalDefinitionCreationOptions opt
                    = new ExternalDefinitionCreationOptions(
                          defname, _deftype);

                opt.Visible = visible;

                definition = group.Definitions.Create(opt); // 2015
            }
            if (null == definition)
            {
                Util.ErrorMsg(
                    "Error creating shared parameter.");

                return(false);
            }

            // create the category set containing our category for binding:

            CategorySet catSet = ca.NewCategorySet();

            catSet.Insert(cat);

            // bind the param:

            try
            {
                Binding binding = typeParameter
          ? ca.NewTypeBinding(catSet) as Binding
          : ca.NewInstanceBinding(catSet) as Binding;

                // we could check if it is already bound,
                // but it looks like insert will just ignore
                // it in that case:

                doc.ParameterBindings.Insert(definition, binding);

                // we can also specify the parameter group here:

                //doc.ParameterBindings.Insert( definition, binding,
                //  BuiltInParameterGroup.PG_GEOMETRY );

                Debug.Print(
                    "Created a shared {0} parameter '{1}' for the {2} category.",
                    (typeParameter ? "type" : "instance"),
                    defname, cat.Name);
            }
            catch (Exception ex)
            {
                Util.ErrorMsg(string.Format(
                                  "Error binding shared parameter to category {0}: {1}",
                                  cat.Name, ex.Message));
                return(false);
            }
            return(true);
        }
        void f( Document doc )
        {
            Application app = doc.Application;

              DefinitionFile sharedParametersFile
            = app.OpenSharedParameterFile();

              DefinitionGroup group = sharedParametersFile
            .Groups.Create( "Reinforcement" );

              Definition def = group.Definitions.Create(
            "ReinforcementParameter", ParameterType.Text );

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

              //bics.Add(BuiltInCategory.OST_AreaRein);
              //bics.Add(BuiltInCategory.OST_FabricAreas);
              //bics.Add(BuiltInCategory.OST_FabricReinforcement);
              //bics.Add(BuiltInCategory.OST_PathRein);
              //bics.Add(BuiltInCategory.OST_Rebar);

              bics.Add( BuiltInCategory
            .OST_IOSRebarSystemSpanSymbolCtrl );

              CategorySet catset = new CategorySet();

              foreach( BuiltInCategory bic in bics )
              {
            catset.Insert(
              doc.Settings.Categories.get_Item( bic ) );
              }

              InstanceBinding binding
            = app.Create.NewInstanceBinding( catset );

              doc.ParameterBindings.Insert( def, binding,
            BuiltInParameterGroup.PG_CONSTRUCTION );
        }
        /// <summary>
        ///  Creates new shared parameter if it does not exist and bind it to the type or instance of the objects 
        /// </summary>
        /// <param name="paramType">Type of the parameter</param>
        /// <param name="categoriesForParam">Category of elements to bind the parameter to</param>
        /// <param name="defaultGroupName">Group name of the parameters</param>
        /// <param name="parameterName">Name of the parameter</param>
        /// <returns>TRUE if shared parameter is created, FALSE otherwise</returns>
        public static bool SetNewSharedParameter(this Element element, ParameterType paramType, CategorySet categoriesForParam, string parameterName, BuiltInParameterGroup group)
        {
            string defaultGroupName = "4P_imported_parameters"; //this is a hack to avoid multiple parameters with the same name.

            if (categoriesForParam == null) return false;
            if (categoriesForParam.Size == 0) return false;
            foreach (Category cat in categoriesForParam)
            {
                if (cat == null) return false;
                if (!cat.AllowsBoundParameters) return false;
            }

            Application application = element.Document.Application;
            Document document = element.Document;
            if (_definitionFile == null)
            {
                //ask for the location of the shared parameters file
                var dialog = new Microsoft.Win32.OpenFileDialog();
                dialog.CheckFileExists = false;
                dialog.Title = "Set shared pID file...";
                dialog.ShowDialog();
                string shrFilePath = dialog.FileName;
                if (shrFilePath == null)
                {
                    _definitionFile = application.OpenSharedParameterFile();
                    if (_definitionFile == null) SetSharedParamFileInUserProgramFolder(document);
                }
                else
                {
                    SetDefinitionFile(element, shrFilePath);
                }
            }
            if (_definitionFile == null) throw new Exception("Definition file must be set before creation of the new parameters.");

            DefinitionFile myDefinitionFile = _definitionFile;

            // Get parameter or create new one
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            Definition myDefinition = null;
            bool found = false;

            foreach (DefinitionGroup gr in myGroups)
            {
                foreach (Definition def in gr.Definitions)
                {
                    if (def.Name == parameterName)
                    {
                        myDefinition = def;
                        found = true;
                        break;
                    }
                }
                if (found) break;
            }

            //if there is not such a parameter new one is created in default group
            if (myDefinition == null)
            {
                DefinitionGroup myGroup = myGroups.get_Item(defaultGroupName);
                if (myGroup == null)
                {
                    myGroup = myGroups.Create(defaultGroupName);
                }

                // Create a type definition
                myDefinition = myGroup.Definitions.get_Item(parameterName);
                if (myDefinition == null)
                {
                    myDefinition = myGroup.Definitions.Create(parameterName, paramType);

                }
            }

            //Create an object of TypeBinding or InstanceBinding according to the Categories and "typeBinding" variable
            Binding binding = null;
            // Get the BingdingMap of current document.
            BindingMap bindingMap = document.ParameterBindings;
            binding = bindingMap.get_Item(myDefinition);

            bool bindOK = false;
            if (!element.CanHaveTypeAssigned() && !(element is Material) && !(element is ProjectInfo))
            {
                if (binding != null)
                {
                    TypeBinding typeBinding = binding as TypeBinding;
                    if (typeBinding == null)
                        throw new Exception("Parameter with this definition already exists and is bound to instances. It cannot be bound to the type at the same time");
                    foreach (Category cat in categoriesForParam) typeBinding.Categories.Insert(cat);
                    bindOK = bindingMap.ReInsert(myDefinition, binding, group);
                    return bindOK;
                }
                else
                {
                    binding = application.Create.NewTypeBinding(categoriesForParam);
                }
            }
            else
            {
                if (binding != null)
                {
                    InstanceBinding instBinding = binding as InstanceBinding;
                    if (instBinding == null)
                        throw new Exception("Parameter with this definition already exists and is bound to types. It cannot be bound to the instance at the same time");
                    foreach (Category cat in categoriesForParam) instBinding.Categories.Insert(cat);
                    bindOK = bindingMap.ReInsert(myDefinition, binding, group);
                    return bindOK;
                }
                else
                {
                    binding = application.Create.NewInstanceBinding(categoriesForParam);
                }
            }

            // Bind the definitions to the document
            bindOK = bindingMap.Insert(myDefinition, binding, group);
            return bindOK;
        }
Exemplo n.º 19
0
 private static void AddCategories(Document doc, CategorySet myCategories, BuiltInCategory cat)
 {
     Category myCategory = doc.Settings.Categories.get_Item(cat);
     myCategories.Insert(myCategory);
 }
Exemplo n.º 20
0
        public Task<List<Category>> GetCategoriesAsync(CategorySet set = CategorySet.All)
        {
            String query = "select * from Category";

            switch (set)
            {
                case CategorySet.All:
                default:
                    break;

                case CategorySet.Active:
                    query += " where IsActive = 1";
                    break;
            }

            return database.QueryAsync<Category>(query);                
        }
        void ProblemAddingParameterBindingForCategory(
            Document doc)
        {
            Application app = doc.Application;

              if( null == _spellingErrorCorrector )
              {
            _spellingErrorCorrector
              = new Util.SpellingErrorCorrector( app );
              }

              DefinitionFile sharedParametersFile
            = app.OpenSharedParameterFile();

              DefinitionGroup group = sharedParametersFile
            .Groups.Create( "Reinforcement" );

              //Definition def = group.Definitions.Create( // 2014
              //  "ReinforcementParameter", ParameterType.Text );

              ExternalDefinitionCreationOptions opt
            = new ExternalDefinitionCreationOptions(
              "ReinforcementParameter", ParameterType.Text );

              Definition def = group.Definitions.Create( opt ); // 2015

              // To handle both ExternalDefinitonCreationOptions
              // and ExternalDefinitionCreationOptions:

              def = _spellingErrorCorrector.NewDefinition(
            group.Definitions, "ReinforcementParameter",
            ParameterType.Text );

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

              //bics.Add(BuiltInCategory.OST_AreaRein);
              //bics.Add(BuiltInCategory.OST_FabricAreas);
              //bics.Add(BuiltInCategory.OST_FabricReinforcement);
              //bics.Add(BuiltInCategory.OST_PathRein);
              //bics.Add(BuiltInCategory.OST_Rebar);

              bics.Add( BuiltInCategory
            .OST_IOSRebarSystemSpanSymbolCtrl );

              CategorySet catset = new CategorySet();

              foreach( BuiltInCategory bic in bics )
              {
            catset.Insert(
              doc.Settings.Categories.get_Item( bic ) );
              }

              InstanceBinding binding
            = app.Create.NewInstanceBinding( catset );

              doc.ParameterBindings.Insert( def, binding,
            BuiltInParameterGroup.PG_CONSTRUCTION );
        }
Exemplo n.º 22
0
        /// <summary>
        /// 创建共享参数
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="app"></param>
        /// <returns></returns>
        public static bool ShareParameterGenerate(Document doc, Autodesk.Revit.ApplicationServices.Application app)
        {
            //设置共享参数
            string     TxtFileName = app.RecordingJournalFilename;
            Definition IdDf;
            Definition areaDf;
            Definition sizeDf;
            Definition XDf;
            Definition YDf;
            Definition ZDf;
            string     sNametmp = TxtFileName.Substring(0, TxtFileName.LastIndexOf("\\")) + "\\Teplate共享参数.txt";

            if (!File.Exists(sNametmp))
            {
                File.WriteAllText(sNametmp, "", Encoding.Default);
                app.SharedParametersFilename = sNametmp;
            }
            try
            {
                DefinitionFile  dsFile  = app.OpenSharedParameterFile();
                DefinitionGroup dsGroup = dsFile.Groups.ToList().Where(m => m.Name == "模板信息").First();
                IdDf   = dsGroup.Definitions.get_Item("HostElemID");
                areaDf = dsGroup.Definitions.get_Item("模板面积");
                sizeDf = dsGroup.Definitions.get_Item("模板尺寸");
                XDf    = dsGroup.Definitions.get_Item("X");
                YDf    = dsGroup.Definitions.get_Item("Y");
                ZDf    = dsGroup.Definitions.get_Item("Z");
            }
            catch
            {
                // 判断 路径是否有效,如果为空,读者可以创建一txt文件
                //将路径赋值给app.SharedParametersFilename
                DefinitionFile dfile = app.OpenSharedParameterFile();
                // 创建一个共享参数分组
                DefinitionGroup dg = dfile.Groups.Create("模板信息");

                // 参数创建的选项,包括参数名字,参数类型,用户是不是可以修改。。
                ExternalDefinitionCreationOptions elemID = new ExternalDefinitionCreationOptions("HostElemID", ParameterType.Integer);
                elemID.UserModifiable = false;
                ExternalDefinitionCreationOptions TemplateArea = new ExternalDefinitionCreationOptions("模板面积", ParameterType.Area);
                TemplateArea.UserModifiable = false;
                ExternalDefinitionCreationOptions TemplateSize = new ExternalDefinitionCreationOptions("模板尺寸", ParameterType.Text);
                TemplateSize.UserModifiable = false;
                ExternalDefinitionCreationOptions X = new ExternalDefinitionCreationOptions("X", ParameterType.Number);
                X.UserModifiable = false;
                ExternalDefinitionCreationOptions Y = new ExternalDefinitionCreationOptions("Y", ParameterType.Number);
                Y.UserModifiable = false;
                ExternalDefinitionCreationOptions Z = new ExternalDefinitionCreationOptions("Z", ParameterType.Number);
                Z.UserModifiable = false;

                // 创建参数
                IdDf   = dg.Definitions.Create(elemID);
                areaDf = dg.Definitions.Create(TemplateArea);
                sizeDf = dg.Definitions.Create(TemplateSize);
                XDf    = dg.Definitions.Create(X);
                YDf    = dg.Definitions.Create(Y);
                ZDf    = dg.Definitions.Create(Z);
            }
            if (IdDf == null || areaDf == null || YDf == null || XDf == null || ZDf == null || sizeDf == null)
            {
                return(false);
            }
            // 创建一个Category集合

            CategorySet cateSet = app.Create.NewCategorySet();

            // 获取墙的category
            Category TemplateCate = Category.GetCategory(doc, BuiltInCategory.OST_Parts);

            // 在Category集合中加入 模板的category
            bool flag = cateSet.Insert(TemplateCate);

            // 给 这个Category集合中的Category 创建一个实例绑定
            InstanceBinding TemBd = app.Create.NewInstanceBinding(cateSet);
            //ElementBinding TemBd = app.Create.NewTypeBinding(cateSet);

            // 获取当前Document的BindingMap
            BindingMap bmap = doc.ParameterBindings;

            //创建共享参数和Category之间的Binding
            bmap.Insert(IdDf, TemBd);
            bmap.Insert(areaDf, TemBd);
            bmap.Insert(sizeDf, TemBd);
            bmap.Insert(XDf, TemBd);
            bmap.Insert(YDf, TemBd);
            bmap.Insert(ZDf, TemBd);
            //设置视图,打开组成部分
            doc.ActiveView.PartsVisibility = PartsVisibility.ShowPartsOnly;
            Material partMat = null;

            try
            {
                partMat = FilterElementList <Material>(doc).Where(m => m.Name == "模板材质").First() as Material;
            }
            catch
            {
                partMat       = doc.GetElement(Material.Create(doc, "模板材质")) as Material;
                partMat.Color = new Color(255, 0, 0);
            }
            doc.Settings.Categories.get_Item(BuiltInCategory.OST_Parts).Material = partMat;
            return(true);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(
            ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Transaction transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "External Tool");

            try
            {
                transaction.Start();

                //Create a clear file as parameter file.
                String path    = Assembly.GetExecutingAssembly().Location;
                int    index   = path.LastIndexOf("\\");
                String newPath = path.Substring(0, index);
                newPath += "\\RevitParameters.txt";
                if (File.Exists(newPath))
                {
                    File.Delete(newPath);
                }
                FileStream fs = File.Create(newPath);
                fs.Close();

                //cache application handle
                Application revitApp = commandData.Application.Application;
                //prepare shared parameter file
                commandData.Application.Application.SharedParametersFilename = newPath;

                //Open shared parameter file
                DefinitionFile parafile = revitApp.OpenSharedParameterFile();

                //get walls category
                Category    wallCat    = commandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_Walls);
                CategorySet categories = revitApp.Create.NewCategorySet();
                categories.Insert(wallCat);

                InstanceBinding binding = revitApp.Create.NewInstanceBinding(categories);

                //Create a group
                DefinitionGroup apiGroup = parafile.Groups.Create("APIGroup");

                //Create a visible "VisibleParam" of text type.
                ExternalDefinitionCreationOptions ExternalDefinitionCreationOptions1 = new ExternalDefinitionCreationOptions("VisibleParam", ParameterType.Text);
                Definition visibleParamDef = apiGroup.Definitions.Create
                                                 (ExternalDefinitionCreationOptions1);
                ;
                BindingMap bindingMap = commandData.Application.ActiveUIDocument.Document.ParameterBindings;
                bindingMap.Insert(visibleParamDef, binding);

                //Create a invisible "InvisibleParam" of text type.
                ExternalDefinitionCreationOptions ExternalDefinitionCreationOptions2 = new ExternalDefinitionCreationOptions("InvisibleParam", ParameterType.Text);
                Definition invisibleParamDef = apiGroup.Definitions.Create
                                                   (ExternalDefinitionCreationOptions2);
                bindingMap.Insert(invisibleParamDef, binding);
            }
            catch (Exception e)
            {
                transaction.RollBack();
                message = e.ToString();
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            finally
            {
                transaction.Commit();
            }
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Create a project parameter
        /// </summary>
        /// <param name="app"></param>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="visible"></param>
        /// <param name="cats"></param>
        /// <param name="group"></param>
        /// <param name="inst"></param>
        public static void RawCreateProjectParameter(Autodesk.Revit.ApplicationServices.Application app, string name, ParameterType type, bool visible, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            string oriFile  = app.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";

            using (File.Create(tempFile)) { }
            app.SharedParametersFilename = tempFile;

            ExternalDefinitionCreationOptions externalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(name, type);

            ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create("TemporaryDefintionGroup").Definitions.Create(externalDefinitionCreationOptions) as ExternalDefinition;

            app.SharedParametersFilename = oriFile;
            File.Delete(tempFile);

            Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats);
            if (inst)
            {
                binding = app.Create.NewInstanceBinding(cats);
            }

            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;

            map.Insert(def, binding, group);
        }
        } // end of PopulateProjectParameterData

        #endregion // Private helper methods

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

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

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

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

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

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

            CategorySet categories     = null;
            Parameter   foundParameter = null;

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

            List <ProjectParameterData> projectParametersData
                = GetProjectParameterData(doc);

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

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

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

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

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

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

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

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

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

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

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

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

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

                        foundParameter
                            = projectInfoElement.get_Parameter(
                                  projectParameterData.Definition);

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

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

            StringBuilder sb = new StringBuilder();

            // Build column headers

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

            // Add each row.

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

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

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

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

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

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

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

            resultsDialog.Show();

            return(Result.Succeeded);
        }
Exemplo n.º 26
0
 public async Task<IEnumerable<String>> GetCategoryNamesAsync(CategorySet set = CategorySet.All)
 {
     IEnumerable<Category> categories = await GetCategoriesAsync(set);            
     return categories.Select(c => c.Name);            
 }
        public static BindSharedParamResult BindSharedParam(
            Document doc,
            Category cat,
            string paramName,
            string grpName,
            ParameterType paramType,
            bool visible,
            bool instanceBinding)
        {
            try // generic
            {
                Application app = doc.Application;

                // This is needed already here to
                // store old ones for re-inserting

                CategorySet catSet = app.Create.NewCategorySet();

                // Loop all Binding Definitions
                // IMPORTANT NOTE: Categories.Size is ALWAYS 1 !?
                // For multiple categories, there is really one
                // pair per each category, even though the
                // Definitions are the same...

                DefinitionBindingMapIterator iter
                    = doc.ParameterBindings.ForwardIterator();

                while (iter.MoveNext())
                {
                    Definition     def = iter.Key;
                    ElementBinding elemBind
                        = (ElementBinding)iter.Current;

                    // Got param name match

                    if (paramName.Equals(def.Name,
                                         StringComparison.CurrentCultureIgnoreCase))
                    {
                        // Check for category match - Size is always 1!

                        if (elemBind.Categories.Contains(cat))
                        {
                            // Check Param Type

                            if (paramType != def.ParameterType)
                            {
                                return(BindSharedParamResult.eWrongParamType);
                            }

                            // Check Binding Type

                            if (instanceBinding)
                            {
                                if (elemBind.GetType() != typeof(InstanceBinding))
                                {
                                    return(BindSharedParamResult.eWrongBindingType);
                                }
                            }
                            else
                            {
                                if (elemBind.GetType() != typeof(TypeBinding))
                                {
                                    return(BindSharedParamResult.eWrongBindingType);
                                }
                            }

                            // Check Visibility - cannot (not exposed)
                            // If here, everything is fine,
                            // ie already defined correctly

                            return(BindSharedParamResult.eAlreadyBound);
                        }

                        // If here, no category match, hence must
                        // store "other" cats for re-inserting

                        else
                        {
                            foreach (Category catOld
                                     in elemBind.Categories)
                            {
                                catSet.Insert(catOld); // 1 only, but no index...
                            }
                        }
                    }
                }

                // If here, there is no Binding Definition for
                // it, so make sure Param defined and then bind it!

                DefinitionFile defFile
                    = GetOrCreateSharedParamsFile(app);

                DefinitionGroup defGrp
                    = GetOrCreateSharedParamsGroup(
                          defFile, grpName);

                Definition definition
                    = GetOrCreateSharedParamDefinition(
                          defGrp, paramType, paramName, visible);

                catSet.Insert(cat);

                InstanceBinding bind = null;

                if (instanceBinding)
                {
                    bind = app.Create.NewInstanceBinding(
                        catSet);
                }
                else
                {
                    bind = app.Create.NewTypeBinding(catSet);
                }

                // There is another strange API "feature".
                // If param has EVER been bound in a project
                // (in above iter pairs or even if not there
                // but once deleted), Insert always fails!?
                // Must use .ReInsert in that case.
                // See also similar findings on this topic in:
                // http://thebuildingcoder.typepad.com/blog/2009/09/adding-a-category-to-a-parameter-binding.html
                // - the code-idiom below may be more generic:

                if (doc.ParameterBindings.Insert(
                        definition, bind))
                {
                    return(BindSharedParamResult.eSuccessfullyBound);
                }
                else
                {
                    if (doc.ParameterBindings.ReInsert(
                            definition, bind))
                    {
                        return(BindSharedParamResult.eSuccessfullyBound);
                    }
                    else
                    {
                        return(BindSharedParamResult.eFailed);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(
                                    "Error in Binding Shared Param: {0}",
                                    ex.Message));

                return(BindSharedParamResult.eFailed);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Заполняет параметры BDS_RebarHostId, BDS_RebarUniqueHostId, Мрк.МаркаКонструкции, Рзм.ТолщинаОсновы. В случае нескольких элемеетов знчения записываются через разделитель "|"
        /// </summary>
        /// <param name="rebar"></param>
        /// <param name="hostElem"></param>
        public static string WriteHostInfoSingleRebar(Autodesk.Revit.ApplicationServices.Application revitApp, CategorySet rebarCatSet, Element rebar, List <Element> hostElements)
        {
            if (Settings.UseHostId)
            {
                HashSet <string> hostIds = new HashSet <string>();
                foreach (Element hostElem in hostElements)
                {
                    ElementId hostId = hostElem.Id;
                    string    tempid = hostId.IntegerValue.ToString();
                    hostIds.Add(tempid);
                }
                Parameter rebarHostIdParam = RebarParametrisation.ParametersSupport.CheckAndAddSharedParameter(rebar, revitApp, rebarCatSet, "BDS_RebarHostId", BuiltInParameterGroup.INVALID, true);
                string    hostIdString     = ConvertHashsetToString(hostIds);
                rebarHostIdParam.Set(hostIdString);
            }
            if (Settings.UseUniqueHostId)
            {
                HashSet <string> hostUniqIds = new HashSet <string>();
                foreach (Element hostElem in hostElements)
                {
                    hostUniqIds.Add(hostElem.UniqueId);
                }

                Parameter rebarHostUniqueIdParam = RebarParametrisation.ParametersSupport.CheckAndAddSharedParameter(rebar, revitApp, rebarCatSet, "BDS_RebarUniqueHostId", BuiltInParameterGroup.INVALID, true);
                string    hostUniqueId           = ConvertHashsetToString(hostUniqIds);
                rebarHostUniqueIdParam.Set(hostUniqueId);
            }

            if (Settings.UseHostMark)
            {
                HashSet <string> hostMarks = new HashSet <string>();
                foreach (Element hostElem in hostElements)
                {
                    Parameter hostMarkParam = hostElem.get_Parameter(BuiltInParameter.ALL_MODEL_MARK);
                    string    tempMark      = hostMarkParam.AsString();
                    if (string.IsNullOrEmpty(tempMark))
                    {
                        return("Не заполнена марка у конструкции: " + hostElem.Id.IntegerValue.ToString() + " в файле " + hostElem.Document.Title);
                    }
                    else
                    {
                        hostMarks.Add(tempMark);
                    }
                }

                string hostMark = ConvertHashsetToString(hostMarks);
                ParametersSupport.TryWriteParameter(rebar, "Мрк.МаркаКонструкции", hostMark);
            }

            if (Settings.UseHostThickness)
            {
                Parameter thicknessRebarParam = rebar.LookupParameter("Рзм.ТолщинаОсновы");
                if (thicknessRebarParam != null)
                {
                    if (!thicknessRebarParam.IsReadOnly)
                    {
                        HashSet <double> hostWidths = new HashSet <double>();

                        foreach (Element hostElem in hostElements)
                        {
                            if (hostElem is Wall)
                            {
                                Wall hostWall = hostElem as Wall;
                                hostWidths.Add(hostWall.Width);
                            }
                            if (hostElem is Floor)
                            {
                                Floor     hostFloor      = hostElem as Floor;
                                Parameter thicknessParam = hostFloor.get_Parameter(BuiltInParameter.FLOOR_ATTR_THICKNESS_PARAM);
                                if (thicknessParam == null)
                                {
                                    thicknessParam = hostFloor.get_Parameter(BuiltInParameter.FLOOR_ATTR_DEFAULT_THICKNESS_PARAM);
                                    if (thicknessParam == null)
                                    {
                                        hostWidths.Add(0);
                                    }
                                }
                                if (thicknessParam != null)
                                {
                                    hostWidths.Add(thicknessParam.AsDouble());
                                }
                            }
                        }

                        double hostWidth = 0;
                        if (hostWidths.Count == 1)
                        {
                            hostWidth = hostWidths.First();
                        }
                        thicknessRebarParam.Set(hostWidth);
                    }
                }
            }
            return(string.Empty);
        }
Exemplo n.º 29
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIDocument  uidoc = commandData.Application.ActiveUIDocument;
            Application app   = commandData.Application.Application;
            Document    doc   = uidoc.Document;

            // Get the current shared params definition file
            DefinitionFile sharedParamsFile = GetSharedParamsFile(app);

            if (null == sharedParamsFile)
            {
                message = "Error getting the shared params file.";
                return(Result.Failed);
            }

            // Get or create the shared params group
            DefinitionGroup sharedParamsGroup = GetOrCreateSharedParamsGroup(
                sharedParamsFile, kSharedParamsGroupAPI);

            if (null == sharedParamsGroup)
            {
                message = "Error getting the shared params group.";
                return(Result.Failed);
            }

            Category cat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Doors);

            // Visibility of the new parameter:
            // Category.AllowsBoundParameters property indicates if a category can
            // have shared or project parameters. If it is false, it may not be bound
            // to shared parameters using the BindingMap. Please note that non-user-visible
            // parameters can still be bound to these categories.
            bool visible = cat.AllowsBoundParameters;

            // Get or create the shared params definition
            ForgeTypeId forgeTypeId        = new ForgeTypeId(SpecTypeId.Number.ToString());
            Definition  fireRatingParamDef = GetOrCreateSharedParamsDefinition(
                sharedParamsGroup, forgeTypeId, kSharedParamsDefFireRating, visible);

            if (null == fireRatingParamDef)
            {
                message = "Error in creating shared parameter.";
                return(Result.Failed);
            }

            // Create the category set for binding and add the category
            // we are interested in, doors or walls or whatever:
            CategorySet catSet = app.Create.NewCategorySet();

            try
            {
                catSet.Insert(cat);
            }
            catch (Exception)
            {
                message = string.Format(
                    "Error adding '{0}' category to parameters binding set.",
                    cat.Name);
                return(Result.Failed);
            }

            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("Bind parameter");
                // Bind the param
                try
                {
                    Binding binding = app.Create.NewInstanceBinding(catSet);
                    // We could check if already bound, but looks like Insert will just ignore it in such case
                    doc.ParameterBindings.Insert(fireRatingParamDef, binding);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    transaction.RollBack();
                    return(Result.Failed);
                }
            }

            return(Result.Succeeded);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Добавить привязку к категории для параметра проекта
        /// </summary>
        public static BindSharedParamResult BindSharedParam(Document doc, Element elem, string paramName, Definition definition)
        {
            try
            {
                Application app = doc.Application;

                //собираю уже добавленные категории для повторной вставки и добавления новой категории
                CategorySet catSet = app.Create.NewCategorySet();

                // Loop all Binding Definitions
                // IMPORTANT NOTE: Categories.Size is ALWAYS 1 !?
                // For multiple categories, there is really one
                // pair per each category, even though the
                // Definitions are the same...

                DefinitionBindingMapIterator iter
                    = doc.ParameterBindings.ForwardIterator();

                while (iter.MoveNext())
                {
                    Definition def = iter.Key;
                    if (!paramName.Equals(def.Name))
                    {
                        continue;
                    }

                    ElementBinding elemBind
                        = (ElementBinding)iter.Current;

                    // Check for category match - Size is always 1!


                    // If here, no category match, hence must
                    // store "other" cats for re-inserting

                    foreach (Category catOld in elemBind.Categories)
                    {
                        catSet.Insert(catOld); // 1 only, but no index...
                    }
                }

                // If here, there is no Binding Definition for
                // it, so make sure Param defined and then bind it!


                Category cat = elem.Category;
                catSet.Insert(cat);

                InstanceBinding bind = app.Create.NewInstanceBinding(catSet);

                //используем Insert или ReInsert, что сработает
                if (doc.ParameterBindings.Insert(definition, bind))
                {
                    return(BindSharedParamResult.eSuccessfullyBound);
                }
                else
                {
                    if (doc.ParameterBindings.ReInsert(definition, bind))
                    {
                        return(BindSharedParamResult.eSuccessfullyBound);
                    }
                    else
                    {
                        return(BindSharedParamResult.eFailed);
                    }
                }
            }
            catch (Exception ex)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Error", string.Format(
                                                      "Error in Binding Shared Param: {0}",
                                                      ex.Message));

                return(BindSharedParamResult.eFailed);
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// Initializes element or type parameter binding.
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="elm"></param>
        /// <param name="paramPath"></param>
        public static void InitParamList(this UIApplication uiapp, Element elm, string paramPath)
        {
            if (uiapp == null)
            {
                throw new ArgumentNullException(nameof(uiapp));
            }

            if (elm == null)
            {
                throw new ArgumentNullException(nameof(elm));
            }

            if (paramPath == null)
            {
                throw new ArgumentNullException(nameof(paramPath));
            }

            var doc        = uiapp.ActiveUIDocument.Document;
            var bindingMap = doc.ParameterBindings;
            var gs         = uiapp.GetGroupList(paramPath);
            var elmCtgs    = new CategorySet();

            elmCtgs.Insert(elm.Category);

            foreach (var group in GetGroups(paramPath))
            {
                var paramGroup = gs.GetGroup(group.GroupName);

                foreach (var param in group.Params)
                {
                    var definition = paramGroup.GetDefinition(param.ParamName, param.CanEdit);
                    var binding    = bindingMap.get_Item(definition);

                    // If the parameter group's name contains type key, it's means type binding.
                    if (!paramGroup.Name.Contains("Group"))
                    {
                        if (binding is InstanceBinding instanceBinding)
                        {
                            bindingMap.ReInsert(definition, instanceBinding);
                        }
                        else
                        {
                            instanceBinding = uiapp.Application.Create.NewInstanceBinding(elmCtgs);
                            bindingMap.Insert(definition, instanceBinding);
                        }
                    }
                    else
                    {
                        if (binding is TypeBinding typeBinding)
                        {
                            bindingMap.ReInsert(definition, typeBinding);
                        }
                        else
                        {
                            typeBinding = uiapp.Application.Create.NewTypeBinding(elmCtgs);
                            bindingMap.Insert(definition, typeBinding);
                        }
                    }
                }
            }
        }
            public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs)
            {
                global::System.Xml.Schema.XmlSchemaComplexType type     = new global::System.Xml.Schema.XmlSchemaComplexType();
                global::System.Xml.Schema.XmlSchemaSequence    sequence = new global::System.Xml.Schema.XmlSchemaSequence();
                CategorySet ds = new CategorySet();

                global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
                any1.Namespace       = "http://www.w3.org/2001/XMLSchema";
                any1.MinOccurs       = new decimal(0);
                any1.MaxOccurs       = decimal.MaxValue;
                any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any1);
                global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
                any2.Namespace       = "urn:schemas-microsoft-com:xml-diffgram-v1";
                any2.MinOccurs       = new decimal(1);
                any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any2);
                global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
                attribute1.Name       = "namespace";
                attribute1.FixedValue = ds.Namespace;
                type.Attributes.Add(attribute1);
                global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
                attribute2.Name       = "tableTypeName";
                attribute2.FixedValue = "CategoryDataTable";
                type.Attributes.Add(attribute2);
                type.Particle = sequence;
                global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
                if (xs.Contains(dsSchema.TargetNamespace))
                {
                    global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
                    global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
                    try {
                        global::System.Xml.Schema.XmlSchema schema = null;
                        dsSchema.Write(s1);
                        for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();)
                        {
                            schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                            s2.SetLength(0);
                            schema.Write(s2);
                            if ((s1.Length == s2.Length))
                            {
                                s1.Position = 0;
                                s2.Position = 0;
                                for (; ((s1.Position != s1.Length) &&
                                        (s1.ReadByte() == s2.ReadByte()));)
                                {
                                    ;
                                }
                                if ((s1.Position == s1.Length))
                                {
                                    return(type);
                                }
                            }
                        }
                    }
                    finally {
                        if ((s1 != null))
                        {
                            s1.Close();
                        }
                        if ((s2 != null))
                        {
                            s2.Close();
                        }
                    }
                }
                xs.Add(dsSchema);
                return(type);
            }
Exemplo n.º 33
0
        /// <summary>
        /// Create project parameter from existing shared parameter
        /// </summary>
        /// <param name="app"></param>
        /// <param name="name"></param>
        /// <param name="cats"></param>
        /// <param name="group"></param>
        /// <param name="inst"></param>
        public static void RawCreateProjectParameterFromExistingSharedParameter(Autodesk.Revit.ApplicationServices.Application app, string name, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            //Location of the shared parameters
            string oriFile = app.SharedParametersFilename;

            //My Documents
            var newpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            //Create txt inside my documents
            Extract("RenumberParts", newpath, "Resources", "SP_RenumberParts.txt");

            //Create variable with the location on SP.txt inside my documents
            string tempFile = newpath + @"\SP_RenumberParts.txt";

            //Change the location of the shared parameters for the SP location
            app.SharedParametersFilename = tempFile;
            DefinitionFile defFile = app.OpenSharedParameterFile();

            var v = (from DefinitionGroup dg in defFile.Groups
                     from ExternalDefinition d in dg.Definitions
                     where d.Name == name
                     select d);


            if (v == null || v.Count() < 1)
            {
                throw new Exception("Invalid Name Input!wwwww");
            }

            ExternalDefinition def = v.First();

            //Place original SP file
            app.SharedParametersFilename = oriFile;

            //Delete SP temporary file
            System.IO.File.Delete(tempFile);

            Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats);
            if (inst)
            {
                binding = app.Create.NewInstanceBinding(cats);
            }

            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;

            map.Insert(def, binding, group);
        }
Exemplo n.º 34
0
        //----------------------------------------------------------
        public string Them_Hoac_Xoa_Parameter_Trong_Project(UIApplication uiapp, Document doc)
        {
            string result = "F";

            try
            {
                Transaction transaction = new Transaction(doc);
                transaction.Start("Parameters");
                var enums      = Enum.GetValues(typeof(BuiltInCategory));
                var enums1     = Enum.GetValues(typeof(BuiltInParameterGroup));
                var categories = doc.Settings.Categories;
                foreach (data_group_share_parameter item in my_group_share_parameter)
                {
                    DefinitionFile parafile = uiapp.Application.OpenSharedParameterFile();
                    if (parafile != null)
                    {
                        DefinitionGroup myGroup = parafile.Groups.get_Item(item.ten_group_parameter);

                        foreach (data_item_share_parameter subitem in item.Children)
                        {
                            if (subitem.exist_parameter == true)
                            {
                                //BuiltInParameterGroup builtInParameterGroup = BuiltInParameterGroup.PG_TEXT;
                                //foreach (BuiltInParameterGroup builtIn in enums1)
                                //{
                                //    if (builtIn.ToString().Split('_')[0] == subitem.ten_parameter && builtIn != BuiltInParameterGroup.INVALID) builtInParameterGroup = builtIn;
                                //}

                                Definition  myDefinition_ProductDate = myGroup.Definitions.get_Item(subitem.ten_parameter);
                                CategorySet myCategories             = uiapp.Application.Create.NewCategorySet();
                                foreach (BuiltInCategory buildCategory in enums)
                                {
                                    try
                                    {
                                        Category cate = categories.get_Item(buildCategory);
                                        if (cate.AllowsBoundParameters == true && cate.CategoryType.ToString() == "Model")
                                        {
                                            myCategories.Insert(cate);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }

                                try
                                {
                                    BindingMap bindingMap = doc.ParameterBindings;
                                    if (subitem.ten_parameter != "Chiều dày hoàn thiện")
                                    {
                                        InstanceBinding instanceBinding = uiapp.Application.Create.NewInstanceBinding(myCategories);
                                        bindingMap.Insert(myDefinition_ProductDate, instanceBinding);
                                    }
                                    else
                                    {
                                        TypeBinding instanceBinding = uiapp.Application.Create.NewTypeBinding(myCategories);
                                        bindingMap.Insert(myDefinition_ProductDate, instanceBinding);
                                    }
                                    if (my_data_parameter_current.Any(x => x.ten_parameter == subitem.ten_parameter) == false)
                                    {
                                        my_data_parameter_current.Add(new data_parameter()
                                        {
                                            ten_parameter = subitem.ten_parameter
                                        });
                                    }
                                }
                                catch (Exception)
                                {
                                }
                            }
                            else
                            {
                                try
                                {
                                    Definition myDefinition_ProductDate = myGroup.Definitions.get_Item(subitem.ten_parameter);
                                    BindingMap bindingMap = doc.ParameterBindings;
                                    bindingMap.Remove(myDefinition_ProductDate);
                                    data_parameter item_remove = my_data_parameter_current.First(x => x.ten_parameter == subitem.ten_parameter);
                                    if (item_remove != null)
                                    {
                                        my_data_parameter_current.Remove(item_remove);
                                    }
                                }
                                catch (Exception)
                                {
                                }
                            }
                            try
                            {
                                if (my_data_parameter_current.Any(x => x.ten_parameter == subitem.ten_parameter) == false)
                                {
                                    my_data_parameter_need.First(x => x.ten_parameter == subitem.ten_parameter).color = Source.color_error;
                                }
                                else
                                {
                                    my_data_parameter_need.First(x => x.ten_parameter == subitem.ten_parameter).color = Source.color;
                                }
                                thong_tin_parameter.Items.Refresh();
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Not found share parameter file!!!", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                result = "S";
                transaction.Commit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return(result);
        }
Exemplo n.º 35
0
 public bool IsCommandAvailable(UIApplication a, CategorySet b)
 {
     return(true);
 }
Exemplo n.º 36
0
 bool IExternalCommandAvailability.IsCommandAvailable(UIApplication applicationData, CategorySet selectedCategories) => true;
Exemplo n.º 37
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static Definition SharedParameter(Document document, string parameterName, ParameterType parameterType, string parameterGroup, bool instance, IEnumerable <Category> categories)
        {
            // Inspired by https://github.com/DynamoDS/DynamoRevit/blob/master/src/Libraries/RevitNodes/Elements/Parameter.cs

            if (categories != null && !categories.Any())
            {
                BH.Engine.Reflection.Compute.RecordError($"Parameter {parameterName} of type {LabelUtils.GetLabelFor(parameterType)} could not be created because no category bindings were provided.");
                return(null);
            }

            // get current shared parameter file
            string sharedParameterFile = document.Application.SharedParametersFilename;

            // if the file does not exist, throw an error
            if (string.IsNullOrWhiteSpace(sharedParameterFile) || !System.IO.File.Exists(sharedParameterFile))
            {
                BH.Engine.Reflection.Compute.RecordError("The shared parameters file specified in the document does not exist.");
                return(null);
            }

            // Create new parameter group if it does not exist yet
            DefinitionGroup groupDef = document.Application.OpenSharedParameterFile().Groups.get_Item(parameterGroup);

            if (groupDef == null)
            {
                try
                {
                    groupDef = document.Application.OpenSharedParameterFile().Groups.Create(parameterGroup);
                }
                catch
                {
                    BH.Engine.Reflection.Compute.RecordError("New group could not be created in the active document's shared parameter file. Please try using an existing group or unlocking the shared parameter file.");
                    return(null);
                }
            }

            // If the parameter definition does exist return it
            bool       bindings = false;
            Definition def      = groupDef.Definitions.get_Item(parameterName);

            if (def != null)
            {
                if (document.ParameterBindings.Contains(def))
                {
                    BH.Engine.Reflection.Compute.RecordWarning($"Parameter {parameterName} already exists in group {parameterGroup}. It already has category bindings, they were not updated - please make sure they are correct.");
                    bindings = true;
                }
                else
                {
                    BH.Engine.Reflection.Compute.RecordWarning($"Parameter {parameterName} already exists in group {parameterGroup}. It did not have any category bindings, so input bindings were applied.");
                }
            }
            else
            {
                def = groupDef.Definitions.Create(new ExternalDefinitionCreationOptions(parameterName, parameterType)) as ExternalDefinition;
            }

            if (!bindings)
            {
                // Apply instance or type binding
                CategorySet paramCategories = (categories == null) ? document.CategoriesWithBoundParameters() : Create.CategorySet(document, categories);

                Binding bin = (instance) ?
                              (Binding)document.Application.Create.NewInstanceBinding(paramCategories) :
                              (Binding)document.Application.Create.NewTypeBinding(paramCategories);

                document.ParameterBindings.Insert(def, bin);
            }

            return(def);
        }
Exemplo n.º 38
0
 public virtual bool IsCommandAvailable(UIApplication applicationData, CategorySet selectedCategories)
 {
     return(applicationData?.ActiveUIDocument?.Document?.IsValidObject ?? false);
 }
Exemplo n.º 39
0
        public static bool AddProjectParameter(this Document document, ExternalDefinitionCreationOptions externalDefinitionCreationOptions, IEnumerable <BuiltInCategory> builtInCategories, bool instance, BuiltInParameterGroup builtInParameterGroup)
        {
            if (document == null || externalDefinitionCreationOptions == null || builtInCategories == null)
            {
                return(false);
            }

            string name = externalDefinitionCreationOptions.Name;

            if (string.IsNullOrWhiteSpace(name))
            {
                return(false);
            }

            CategorySet categorySet = Create.CategorySet(document, builtInCategories);

            if (categorySet == null || categorySet.Size == 0)
            {
                return(false);
            }

            ElementBinding elementBinding = null;

            if (Query.TryGetElementBinding(document, externalDefinitionCreationOptions.Name, out InternalDefinition internalDefinition, out elementBinding))
            {
                return(false);
            }

            Autodesk.Revit.ApplicationServices.Application application = new UIDocument(document).Application.Application;

            bool result = false;

            string path = System.IO.Path.GetTempFileName();

            try
            {
                using (SharedParameterFileWrapper sharedParameterFileWrapper = new SharedParameterFileWrapper(application))
                {
                    Definition definition = sharedParameterFileWrapper.Create(System.IO.Path.GetRandomFileName(), externalDefinitionCreationOptions);
                    if (definition != null)
                    {
                        if (instance)
                        {
                            elementBinding = application.Create.NewInstanceBinding(categorySet);
                        }
                        else
                        {
                            elementBinding = application.Create.NewTypeBinding(categorySet);
                        }

                        if (elementBinding != null)
                        {
                            result = document.ParameterBindings.Insert(definition, elementBinding, builtInParameterGroup);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
            }
            finally
            {
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
            }

            return(result);
        }
Exemplo n.º 40
0
 /// <summary>
 /// Command Availability
 /// </summary>
 /// <param name="applicationData"></param>
 /// <param name="selectedCategories"></param>
 /// <returns></returns>
 public bool IsCommandAvailable(UIApplication applicationData, CategorySet selectedCategories)
 {
     return applicationData.ActiveUIDocument != null;
 }