Beispiel #1
0
        public static bool AddSharedParameterByDefaulGroupName(Document doc, string sharedParameterFile, string groupName, string parameterName, Category newCategory, bool isInstance, BuiltInParameterGroup parameterGroup)
        {
            doc.Application.SharedParametersFilename = sharedParameterFile;
            DefinitionFile   definitionFile = doc.Application.OpenSharedParameterFile();
            DefinitionGroups groups         = definitionFile.Groups;
            DefinitionGroup  group          = groups.get_Item(groupName);

            if (group == null)
            {
                throw new Exception("没有找到对应的参数组");
            }
            Definition definition = group.Definitions.get_Item(parameterName);

            if (definition == null)
            {
                throw new Exception("没有找到对应的参数");
            }
            ElementBinding binding       = null;
            ElementBinding orientBinding = doc.ParameterBindings.get_Item(definition) as ElementBinding;
            CategorySet    categories    = new CategorySet();;

            if (orientBinding != null)
            {
                foreach (Category c in orientBinding.Categories)
                {
                    categories.Insert(c);
                }
            }
            categories.Insert(newCategory);
            if (isInstance)
            {
                binding = doc.Application.Create.NewInstanceBinding(categories);
            }
            else
            {
                binding = doc.Application.Create.NewTypeBinding(categories);
            }
            doc.ParameterBindings.Remove(definition);
            var result = doc.ParameterBindings.Insert(definition, binding, parameterGroup);

            return(result);
        }
Beispiel #2
0
        public static ExternalDefinition Create_SP(string sp_name
                                                   , ParameterType type, string group_name)
        {
            DefinitionFile deFile = CachedApp.OpenSharedParameterFile();
            // create new group in the shared paramters files
            DefinitionGroups groups       = deFile.Groups;
            bool             founded      = false;
            Definition       myDefinition = groups.First().Definitions.First();

            foreach (DefinitionGroup dg in groups)
            {
                if (dg.Name == group_name)
                {
                    ExternalDefinition exDef = dg.Definitions.get_Item(sp_name) as ExternalDefinition;
                    if (exDef != null)
                    {
                        //exDef.Description
                        return(exDef);
                    }
                    //ExternalDefinition exDef = dg.Definitions.get_Item("CompanyName") as ExternalDefinition;
                    ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(sp_name, type);

                    myDefinition = dg.Definitions.Create(option);

                    founded = true;
                    break;
                }
            }
            if (!founded)
            {
                DefinitionGroup myGroup = groups.Create(group_name);
                // Create a type definition
                ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(sp_name, type);
                myDefinition = myGroup.Definitions.Create(option);
            }

            ExternalDefinition eDef = myDefinition as ExternalDefinition;

            return(eDef);

            //
        }
Beispiel #3
0
        public static void PrepareSharedParameter(Document doc)
        {
            doc.Application.SharedParametersFilename = SharedParameterFile;
            if (!File.Exists(SharedParameterFile))
            {
                var fs = File.Create(SharedParameterFile);
                fs.Close();
            }
            DefinitionFile   definitionFile = doc.Application.OpenSharedParameterFile();
            DefinitionGroups groups         = definitionFile.Groups;
            DefinitionGroup  group          = groups.get_Item(GroupName);

            if (group == null)
            {
                group = definitionFile.Groups.Create(GroupName);
                group.Definitions.Create(new ExternalDefinitionCreationOptions(CustomParameters.监测类型.ToString(), ParameterType.Text));
                group.Definitions.Create(new ExternalDefinitionCreationOptions(CustomParameters.测点编号.ToString(), ParameterType.Text));
                group.Definitions.Create(new ExternalDefinitionCreationOptions(CustomParameters.监测点.ToString(), ParameterType.Text));
            }
        }
