/***************************************************/
        /****               Public Methods              ****/
        /***************************************************/

        public static ParameterElement ToRevitParameterElement(this ParameterDefinition parameterDefinition, Document document, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null)
        {
            if (parameterDefinition == null)
            {
                return(null);
            }

            ParameterElement parameterElement = refObjects.GetValue <ParameterElement>(document, parameterDefinition.BHoM_Guid);

            if (parameterElement != null)
            {
                return(parameterElement);
            }

            settings = settings.DefaultIfNull();

            Definition definition = Create.Parameter(document, parameterDefinition.Name, parameterDefinition.ParameterType, parameterDefinition.ParameterGroup, parameterDefinition.Instance, parameterDefinition.Categories, parameterDefinition.Shared, parameterDefinition.Discipline);

            if (definition is ExternalDefinition)
            {
                parameterElement = SharedParameterElement.Lookup(document, ((ExternalDefinition)definition).GUID);
            }
            else if (definition is InternalDefinition)
            {
                parameterElement = document.GetElement(((InternalDefinition)definition).Id) as ParameterElement;
            }

            refObjects.AddOrReplace(parameterDefinition, parameterElement);
            return(parameterElement);
        }
        /// <summary>
        /// Helper method to control `SetAllowVaryBetweenGroups`
        /// option for instance binding param
        /// </summary>
        static void SetInstanceParamVaryBetweenGroupsBehaviour(
            Document doc,
            Guid guid,
            bool allowVaryBetweenGroups = true)
        {
            try // last resort
            {
                SharedParameterElement sp
                    = SharedParameterElement.Lookup(doc, guid);

                // Should never happen as we will call
                // this only for *existing* shared param.

                if (null == sp)
                {
                    return;
                }

                InternalDefinition def = sp.GetDefinition();

                if (def.VariesAcrossGroups != allowVaryBetweenGroups)
                {
                    // Must be within an outer transaction!

                    def.SetAllowVaryBetweenGroups(doc, allowVaryBetweenGroups);
                }
            }
            catch { } // ideally, should report something to log...
        }