Beispiel #4
0
        /// <summary>
        /// Get existed or create a new shared parameters with the given name, group and Revit DB Application.
        /// </summary>
        /// <param name="name">Shared parameter name</param>
        /// <param name="groupName">Shared parameter group name</param>
        /// <param name="revitApp">Revit DB Application</param>
        /// <returns>ExternalDefinition of get or created shared parameter</returns>
        public static ExternalDefinition GetOrCreateDef(string name, string groupName, Application revitApp)
        {
            DefinitionFile parameterFile = GetSharedParameterFile(revitApp);

            DefinitionGroup group = parameterFile.Groups.get_Item(groupName);

            if (group == null)
            {
                group = parameterFile.Groups.Create(groupName);
            }

            ExternalDefinition Bdef = group.Definitions.get_Item(name) as ExternalDefinition;

            if (Bdef == null)
            {
                Bdef = group.Definitions.Create(name, ParameterType.Length) as ExternalDefinition;
            }

            return(Bdef);
        }
        /// <summary>
        /// Get existed or create a new shared parameters with the given name, group and Revit DB Application.
        /// </summary>
        /// <param name="name">Shared parameter name</param>
        /// <param name="groupName">Shared parameter group name</param>
        /// <param name="revitApp">Revit DB Application</param>
        /// <returns>ExternalDefinition of get or created shared parameter</returns>
        public static ExternalDefinition GetOrCreateDef(string name, string groupName, Application revitApp)
        {
            DefinitionFile parameterFile = GetSharedParameterFile(revitApp);

            DefinitionGroup group = parameterFile.Groups.get_Item(groupName);

            if (group == null)
            {
                group = parameterFile.Groups.Create(groupName);
            }

            ExternalDefinition Bdef = group.Definitions.get_Item(name) as ExternalDefinition;

            if (Bdef == null)
            {
                ExternalDefinitionCreationOptions ExternalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(name, SpecTypeId.ReinforcementLength);
                Bdef = group.Definitions.Create(ExternalDefinitionCreationOptions) as ExternalDefinition;
            }

            return(Bdef);
        }
Beispiel #6
0
        private DefinitionGroup GetSharedGroup()
        {
            string sharedParametersFile = this.GetSharedParametersFile();

            this.m_revitApp.SharedParametersFilename = sharedParametersFile;
            DefinitionFile definitionFile = this.m_revitApp.OpenSharedParameterFile();

            if (definitionFile == null)
            {
                return(null);
            }
            DefinitionGroups groups          = definitionFile.Groups;
            DefinitionGroup  definitionGroup = groups.get_Item("RDBParameters");

            if (definitionGroup == null)
            {
                groups.Create("RDBParameters");
                definitionGroup = groups.get_Item("RDBParameters");
            }
            return(definitionGroup);
        }
        /// <summary>
        /// Method to iterate through shared parameters by group
        /// </summary>
        /// <returns></returns>
        public bool GetSharedParameterList()
        {
            if (File.Exists(_sharedFilePath) && null == _sharedFile)
            {
                TaskDialog.Show("Error", "SharedPARAM.txt has an invalid format.");
                return(false);
            }

            DefinitionGroup group = _sharedFile.Groups.get_Item(_groupName);

            if (null == group)
            {
                return(false);
            }

            foreach (Definition definition in group.Definitions)
            {
                _sharedParamNames.Add(definition.Name);
            }
            return(true);
        }
Beispiel #8
0
        public static Definition CreateDefinition(this Param p, Document doc)
        {
            string localname = "CC_SharedParams.txt";
            string FullName  = localname.GetMyDocs();

            if (File.Exists(FullName))
            {
                File.Delete(FullName);
            }

            using (StreamWriter stream = new StreamWriter(FullName))
            {
                stream.Close();
            }

            Application app = doc.Application;

            app.SharedParametersFilename = FullName;
            DefinitionFile df = app.OpenSharedParameterFile();

            if (df.Groups.get_Item(Group) == null)
            {
                DefinitionGroup newgroup = df.Groups.Create(Group);
                if (df.Groups.get_Item(Group).Definitions.get_Item(p.Name) == null)
                {
                    return(newgroup.Definitions.Create(p.CreateOptions()));
                }
                else
                {
                    return(newgroup.Definitions.get_Item(p.Name));
                }
            }
            DefinitionGroup group = df.Groups.get_Item(Group);

            if (df.Groups.get_Item(Group).Definitions.get_Item(p.Name) == null)
            {
                return(group.Definitions.Create(p.CreateOptions()));
            }
            return(group.Definitions.get_Item(p.Name));
        }
Beispiel #9
0
        public static Definition GetOrCreateSharedParamsDefinition(DefinitionGroup defGroup, ParameterType defType, string defName, bool visible)
        {
            ExternalDefinitonCreationOptions options = new ExternalDefinitonCreationOptions(defName, defType);

            options.Visible = visible;

            Definition def = defGroup.Definitions.get_Item(defName);

            if (null == def)
            {
                try
                {
                    def = defGroup.Definitions.Create(options);
                }
                catch (Exception)
                {
                    def = null;
                }
            }

            return def;
        }
Beispiel #10
0
        public bool SetNewParameterToInstanceWall(UIApplication app, DefinitionFile myDefinitionFile)
        {
            if (myDefinitionFile == null)
            {
                throw new Exception("No SharedParameter File!");
            }
            // create a new group in the shared parameters file
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            DefinitionGroup  myGroup  = myGroups.Create("MyParameters1");

            // create an instance definition in definition group MyParameters
            ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions("Instance_ProductDate", ParameterType.Text);

            // Don't let the user modify the value, only the API
            option.UserModifiable = false;
            // Set tooltip
            option.Description = "Wall product date";
            Definition myDefinition_ProductDate = myGroup.Definitions.Create(option);

            // create a category set and insert category of wall to it
            CategorySet myCategories = app.Application.Create.NewCategorySet();
            // use BuiltInCategory to get category of wall
            Category myCategory = Category.GetCategory(app.ActiveUIDocument.Document, BuiltInCategory.OST_Walls);


            myCategories.Insert(myCategory);

            //Create an instance of InstanceBinding
            InstanceBinding instanceBinding = app.Application.Create.NewInstanceBinding(myCategories);

            // Get the BingdingMap of current document.
            BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings;

            // Bind the definitions to the document
            bool instanceBindOK = bindingMap.Insert(myDefinition_ProductDate,
                                                    instanceBinding, BuiltInParameterGroup.PG_TEXT);

            return(instanceBindOK);
        }
Beispiel #11
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 InstanceBinding(categorySet), parameterGroup);

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

            return(result);
        }
Beispiel #12
0
        /// <summary>
        /// Helper to get shared params definition.
        /// </summary>
        public static Definition GetOrCreateSharedParamsDefinition(DefinitionGroup defGroup, ParameterType defType, string defName, bool visible)
        {
            Definition definition = defGroup.Definitions.get_Item(defName);

            if (definition == null)
            {
                try
                {
                    var opt = new ExternalDefinitionCreationOptions(defName, defType)
                    {
                        Visible = visible
                    };

                    definition = defGroup.Definitions.Create(opt);
                }
                catch (Exception)
                {
                    definition = null;
                }
            }

            return(definition);
        }
        public static void AddSetOfSharedParameters(Document doc)
        {
            Application app = doc.Application;

            String filePath = GetRandomSharedParameterFileName();

            app.SharedParametersFilename = filePath;

            DefinitionFile  dFile  = app.OpenSharedParameterFile();
            DefinitionGroup dGroup = dFile.Groups.Create("Demo group");
            List <SharedParameterBindingManager> managers = BuildSharedParametersToCreate();

            using (Transaction t = new Transaction(doc, "Bind parameters"))
            {
                t.Start();
                foreach (SharedParameterBindingManager manager in managers)
                {
                    manager.Definition = dGroup.Definitions.Create(manager.GetCreationOptions());
                    manager.AddBindings(doc);
                }
                t.Commit();
            }
        }