Esempio n. 3
0
        //private void CreateExternalSharedParamFile(string sharedParameterFile)
        //{
        //    System.IO.FileStream fileStream = System.IO.File.Create(sharedParameterFile);
        //    fileStream.Close();
        //}
        //private void ShowDefinitionFileInfo(DefinitionFile myDefinitionFile)
        //{
        //    StringBuilder fileInformation = new StringBuilder(500);

        //    // get the file name
        //    fileInformation.AppendLine("File Name: " + myDefinitionFile.Filename);

        //    // iterate the Definition groups of this file
        //    foreach (DefinitionGroup myGroup in myDefinitionFile.Groups)
        //    {
        //        // get the group name
        //        fileInformation.AppendLine("Group Name: " + myGroup.Name);

        //        // iterate the difinitions
        //        foreach (Definition definition in myGroup.Definitions)
        //        {
        //            // get definition name
        //            fileInformation.AppendLine("Definition Name: " + definition.Name);
        //        }
        //    }
        //    TaskDialog.Show("Revit", fileInformation.ToString());
        //}
        //private DefinitionFile SetAndOpenExternalSharedParamFile(Autodesk.Revit.ApplicationServices.Application application, string sharedParameterFile)
        //{
        //    // set the path of shared parameter file to current Revit
        //    application.SharedParametersFilename = sharedParameterFile;
        //    // open the file
        //    return application.OpenSharedParameterFile();
        //}
        //private void ReadEditExternalParam(DefinitionFile file)
        //{
        //    // get ExternalDefinition from shared parameter file
        //    DefinitionGroups myGroups = file.Groups;
        //    DefinitionGroup myGroup = myGroups.get_Item("MyGroup");
        //    if (myGroup != null)
        //    {
        //        ExternalDefinition myExtDef = myGroup.Definitions.get_Item("MyParam") as ExternalDefinition;
        //        if (myExtDef != null)
        //        {
        //            DefinitionGroup newGroup = myGroups.get_Item("AnotherGroup");
        //            if (newGroup != null)
        //            {
        //                // change the OwnerGroup of the ExternalDefinition
        //                myExtDef.OwnerGroup = newGroup;
        //            }
        //        }
        //    }
        //}
        private void createCategory()
        {
            try
            {
                SharedParameterElement sp = SharedParameterElement.Lookup(doc, new Guid("2FB57A90-CF7B-4F49-8127-B0C7F7276FD7"));
                if (sp == null)
                {
                    using (Transaction myTrans = new Transaction(doc))
                    {
                        myTrans.Start("Attach Parameters");
                        try
                        {
                            sharedParameterYarat(revitApp, "Parametre1", "REVITeRA", ParameterType.Text, true, new Guid("2FB57A90-CF7B-4F49-8127-B0C7F7276FD7"));
                            sharedParameterYarat(revitApp, "Parametre2", "REVITeRA", ParameterType.Text, true, new Guid("641644D9-B65F-4EF7-96A5-D9B243B8477D"));
                            sharedParameterYarat(revitApp, "Parametre3", "REVITeRA", ParameterType.Text, true, new Guid("208BB516-A3CB-47AC-B339-3EFDDF5DE71A"));
                            CategorySet cats1 = new CategorySet();
                            cats1 = revitApp.Create.NewCategorySet();
                            cats1.Insert(doc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls));
                            sharedParameterEkle(revitApp, "Parametre1", cats1, BuiltInParameterGroup.INVALID, true);
                            sharedParameterEkle(revitApp, "Parametre2", cats1, BuiltInParameterGroup.INVALID, true);
                            sharedParameterEkle(revitApp, "Parametre3", cats1, BuiltInParameterGroup.INVALID, true);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        myTrans.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Generic Parameter value filter. An attempt to write a generic method,
        /// that returns an element filter consumed by FilteredElementCollector.
        /// </summary>
        /// <typeparam name="T1">Type of the parameter VALUE to filter by.</typeparam>
        /// <typeparam name="T2">Type of the PARAMETER to filter.</typeparam>
        /// <param name="value">Currently: string, bool.</param>
        /// <param name="parameterId">Currently: Guid, BuiltInCategory.</param>
        /// <returns>ElementParameterFilter consumed by FilteredElementCollector.</returns>
        public static ElementParameterFilter ParameterValueGenericFilter <T1, T2>(Document doc, T1 value, T2 parameterId)
        {
            //Initialize ParameterValueProvider
            ParameterValueProvider pvp = null;

            switch (parameterId)
            {
            case BuiltInParameter bip:
                pvp = new ParameterValueProvider(new ElementId((int)bip));
                break;

            case Guid guid:
                SharedParameterElement spe = SharedParameterElement.Lookup(doc, guid);
                pvp = new ParameterValueProvider(spe.Id);
                break;

            default:
                throw new NotImplementedException("ParameterValueGenericFilter: T2 (parameter) type not implemented!");
            }

            //Branch off to value types
            switch (value)
            {
            case string str:
                FilterStringRuleEvaluator fsrE = new FilterStringEquals();
                FilterStringRule          fsr  = new FilterStringRule(pvp, fsrE, str, false);
                return(new ElementParameterFilter(fsr));

            case bool bol:
                int _value;

                if (bol == true)
                {
                    _value = 1;
                }
                else
                {
                    _value = 0;
                }

                FilterNumericRuleEvaluator fnrE = new FilterNumericEquals();
                FilterIntegerRule          fir  = new FilterIntegerRule(pvp, fnrE, _value);
                return(new ElementParameterFilter(fir));

            default:
                throw new NotImplementedException("ParameterValueGenericFilter: T1 (value) type not implemented!");
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Проверяет налиxие общего параметра у элемента. Если параметр есть - возвращает его. Иначе добавляет параметр из файла общих параметров.
        /// </summary>
        /// <param name="elem"></param>
        /// <param name="app"></param>
        /// <param name="catset"></param>
        /// <param name="ParameterName"></param>
        /// <param name="paramGroup"></param>
        /// <param name="SetVaryByGroups"></param>
        /// <returns></returns>
        public static Parameter CheckAndAddSharedParameter(Element elem, Application app, CategorySet catset, string ParameterName, BuiltInParameterGroup paramGroup, bool SetVaryByGroups)
        {
            Document  doc   = elem.Document;
            Parameter param = elem.LookupParameter(ParameterName);

            if (param != null)
            {
                return(param);
            }

            string oldSharedParamsFile = app.SharedParametersFilename;

            app.SharedParametersFilename = @"\\picompany.ru\pikp\lib\_CadSettings\02_Revit\04. Shared Parameters\SP-ALL-PIC.txt";

            ExternalDefinition exDef           = null;
            string             sharedFile      = app.SharedParametersFilename;
            DefinitionFile     sharedParamFile = app.OpenSharedParameterFile();

            foreach (DefinitionGroup defgroup in sharedParamFile.Groups)
            {
                foreach (Definition def in defgroup.Definitions)
                {
                    if (def.Name == ParameterName)
                    {
                        exDef = def as ExternalDefinition;
                    }
                }
            }
            if (exDef == null)
            {
                throw new Exception("В файл общих параметров не найден общий параметр " + ParameterName);
            }

            bool checkContains = doc.ParameterBindings.Contains(exDef);

            if (checkContains)
            {
                var res = BindSharedParam(doc, elem, ParameterName, exDef);
            }

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

            doc.ParameterBindings.Insert(exDef, newIB, paramGroup);

            if (SetVaryByGroups)
            {
                doc.Regenerate();

                SharedParameterElement spe    = SharedParameterElement.Lookup(doc, exDef.GUID);
                InternalDefinition     intDef = spe.GetDefinition();
                intDef.SetAllowVaryBetweenGroups(doc, true);
            }
            doc.Regenerate();


            app.SharedParametersFilename = oldSharedParamsFile;
            param = elem.LookupParameter(ParameterName);
            if (param == null)
            {
                throw new Exception("Не удалось добавить обший параметр " + ParameterName);
            }

            return(param);
        }
Esempio n. 6
0
        void ReconstructSharedParameterByName
        (
            Document doc,
            ref SharedParameterElement element,

            [Description("Parameter Name")] string name,
            [Description("Overwrite Parameter definition if found"), Optional, DefaultValue(false)] bool overwrite
        )
        {
            var  parameterGUID  = default(Guid?);
            var  parameterType  = ParameterType.Text;
            var  parameterGroup = BuiltInParameterGroup.PG_DATA;
            bool instance       = true;
            bool visible        = true;

            using (var bindings = doc.ParameterBindings.ReverseIterator())
            {
                while (bindings.MoveNext())
                {
                    if (bindings.Key is InternalDefinition def)
                    {
                        if
                        (
                            def.Name == name &&
                            def.Visible == visible &&
                            def.ParameterType == parameterType &&
                            def.ParameterGroup == parameterGroup &&
                            (instance ? bindings.Current is InstanceBinding : bindings.Current is TypeBinding)
                        )
                        {
                            if (doc.GetElement(def.Id) is SharedParameterElement parameterElement)
                            {
                                if (!overwrite)
                                {
                                    ReplaceElement(ref element, parameterElement);
                                    throw new CancelException($"A parameter called \"{name}\" is already in the document");
                                }
                                parameterGUID = parameterElement.GuidValue;
                            }
                        }
                    }
                }
            }

            using (var defOptions = new ExternalDefinitionCreationOptions(name, parameterType)
            {
                Visible = visible
            })
            {
                if (parameterGUID.HasValue)
                {
                    defOptions.GUID = parameterGUID.Value;
                }

                using (var definitionFile = Revit.ActiveUIApplication.Application.CreateSharedParameterFile())
                {
                    if (definitionFile?.Groups.Create(LabelUtils.GetLabelFor(parameterGroup)).Definitions.Create(defOptions) is ExternalDefinition definition)
                    {
                        // TODO : Ask for categories
                        using (var categorySet = new CategorySet())
                        {
                            foreach (var category in doc.Settings.Categories.Cast <Category>().Where(category => category.AllowsBoundParameters))
                            {
                                categorySet.Insert(category);
                            }

                            var binding = instance ? (ElementBinding) new InstanceBinding(categorySet) : (ElementBinding) new TypeBinding(categorySet);

                            if (!doc.ParameterBindings.Insert(definition, binding, parameterGroup))
                            {
                                if (!overwrite || !doc.ParameterBindings.ReInsert(definition, binding, parameterGroup))
                                {
                                    throw new InvalidOperationException("Failed while creating the parameter binding.");
                                }
                            }
                        }

                        parameterGUID = definition.GUID;
                    }
                }
            }

            ReplaceElement(ref element, SharedParameterElement.Lookup(doc, parameterGUID.Value));
        }
Esempio n. 7
0
        void ReconstructParameterByName
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            [Description("Parameter Name")] string name,
            [Description("Overwrite Parameter definition if found"), Optional, DefaultValue(false)] bool overwrite
        )
        {
            var app = Revit.ActiveUIApplication.Application;

            var  parameterType  = ParameterType.Text;
            var  parameterGroup = BuiltInParameterGroup.PG_DATA;
            bool instance       = true;
            bool visible        = true;

            if (!overwrite)
            {
                using (var bindings = doc.ParameterBindings.ReverseIterator())
                {
                    while (bindings.MoveNext())
                    {
                        if (bindings.Key is InternalDefinition def)
                        {
                            if
                            (
                                def.Name == name &&
                                def.Visible == visible &&
                                def.ParameterType == parameterType &&
                                def.ParameterGroup == parameterGroup &&
                                bindings.Current is InstanceBinding)
                            {
                                if (doc.GetElement(def.Id) is ParameterElement parameterElement)
                                {
                                    ReplaceElement(ref element, parameterElement);
                                    throw new WarningException($"A parameter called \"{name}\" is already in the document");
                                }
                            }
                        }
                    }
                }
            }

            using (var defOptions = new ExternalDefinitionCreationOptions(name, parameterType)
            {
                Visible = visible
            })
            {
                string sharedParametersFilename = app.SharedParametersFilename;
                string tempParametersFilename   = Path.GetTempFileName() + ".txt";

                ExternalDefinition definition = null;
                try
                {
                    // Create Temp Shared Parameters File
                    {
                        using (File.Create(tempParametersFilename)) { }
                        app.SharedParametersFilename = tempParametersFilename;
                    }
                    definition = app.OpenSharedParameterFile().Groups.Create(parameterGroup.ToString()).Definitions.Create(defOptions) as ExternalDefinition;
                }
                finally
                {
                    // Restore User Shared Parameters File
                    app.SharedParametersFilename = sharedParametersFilename;
                    File.Delete(tempParametersFilename);
                }

                if (overwrite || !doc.ParameterBindings.Contains(definition))
                {
                    // TODO : Ask for categories
                    var categorySet = new CategorySet();
                    foreach (var category in doc.Settings.Categories.Cast <Category>().Where(category => category.AllowsBoundParameters))
                    {
                        categorySet.Insert(category);
                    }

                    var binding = instance ? (ElementBinding) new InstanceBinding(categorySet) : (ElementBinding) new TypeBinding(categorySet);

                    if (!doc.ParameterBindings.Insert(definition, binding, parameterGroup))
                    {
                        throw new InvalidOperationException("Failed while creating the parameter binding.");
                    }
                }

                ReplaceElement(ref element, SharedParameterElement.Lookup(doc, definition.GUID));
            }
        }