Beispiel #14
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);
        }
Beispiel #15
0
        //Macro Command
        //Creates Shared Parameters (Hard Coded) into external shared parameter file. Note: Should match Excel file headers
        //TODO: Read parameters from columns created in Excel file, future update
        public void B_CreateFeederSharedParameters()
        {
            //Name Constants
            //**will get this from a database later
            const string kSharedParamsGroup = "FD_Conduit_Feeders";
            const string kSharedParamsDefA  = "FD_FEEDER DESIGNATOR";
            const string kSharedParamsDefB  = "FD_SCH 40 PVC";
            const string kSharedParamsDefC  = "FD_CONDUCTOR(S)";
            const string kSharedParamsDefD  = "FD_GROUND";
            const string kSharedParamsDefE  = "FD_FROM";
            const string kSharedParamsDefF  = "FD_TO";

            UIApplication uiapp = this.Application;

            DefinitionFile defFile = uiapp.Application.OpenSharedParameterFile();

            if (defFile == null)
            {
                TaskDialog.Show("Error, no Shared Parameter File!",
                                "You need to create shared parameter file in project directory first, yo!");
                return;
            }

            //create a group
            DefinitionGroup sharedParamsGroup = GetOrCreateSharedParamsGroup(defFile, kSharedParamsGroup);

            //create parameters
            GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Text, kSharedParamsDefA);
            GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Text, kSharedParamsDefB);
            GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Text, kSharedParamsDefC);
            GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Text, kSharedParamsDefD);
            GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Text, kSharedParamsDefE);
            GetOrCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Text, kSharedParamsDefF);

            ShowDefinitionFileInfo(defFile);
        }
Beispiel #16
0
        /// <summary>
        /// Submit RebarShapeDefinition. All the parameters and constraints
        /// will be added to RebarShape. The RebarShape will be added to Revit document after
        /// successfully submitted.
        /// </summary>
        /// <param name="defGroup">Parameter definition group</param>
        public void Commit(Document rvtDoc, DefinitionGroup defGroup)
        {
            // Submit all the parameters.
            foreach (RebarShapeParameter param in m_parameters)
            {
                param.Commit(rvtDoc, defGroup);
            }

            // Submit all the constraints.
            foreach (ConstraintOnRebarShape constraint in m_constraints)
            {
                constraint.Commit();
            }

            // Submit the RebarShape.
            if (m_rebarshapeDefinition.Complete)
            {
                m_rebarshapeDefinition.CheckDefaultParameterValues(0, 0);
            }
            else
            {
                throw new Exception("The Rebar shape definition is not completed.");
            }
        }
Beispiel #17
0
        FindGUID(ref Guid paramGuid)
        {
            DefinitionFile sharedParamFile = null;

            try {
                sharedParamFile = OpenSharedParamFile();
                DefinitionGroup group = sharedParamFile.Groups.get_Item(m_paramGroupName);
                if (group != null)
                {
                    Definition definition = group.Definitions.get_Item(m_fireRatingParamName);
                    if (definition != null)
                    {
                        ExternalDefinition externalDefinition = (ExternalDefinition)definition;
                        paramGuid = externalDefinition.GUID;
                        return(true);
                    }
                }

                return(false);
            }
            catch (Exception) {
                return(false);
            }
        }
        public static ExternalDefinition AddParameterToDefFile(DefinitionFile defFile, string groupName, MyProjectSharedParameter myparam)
        {
            DefinitionGroup        tempGroup = null;
            List <DefinitionGroup> groups    = defFile.Groups.Where(i => i.Name == groupName).ToList();

            if (groups.Count == 0)
            {
                try
                {
                    tempGroup = defFile.Groups.Create(groupName);
                }
                catch (Exception ex)
                {
                    throw new Exception("Не удалось создать группу " + groupName + " в файле общих параметров " + defFile.Filename);
                }
            }
            else
            {
                tempGroup = groups.First();
            }


            Definitions defs = tempGroup.Definitions;
            ExternalDefinitionCreationOptions defOptions =
                new ExternalDefinitionCreationOptions(myparam.Name, myparam.def.ParameterType);

            defOptions.GUID = myparam.guid;

            ExternalDefinition exDef = defs.Create(defOptions) as ExternalDefinition;

            if (exDef == null)
            {
                throw new Exception("Не удалось создать общий параметр " + myparam.Name);
            }
            return(exDef);
        }
Beispiel #19
0
 /// <summary>
 /// Yield the Parameter.
 /// </summary>
 /// <param name="defGroup">Definition group</param>
 public abstract void Commit(Autodesk.Revit.DB.Document doc, DefinitionGroup defGroup);
Beispiel #20
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);
        }
Beispiel #21
0
        /// <summary>
        /// Get a external definition if there exists one, otherwise create a new one.
        /// </summary>
        /// <param name="group">Definition group</param>
        /// <returns>External definition</returns>
        protected ExternalDefinition GetOrCreateDef(DefinitionGroup group)
        {
            ExternalDefinition Bdef =
                group.Definitions.get_Item(m_name) as ExternalDefinition;

            if(Bdef == null)
                Bdef = group.
                    Definitions.Create(m_name, ParameterType.Length) as ExternalDefinition;

            return Bdef;
        }
    public static Definition GetOrCreateSharedParamsDefinition(
      DefinitionGroup defGroup,
      ParameterType defType,
      string defName,
      bool visible)
    {
      Definition definition = defGroup.Definitions.get_Item(defName);
      if (null == definition)
      {
        try
        {
          //definition = defGroup.Definitions.Create(defName, defType, visible);
          
          // 'Autodesk.Revit.DB.Definitions.Create(string, Autodesk.Revit.DB.ParameterType, bool)' is obsolete: 
          // 'This method is deprecated in Revit 2015. Use Create(Autodesk.Revit.DB.ExternalDefinitonCreationOptions) instead'
	
          // Modified code for Revit 2015

          ExternalDefinitonCreationOptions extDefCrOptns = new ExternalDefinitonCreationOptions(defName, defType);
          extDefCrOptns.Visible = true;
          definition = defGroup.Definitions.Create(extDefCrOptns);

        }
        catch (Exception)
        {
          definition = null;
        }
      }
      return definition;
    }
        CollectEvent(object sender, CollectorEventArgs e)
        {
            // cast the sender object to the SnoopCollector we are expecting
            Collector snoopCollector = sender as Collector;

            if (snoopCollector == null)
            {
                Debug.Assert(false);    // why did someone else send us the message?
                return;
            }

            // see if it is a type we are responsible for
            Parameter param = e.ObjToSnoop as Parameter;

            if (param != null)
            {
                Stream(snoopCollector.Data(), param);
                return;
            }

            Definition paramDef = e.ObjToSnoop as Definition;

            if (paramDef != null)
            {
                Stream(snoopCollector.Data(), paramDef);
                return;
            }

            DefinitionGroup defGroup = e.ObjToSnoop as DefinitionGroup;

            if (defGroup != null)
            {
                Stream(snoopCollector.Data(), defGroup);
                return;
            }

            DefinitionFile defFile = e.ObjToSnoop as DefinitionFile;

            if (defFile != null)
            {
                Stream(snoopCollector.Data(), defFile);
                return;
            }

            Binding binding = e.ObjToSnoop as Binding;

            if (binding != null)
            {
                Stream(snoopCollector.Data(), binding);
                return;
            }

            ElementBinding elemBind = e.ObjToSnoop as ElementBinding;

            if (elemBind != null)
            {
                Stream(snoopCollector.Data(), elemBind);
                return;
            }

            // no more in 2011?
            //ParameterListItem paramListItem = e.ObjToSnoop as ParameterListItem;
            //if (paramListItem != null) {
            //    Stream(snoopCollector.Data(), paramListItem);
            //    return;
            //}
        }
Beispiel #24
0
 public Definitions GetParametersDefinitionByGrup(DefinitionGroup paramGroup)
 {
     return(paramGroup.Definitions);
 }
Beispiel #25
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);
        }
Beispiel #26
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            if (doc.IsFamilyDocument)
            {
                message = "This command can only be used in a project, not in a family file.";
                return(Result.Failed);
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Create per doc Parameters");
                // get the current shared params definition file
                DefinitionFile sharedParamsFile = LabUtils.GetSharedParamsFile(app.Application);
                if (null == sharedParamsFile)
                {
                    message = "Error getting the shared params file.";
                    return(Result.Failed);
                }
                // get or create the shared params group
                DefinitionGroup sharedParamsGroup = LabUtils.GetOrCreateSharedParamsGroup(
                    sharedParamsFile, LabConstants.ParamGroupName);

                if (null == sharedParamsGroup)
                {
                    message = "Error getting the shared params group.";
                    return(Result.Failed);
                }
                // visible param
                Definition docParamDefVisible = LabUtils.GetOrCreateSharedParamsDefinition(
                    sharedParamsGroup, ParameterType.Integer, LabConstants.ParamNameVisible, true);

                if (null == docParamDefVisible)
                {
                    message = "Error creating visible per-doc parameter.";
                    return(Result.Failed);
                }
                // invisible param
                Definition docParamDefInvisible = LabUtils.GetOrCreateSharedParamsDefinition(
                    sharedParamsGroup, ParameterType.Integer, LabConstants.ParamNameInvisible, false);

                if (null == docParamDefInvisible)
                {
                    message = "Error creating invisible per-doc parameter.";
                    return(Result.Failed);
                }
                // bind the param
                try
                {
                    CategorySet catSet = app.Application.Create.NewCategorySet();

                    catSet.Insert(doc.Settings.Categories.get_Item(
                                      BuiltInCategory.OST_ProjectInformation));

                    Binding binding = app.Application.Create.NewInstanceBinding(catSet);
                    doc.ParameterBindings.Insert(docParamDefVisible, binding);
                    doc.ParameterBindings.Insert(docParamDefInvisible, binding);
                }
                catch (Exception e)
                {
                    message = "Error binding shared parameter: " + e.Message;
                    return(Result.Failed);
                }
                // set the initial values
                // get the singleton project info element
                Element projInfoElem = LabUtils.GetProjectInfoElem(doc);

                if (null == projInfoElem)
                {
                    message = "No project info element found. Aborting command...";
                    return(Result.Failed);
                }

                // For simplicity, access params by name rather than by GUID
                // and simply the first best one found under that name:

                projInfoElem.LookupParameter(LabConstants.ParamNameVisible).Set(55);
                projInfoElem.LookupParameter(LabConstants.ParamNameInvisible).Set(0);

                tx.Commit();
            }
            return(Result.Succeeded);
        }
Beispiel #27
0
        private void Stream(ArrayList data, DefinitionGroup defGroup)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(DefinitionGroup)));

            data.Add(new Snoop.Data.String("Name", defGroup.Name));
            data.Add(new Snoop.Data.Enumerable("Definitions", defGroup.Definitions));
        }
        /// <summary>
        /// Helper to get shared params definition.
        /// </summary>
        public static Definition GetOrCreateSharedParamsDefinition(
            DefinitionGroup defGroup,
            ParameterType defType,
            string defName,
            bool visible)
        {
            Definition definition
            = defGroup.Definitions.get_Item(
              defName );

              if( null == definition )
              {
            try
            {
              //definition = defGroup.Definitions.Create( defName, defType, visible ); // 2014

              ExternalDefinitionCreationOptions opt
            = new ExternalDefinitionCreationOptions(
              defName, defType ); // 2015

              opt.Visible = visible;

              definition = defGroup.Definitions.Create( opt ); // 2015
            }
            catch( Exception )
            {
              definition = null;
            }
              }
              return definition;
        }
Beispiel #29
0
 /// <summary>
 /// Yield the Parameter.
 /// </summary>
 /// <param name="defGroup">Definition group</param>
 public abstract void Commit(Autodesk.Revit.DB.Document doc, DefinitionGroup defGroup);
        static Definition CreateNewDefinition(
            DefinitionGroup group,
            string parameter_name,
            ParameterType parameter_type)
        {
            //return group.Definitions.Create(
              //  parameter_name, parameter_type, true ); // 2014

              //return group.Definitions.Create(
              //  new ExternalDefinitonCreationOptions(
              //    parameter_name, parameter_type ) ); // 2015

              return group.Definitions.Create(
            new ExternalDefinitionCreationOptions(
              parameter_name, parameter_type ) ); // 2016
        }
        /// <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);
        }
        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);
            }
        }
 private Definition OpenDefinition(string parameterName, ParameterType parameterType, DefinitionGroup definitionGroup)
 {
     var definition = definitionGroup.Definitions.get_Item(parameterName)
                          ?? definitionGroup.Definitions.Create(parameterName, parameterType, true);
     return definition;
 }
Beispiel #34
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);
        }
 /// <summary>
 /// Add a formula parameter to RebarShapeDefinition.
 /// </summary>
 /// <param name="defGroup">Definition group</param>
 public override void Commit(Autodesk.Revit.DB.Document doc, DefinitionGroup defGroup)
 {
     ExternalDefinition def = GetOrCreateDef(defGroup);
     m_parameterId = Autodesk.Revit.DB.Structure.RebarShapeParameters.GetOrCreateElementIdForExternalDefinition(doc, def);
     m_rebarShapeDef.RebarshapeDefinition.AddFormulaParameter(m_parameterId, m_formula);
 }
        /// <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);
        }
Beispiel #37
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);
        }
        /***************************************************/
        /****              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);
        }
Beispiel #39
0
        /// <summary>
        /// Submit RebarShapeDefinition. All the parameters and constraints
        /// will be added to RebarShape. The RebarShape will be added to Revit document after 
        /// successfully submitted.
        /// </summary>
        /// <param name="defGroup">Parameter definition group</param>
        public void Commit(Document rvtDoc, DefinitionGroup defGroup)
        {
            // Submit all the parameters.
            foreach (RebarShapeParameter param in m_parameters)
            {
                param.Commit(rvtDoc, defGroup);
            }

            // Submit all the constraints.
            foreach (ConstraintOnRebarShape constraint in m_constraints)
            {
                constraint.Commit();
            }

            // Submit the RebarShape.
            if (m_rebarshapeDefinition.Complete)
            {
                m_rebarshapeDefinition.CheckDefaultParameterValues(0, 0);
            }
            else
            {
                throw new Exception("The Rebar shape definition is not completed.");
            }
        }
Beispiel #40
0
 /// <summary>
 /// Add a formula parameter to RebarShapeDefinition.
 /// </summary>
 /// <param name="defGroup">Definition group</param>
 public override void Commit(Autodesk.Revit.DB.Document doc, DefinitionGroup defGroup)
 {
     ExternalDefinition def = GetOrCreateDef(defGroup);
     m_parameterId = Autodesk.Revit.DB.Structure.RebarShapeParameters.GetOrCreateElementIdForExternalDefinition(doc, def);
     m_rebarShapeDef.RebarshapeDefinition.AddFormulaParameter(m_parameterId, m_formula);                
 }
 /// <summary>
 /// Create a new shared parameter definition 
 /// in the specified grpup.
 /// </summary>
 static Definition CreateNewDefinition(
     DefinitionGroup group,
     string parameter_name,
     ParameterType parameter_type)
 {
     return group.Definitions.Create(
     new ExternalDefinitionCreationOptions(
       parameter_name, parameter_type ) );
 }