// add one type (version 1)
        //
        void addType(string name, double w, double d)
        {
            // get the family manager from the current doc
              FamilyManager pFamilyMgr = _doc.FamilyManager;

              // add new types with the given name
              //
              FamilyType type1 = pFamilyMgr.NewType(name);

              // look for 'Width' and 'Depth' parameters and set them to the given value
              //
              // first 'Width'
              //
              FamilyParameter paramW = pFamilyMgr.get_Parameter("Width");
              double valW = mmToFeet(w);
              if (paramW != null)
              {
            pFamilyMgr.Set(paramW, valW);
              }

              // same idea for 'Depth'
              //
              FamilyParameter paramD = pFamilyMgr.get_Parameter("Depth");
              double valD = mmToFeet(d);
              if (paramD != null)
              {
            pFamilyMgr.Set(paramD, valD);
              }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the value of a family parameter of the current family type, this applies to all family parameters (instance and type).
        /// </summary>
        /// <param name="parameterName">A family parameter of the current type.</param>
        /// <param name="familyTypeName">The name of the family type.</param>
        /// <returns>The parameter value.</returns>
        public object GetParameterValueByName(string familyTypeName, string parameterName)
        {
            Autodesk.Revit.DB.FamilyParameter familyParameter = FamilyManager.get_Parameter(parameterName);
            if (familyParameter == null)
            {
                throw new InvalidOperationException(Properties.Resources.ParameterNotFound);
            }

            TransactionManager.Instance.EnsureInTransaction(this.InternalFamilyDocument);
            SetFamilyDocumentCurrentType(familyTypeName);
            TransactionManager.Instance.TransactionTaskDone();

            switch (familyParameter.StorageType)
            {
            case Autodesk.Revit.DB.StorageType.Integer:
                return(FamilyManager.CurrentType.AsInteger(familyParameter) * UnitConverter.HostToDynamoFactor(familyParameter.Definition.GetSpecTypeId()));

            case Autodesk.Revit.DB.StorageType.Double:
                return(FamilyManager.CurrentType.AsDouble(familyParameter) * UnitConverter.HostToDynamoFactor(familyParameter.Definition.GetSpecTypeId()));

            case Autodesk.Revit.DB.StorageType.String:
                return(FamilyManager.CurrentType.AsString(familyParameter));

            case Autodesk.Revit.DB.StorageType.ElementId:
                Elements.Element element = ElementSelector.ByElementId(FamilyManager.CurrentType.AsElementId(familyParameter).IntegerValue);
                return(element);

            default:
                return(null);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Set the value of a family parameter of the current family type, this applies to all family parameters (instance and type).
        /// </summary>
        /// <param name="familyTypeName">The name of Family Type</param>
        /// <param name="parameter">A family parameter of the current type.</param>
        /// <param name="value">The new value for the family parameter.</param>
        /// <returns>The family document with an updated value for the specified parameter.</returns>
        public FamilyDocument SetParameterValueByName(string familyTypeName, string parameter, object value)
        {
            TransactionManager.Instance.EnsureInTransaction(this.InternalDocument);
            Autodesk.Revit.DB.FamilyParameter familyParameter = FamilyManager.get_Parameter(parameter);
            if (familyParameter == null)
            {
                throw new InvalidOperationException(Properties.Resources.ParameterNotFound);
            }

            SetFamilyDocumentCurrentType(familyTypeName);

            switch (familyParameter.StorageType)
            {
            case Autodesk.Revit.DB.StorageType.Integer:
                SetIntValue(value, familyParameter);
                break;

            case Autodesk.Revit.DB.StorageType.Double:
                SetDoubleValue(value, familyParameter);
                break;

            case Autodesk.Revit.DB.StorageType.String:
                SetStringValue(value, familyParameter);
                break;

            case Autodesk.Revit.DB.StorageType.ElementId:
                SetElementIdValue(value, familyParameter);
                break;

            default:
                break;
            }
            TransactionManager.Instance.TransactionTaskDone();
            return(this);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// load shared parameters from shared parameter file and add them to family
        /// </summary>
        /// <returns>
        /// if succeeded, return true; otherwise false
        /// </returns>
        private bool AddSharedParameter()
        {
            if (File.Exists(m_sharedFilePath) &&
                null == m_sharedFile)
            {
                MessageManager.MessageBuff.AppendLine("SharedParameter.txt has an invalid format.");
                return(false);
            }

            foreach (DefinitionGroup group in m_sharedFile.Groups)
            {
                foreach (ExternalDefinition def in group.Definitions)
                {
                    // check whether the parameter already exists in the document
                    FamilyParameter param = m_manager.get_Parameter(def.Name);
                    if (null != param)
                    {
                        continue;
                    }

                    try
                    {
                        m_manager.AddParameter(def, def.ParameterGroup, true);
                    }
                    catch (System.Exception e)
                    {
                        MessageManager.MessageBuff.AppendLine(e.Message);
                        return(false);
                    }
                }
            }

            return(true);
        }
        // ======================================
        //   (4.1) add formula
        // ======================================
        public void addFormulas()
        {
            // we will add the following fomulas
              //   Tw = Width / 4.0
              //   Td = Depth / 4.0
              //

              // first get the parameter
              FamilyManager pFamilyMgr = _doc.FamilyManager;

              FamilyParameter paramTw = pFamilyMgr.get_Parameter("Tw");
              FamilyParameter paramTd = pFamilyMgr.get_Parameter("Td");

              // set the formula
              pFamilyMgr.SetFormula(paramTw, "Width / 4.0");
              pFamilyMgr.SetFormula(paramTd, "Depth / 4.0");
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Executes on type to instance change
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        private void ExecuteParameterChange(UIApplication uiapp, String text, List <string> values, string type)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message =
                    "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Type To Instance"))
                {
                    tg.Start();
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(true);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);
                        // Since we'll modify the document, we need a transaction
                        // It's best if a transaction is scoped by a 'using' block
                        // The name of the transaction was given as an argument
                        if (trans.Start(text) == TransactionStatus.Started)
                        {
                            FamilyManager mgr = doc.FamilyManager;
                            foreach (var value in values)
                            {
                                FamilyParameter fp = mgr.get_Parameter(value);
                                if (fp.IsInstance)
                                {
                                    mgr.MakeType(fp);
                                }
                                else
                                {
                                    mgr.MakeInstance(fp);
                                };
                            }
                        }
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            if (EncounteredError != null)
                            {
                                EncounteredError(this, null);
                            }
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
Ejemplo n.º 7
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication rvtUIAPP = commandData.Application;
            UIDocument    uidoc    = rvtUIAPP.ActiveUIDocument;
            Configuration config   = ConfigurationManager.OpenExeConfiguration
                                         (System.Reflection.Assembly.GetExecutingAssembly().Location);
            string familyRepo = config.AppSettings.Settings["Family_repo_folder"].Value;
            string serverAPI  = config.AppSettings.Settings["Server_API"].Value;

            m_rvtDoc = uidoc.Document;
            m_rvtApp = rvtUIAPP.Application;
            try
            {
                string[] filePaths = Directory.GetFiles(@familyRepo, "*.rfa");
                foreach (string path in filePaths)
                {
                    Document doc = m_rvtApp.OpenDocumentFile(path);
                    if (doc.IsFamilyDocument)
                    {
                        try {
                            Family          f       = doc.OwnerFamily;
                            FamilyManager   manager = doc.FamilyManager;
                            FamilyParameter keynote = null;

                            String note = HttpGET(serverAPI + "GetFamilyKeynote?path=" + path);
                            keynote = manager.get_Parameter(BuiltInParameter.KEYNOTE_PARAM);
                            if (keynote != null)
                            {
                                using (Transaction trans = new Transaction(doc, "SET_PARAM"))
                                {
                                    trans.Start();
                                    if (manager.Types.Size == 0)
                                    {
                                        manager.NewType("Type 1");
                                    }
                                    manager.SetFormula(keynote, null);
                                    manager.Set(keynote, note);
                                    trans.Commit();
                                }
                                doc.Save();
                            }
                        }
                        catch (Exception e)
                        {
                            TaskDialog.Show("Error2", e.Message);
                        }
                    }
                }

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the formula of a family parameter.
        /// </summary>
        /// <param name="parameterName">The family parameter.</param>
        /// <returns>The family parameter formula.</returns>
        public string GetFormula(string parameterName)
        {
            Autodesk.Revit.DB.FamilyParameter familyParameter = FamilyManager.get_Parameter(parameterName);
            if (familyParameter == null)
            {
                throw new InvalidOperationException(Properties.Resources.ParameterNotFound);
            }

            return(familyParameter.Formula);
        }
        /// <summary>
        /// Restore all values
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, List <Tuple <string, string, double> > values)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message = "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Change"))
                {
                    tg.Start();
                    foreach (var value in values)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                            FailureHandler         failureHandler         = new FailureHandler();
                            failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                            failureHandlingOptions.SetClearAfterRollback(true);
                            trans.SetFailureHandlingOptions(failureHandlingOptions);

                            FamilyManager   mgr = doc.FamilyManager;
                            FamilyParameter fp  = mgr.get_Parameter(value.Item1);
                            // Since we'll modify the document, we need a transaction
                            // It's best if a transaction is scoped by a 'using' block
                            // The name of the transaction was given as an argument
                            if (trans.Start(text) == TransactionStatus.Started)
                            {
                                mgr.Set(fp, value.Item3);
                                //operation(mgr, fp);
                                doc.Regenerate();
                                if (!value.Item1.Equals(value.Item2))
                                {
                                    mgr.RenameParameter(fp, value.Item2);
                                }
                                trans.Commit();
                                uidoc.RefreshActiveView();
                            }
                            if (failureHandler.ErrorMessage != "")
                            {
                                RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage));
                            }
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
        /// <summary>
        /// Delete parameter
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, List <string> values)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message =
                    "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Delete"))
                {
                    tg.Start();
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(true);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);
                        // Since we'll modify the document, we need a transaction
                        // It's best if a transaction is scoped by a 'using' block
                        // The name of the transaction was given as an argument
                        if (trans.Start(text) == TransactionStatus.Started)
                        {
                            FamilyManager mgr = doc.FamilyManager;
                            foreach (var value in values)
                            {
                                FamilyParameter fp = mgr.get_Parameter(value);
                                mgr.RemoveParameter(fp);
                            }
                        }
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            RequestError.ErrorLog.Add(new Message("", failureHandler.ErrorMessage));
                        }
                        else
                        {
                            RequestError.NotifyLog += $"Successfully purged {values.Count.ToString()} unused parameters.";
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Set the formula of a family parameter (syntax is exactly as Revit, whatever works in Revit's formulas works here).
        /// </summary>
        /// <param name="parameterName">The family parameter.</param>
        /// <param name="formula">The formula string.</param>
        /// <returns>The document family</returns>
        public FamilyDocument SetFormula(string parameterName, string formula)
        {
            Autodesk.Revit.DB.FamilyParameter familyParameter = FamilyManager.get_Parameter(parameterName);
            if (familyParameter == null)
            {
                throw new InvalidOperationException(Properties.Resources.ParameterNotFound);
            }

            TransactionManager.Instance.EnsureInTransaction(this.InternalDocument);
            FamilyManager.SetFormula(familyParameter, formula);
            TransactionManager.Instance.TransactionTaskDone();
            return(this);
        }
Ejemplo n.º 12
0
        public FamilySymbol CreatNewSymbol(Document doc, Family doorfamily, int doorwidth, int doorheight, string str)
        {
            Document      familydoc     = doc.EditFamily(doorfamily);
            FamilyManager familymanager = familydoc.FamilyManager;
            string        symbolname    = str;

            using (Transaction creatnewsymbol = new Transaction(familydoc))
            {
                creatnewsymbol.Start("新建族类型");
                FamilyType      familytype  = familymanager.NewType(symbolname);
                FamilyParameter para_width  = familymanager.get_Parameter(BuiltInParameter.DOOR_WIDTH);
                FamilyParameter para_height = familymanager.get_Parameter(BuiltInParameter.GENERIC_HEIGHT);
                familymanager.Set(para_width, doorwidth / 304.8);
                familymanager.Set(para_height, doorheight / 304.8);
                creatnewsymbol.Commit();
            }
            LoadOptions loadoptions = new LoadOptions();

            doorfamily = familydoc.LoadFamily(doc, loadoptions);
            FamilySymbol newsymbol = null;

            using (Transaction activesymbol = new Transaction(doc))
            {
                activesymbol.Start("激活族类型");
                ISet <ElementId> idstmp = doorfamily.GetFamilySymbolIds();
                foreach (ElementId id in idstmp)
                {
                    FamilySymbol symbol = doc.GetElement(id) as FamilySymbol;
                    if (symbol.Name.Equals(symbolname))
                    {
                        symbol.Activate();
                        newsymbol = symbol;
                    }
                }
                activesymbol.Commit();
            }

            return(newsymbol);
        }
Ejemplo n.º 13
0
        void modifyFamilyParamValue()
        {
            FamilyManager mgr = _doc.FamilyManager;

            FamilyParameter[] a = new FamilyParameter[] {
                mgr.get_Parameter("Width"),
                mgr.get_Parameter("Depth")
            };

            foreach (FamilyType t in mgr.Types)
            {
                mgr.CurrentType = t;
                foreach (FamilyParameter fp in a)
                {
                    if (t.HasValue(fp))
                    {
                        double x = (double)t.AsDouble(fp);
                        mgr.Set(fp, 2.0 * x);
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public void MakeNewFamilyType(Document familyDoc, int D1, int L1)
        {
            FamilyManager familyManager = familyDoc.FamilyManager;

            using (Transaction newFamilyTypeTransaction = new Transaction(familyDoc, "Add Type to Family")) {
                int changesMade = 0;
                newFamilyTypeTransaction.Start();

                FamilyType newFamilyType = familyManager.NewType("60 X 100");

                if (newFamilyType != null)
                {
                    FamilyParameter familyParam = familyManager.get_Parameter("D 1");
                    if (null != familyParam)
                    {
                        familyManager.Set(familyParam, D1);
                        changesMade += 1;
                    }

                    familyParam = familyManager.get_Parameter("L 1");
                    if (null != familyParam)
                    {
                        familyManager.Set(familyParam, L1);
                        changesMade += 1;
                    }
                }

                if (2 == changesMade)
                {
                    newFamilyTypeTransaction.Commit();
                }
                else
                {
                    newFamilyTypeTransaction.RollBack();
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Remove an existing family parameter from the family.
        /// </summary>
        /// <param name="parameterName">The family parameter name.</param>
        /// <returns>The id of the deleted family parameter.</returns>
        public int DeleteParameter(string parameterName)
        {
            Autodesk.Revit.DB.FamilyParameter familyParameter = FamilyManager.get_Parameter(parameterName);
            if (familyParameter == null)
            {
                throw new InvalidOperationException(Properties.Resources.ParameterNotFound);
            }

            int parameterId = familyParameter.Id.IntegerValue;

            TransactionManager.Instance.EnsureInTransaction(this.InternalDocument);
            FamilyManager.RemoveParameter(familyParameter);
            TransactionManager.Instance.TransactionTaskDone();
            return(parameterId);
        }
Ejemplo n.º 16
0
        private bool AddSharedParameter()
        {
            // check to make sure that the file still exists and is valid
            if (File.Exists(_sharedFilePath) && null == _sharedFile)
            {
                TaskDialog.Show("Error", "SharedPARAM.txt has an invalid format.");
                return(false);
            }

            // get the Areas group from shared param file
            DefinitionGroup group = _sharedFile.Groups.get_Item(_groupName);

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

            // get the definition named Program Area
            ExternalDefinition def = group.Definitions.get_Item(_paramName) as ExternalDefinition;

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

            // check whether the parameter already exists in the document
            FamilyParameter param = _manager.get_Parameter(def.Name);

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

            try
            {
                // add that parameter to the current family document
                _manager.AddParameter(def, def.ParameterGroup, true);
            }
            catch (System.Exception e)
            {
                TaskDialog.Show("Error", e.Message);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Change Parameter
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, Tuple <string, double> value)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message = "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (Transaction trans = new Transaction(uidoc.Document, "Change Parameter Value"))
                {
                    FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                    FailureHandler         failureHandler         = new FailureHandler();
                    failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                    failureHandlingOptions.SetClearAfterRollback(true);
                    trans.SetFailureHandlingOptions(failureHandlingOptions);

                    FamilyManager   mgr = doc.FamilyManager;
                    FamilyParameter fp  = mgr.get_Parameter(value.Item1);
                    // Since we'll modify the document, we need a transaction
                    // It's best if a transaction is scoped by a 'using' block
                    // The name of the transaction was given as an argument
                    if (trans.Start(text) == TransactionStatus.Started)
                    {
                        if (fp.IsDeterminedByFormula || fp.IsReporting)
                        {
                            trans.RollBack();  //Cannot change parameters driven by formulas, cannot change reporting parameters
                            return;
                        }

                        mgr.Set(fp, value.Item2);
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage));
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Working sample code for
        /// http://forums.autodesk.com/t5/revit-api/family-types-amp-shared-parameter-values/m-p/6218767
        /// </summary>
        void SetFamilyParameterValueWorks(
            Document doc,
            string paramNameToAmend)
        {
            FamilyManager   mgr = doc.FamilyManager;
            FamilyParameter familyParam
                = mgr.get_Parameter(paramNameToAmend);

            if (familyParam != null)
            {
                foreach (FamilyType familyType in mgr.Types)
                {
                    Debug.Print(familyType.Name);
                    mgr.CurrentType = familyType;
                    mgr.Set(familyParam, 2);
                }
            }
        }
        /// <summary>
        /// Non-working sample code for
        /// http://forums.autodesk.com/t5/revit-api/family-types-amp-shared-parameter-values/m-p/6218767
        /// </summary>
        void SetFamilyParameterValueFails(
            Document doc,
            string paramNameToAmend)
        {
            FamilyManager         mgr         = doc.FamilyManager;
            FamilyTypeSet         familyTypes = mgr.Types;
            FamilyTypeSetIterator familyTypeItor
                = familyTypes.ForwardIterator();

            familyTypeItor.Reset();
            while (familyTypeItor.MoveNext())
            {
                FamilyParameter familyParam
                    = mgr.get_Parameter(paramNameToAmend);

                if (familyParam != null)
                {
                    FamilyType familyType = familyTypeItor.Current as FamilyType;
                    Debug.Print(familyType.Name);
                    mgr.Set(familyParam, 2);
                }
            }
        }
Ejemplo n.º 20
0
        public void ProduceProfile(ref Document doc, ref List <string> vs, ref List <string> pv)
        {
            using (Transaction t = new Transaction(doc, "make profile xn * yn"))
            {
                t.Start();
                FamilyManager familyManager = doc.FamilyManager;

                for (int i = 0; i != vs.Count; i++)
                {
                    FamilyParameter familyParameter = familyManager.get_Parameter(vs[i]);
                    try
                    {
                        familyManager.SetValueString(familyParameter, pv[i]);
                    }
                    catch
                    {
                        familyManager.Set(familyParameter, int.Parse(pv[i]));
                    }
                }


                t.Commit();
            }
        }
Ejemplo n.º 21
0
        public bool BindSharedParameters()
        {
            if (File.Exists(m_sharedFilePath) &&
                null == m_sharedFile)
            {
                MessageBox.Show("SharedParameter.txt has an invalid format.");
                return(false);
            }

            foreach (DefinitionGroup group in m_sharedFile.Groups)
            {
                foreach (ExternalDefinition def in group.Definitions)
                {
                    // check whether the parameter already exists in the document
                    FamilyParameter param = m_manager.get_Parameter(def.Name);
                    if (null != param)
                    {
                        continue;
                    }

                    BuiltInParameterGroup bpg = BuiltInParameterGroup.INVALID;
                    try
                    {
                        if (def.OwnerGroup.Name == "Dimensions")
                        {
                            bpg = BuiltInParameterGroup.PG_GEOMETRY;
                        }
                        else if (def.OwnerGroup.Name == "Electrical")
                        {
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL;
                        }
                        else if (def.OwnerGroup.Name == "Identity Data")
                        {
                            bpg = BuiltInParameterGroup.PG_IDENTITY_DATA;
                        }
                        else if (def.OwnerGroup.Name == "Electrical - Loads")
                        {
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL_LOADS;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical - Air Flow")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_AIRFLOW;
                        }
                        else if (def.OwnerGroup.Name == "Energy Analysis")
                        {
                            bpg = BuiltInParameterGroup.PG_ENERGY_ANALYSIS;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical - Loads")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_LOADS;
                        }
                        else if (def.OwnerGroup.Name == "Structural")
                        {
                            bpg = BuiltInParameterGroup.PG_STRUCTURAL;
                        }
                        else if (def.OwnerGroup.Name == "Plumbing")
                        {
                            bpg = BuiltInParameterGroup.PG_PLUMBING;
                        }
                        else if (def.OwnerGroup.Name == "Green Building Properties")
                        {
                            bpg = BuiltInParameterGroup.PG_GREEN_BUILDING;
                        }
                        else if (def.OwnerGroup.Name == "Materials and Finishes")
                        {
                            bpg = BuiltInParameterGroup.PG_MATERIALS;
                        }
                        else if (def.OwnerGroup.Name == "Other")
                        {
                            bpg = BuiltInParameterGroup.INVALID;
                        }
                        else if (def.OwnerGroup.Name == "Construction")
                        {
                            bpg = BuiltInParameterGroup.PG_CONSTRUCTION;
                        }
                        else
                        {
                            bpg = BuiltInParameterGroup.INVALID;
                        }

                        m_manager.AddParameter(def, bpg, false);
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 22
0
        public FamilyHelper(ExternalCommandData commandData)
        {
            InitializeComponent();
            this.DataContext = this;
            InitializeCommand();

            cdata = commandData;
            uiapp = commandData.Application;
            uidoc = uiapp.ActiveUIDocument;
            doc   = uidoc.Document;

            FamilyManager fm = doc.FamilyManager;

            CurrentSharedParamFile  = uiapp.Application.OpenSharedParameterFile();
            CurrentDefinitionGroups = CurrentSharedParamFile.Groups.ToList();
            #region 铝型材纠错
            var p1 = fm.get_Parameter("米重");
            var p2 = fm.get_Parameter("模图编号");

            double?v1 = 0;
            string v2 = "";
            if (p1 != null && p2 != null)
            {
                if (!p1.IsShared && !p2.IsShared)
                {
                    using (Transaction trans = new Transaction(doc, "CreateFamilyParameters"))
                    {
                        trans.Start();
                        foreach (FamilyType ft in fm.Types)
                        {
                            if (ft.HasValue(p1))
                            {
                                v1 = ft.AsDouble(p1);
                            }
                            if (ft.HasValue(p2))
                            {
                                v2 = ft.AsString(p2);
                            }
                        }
                        doc.Delete(p1.Id);
                        doc.Delete(p2.Id);

                        DefinitionFile     spfile = uiapp.Application.OpenSharedParameterFile();
                        DefinitionGroup    _grp   = spfile.Groups.get_Item("物理特性");
                        ExternalDefinition _def1  = _grp.Definitions.get_Item("米重") as ExternalDefinition;
                        ExternalDefinition _def2  = _grp.Definitions.get_Item("模图编号") as ExternalDefinition;
                        //添加参数
                        FamilyManager   familyMgr  = doc.FamilyManager;
                        bool            isInstance = false;
                        FamilyParameter paramMID   = familyMgr.AddParameter(_def2, BuiltInParameterGroup.PG_TEXT, isInstance);
                        FamilyParameter paramWPM   = familyMgr.AddParameter(_def1, BuiltInParameterGroup.INVALID, isInstance);

                        familyMgr.Set(paramMID, v2);
                        familyMgr.Set(paramWPM, (double)v1);

                        trans.Commit();

                        txtMID.Text = v2;
                        txtWPM.Text = v1.ToString();
                    }
                }
            }

            #endregion
        }
        /// <summary>
        /// The method is used to collect template information, specifying the New Window Parameters
        /// </summary>
        private void CollectTemplateInfo()
        {
            List <Wall> walls = Utility.GetElements <Wall>(m_application, m_document);

            m_wallThickness = walls[0].Width;
            ParameterMap paraMap        = walls[0].ParametersMap;
            Parameter    wallheightPara = walls[0].get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);//paraMap.get_Item("Unconnected Height");

            if (wallheightPara != null)
            {
                m_wallHeight = wallheightPara.AsDouble();
            }

            LocationCurve location = walls[0].Location as LocationCurve;

            m_wallWidth = location.Curve.Length;

            m_windowInset = m_wallThickness / 10;
            FamilyType      type           = m_familyManager.CurrentType;
            FamilyParameter heightPara     = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT);
            FamilyParameter widthPara      = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH);
            FamilyParameter sillHeightPara = m_familyManager.get_Parameter("Default Sill Height");

            if (type.HasValue(heightPara))
            {
                switch (heightPara.StorageType)
                {
                case StorageType.Double:
                    m_height = type.AsDouble(heightPara).Value;
                    break;

                case StorageType.Integer:
                    m_height = type.AsInteger(heightPara).Value;
                    break;
                }
            }
            if (type.HasValue(widthPara))
            {
                switch (widthPara.StorageType)
                {
                case StorageType.Double:
                    m_width = type.AsDouble(widthPara).Value;
                    break;

                case StorageType.Integer:
                    m_width = type.AsDouble(widthPara).Value;
                    break;
                }
            }
            if (type.HasValue(sillHeightPara))
            {
                switch (sillHeightPara.StorageType)
                {
                case StorageType.Double:
                    m_sillHeight = type.AsDouble(sillHeightPara).Value;
                    break;

                case StorageType.Integer:
                    m_sillHeight = type.AsDouble(sillHeightPara).Value;
                    break;
                }
            }

            //set the height,width and sillheight parameter of the opening
            m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT),
                                m_height);
            m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH),
                                m_width);
            m_familyManager.Set(m_familyManager.get_Parameter("Default Sill Height"), m_sillHeight);

            //get materials

            FilteredElementCollector elementCollector = new FilteredElementCollector(m_document);

            elementCollector.WherePasses(new ElementClassFilter(typeof(Material)));
            IList <Element> materials = elementCollector.ToElements();

            foreach (Element materialElement in materials)
            {
                Material material = materialElement as Material;
                m_para.GlassMaterials.Add(material.Name);
                m_para.FrameMaterials.Add(material.Name);
            }

            //get categories
            Categories      categories = m_document.Settings.Categories;
            Category        category   = categories.get_Item(BuiltInCategory.OST_Windows);
            CategoryNameMap cnm        = category.SubCategories;

            m_frameCat = categories.get_Item(BuiltInCategory.OST_WindowsFrameMullionProjection);
            m_glassCat = categories.get_Item(BuiltInCategory.OST_WindowsGlassProjection);

            //get referenceplanes
            List <ReferencePlane> planes = Utility.GetElements <ReferencePlane>(m_application, m_document);

            foreach (ReferencePlane p in planes)
            {
                if (p.Name.Equals("Sash"))
                {
                    m_sashPlane = p;
                }
                if (p.Name.Equals("Exterior"))
                {
                    m_exteriorPlane = p;
                }
                if (p.Name.Equals("Center (Front/Back)"))
                {
                    m_centerPlane = p;
                }
                if (p.Name.Equals("Top") || p.Name.Equals("Head"))
                {
                    m_topPlane = p;
                }
                if (p.Name.Equals("Sill") || p.Name.Equals("Bottom"))
                {
                    m_sillPlane = p;
                }
            }
        }
Ejemplo n.º 24
0
        private void EditFamily(Document famDoc, ExternalDefinition ExDef)
        {
            View view = famDoc.FindElement(typeof(View), targetName: "视图 1") as View;

            if (view == null)
            {
                throw new InvalidOperationException("view is null! ");
            }
            // 对于开挖土体族,其与模型土体不同的地方在于,它还是
            using (Transaction tranFam = new Transaction(famDoc))
            {
                try
                {
                    tranFam.SetName("对族文档进行修改");
                    tranFam.Start();
                    // ---------------------------------------------------------------------------------------------------------

                    // 添加参数
                    FamilyManager FM = famDoc.FamilyManager;

                    //’在进行参数读写之前,首先需要判断当前族类型是否存在,如果不存在,读写族参数都是不可行的
                    if (FM.CurrentType == null)
                    {
                        FM.NewType("CurrentType"); // 随便取个名字即可,后期会将族中的第一个族类型名称统一进行修改。
                    }

                    //
                    FamilyParameter Para_Depth;
                    Para_Depth = FM.get_Parameter("Depth");


                    FM.RemoveParameter(Para_Depth);

                    Para_Depth = FM.AddParameter(ExDef, BuiltInParameterGroup.PG_GEOMETRY, isInstance: true);

                    //' give initial values
                    // FM.Set(Para_Depth, depth); // 这里不知为何为给出报错:InvalidOperationException:There is no current type.
                    Extrusion extru = famDoc.FindElement(typeof(Extrusion)) as Extrusion;

                    // 添加标注
                    PlanarFace TopFace = GeoHelper.FindFace(extru, new XYZ(0, 0, 1));
                    PlanarFace BotFace = GeoHelper.FindFace(extru, new XYZ(0, 0, -1));

                    // make an array of references
                    ReferenceArray refArray = new ReferenceArray();
                    refArray.Append(TopFace.Reference);
                    refArray.Append(BotFace.Reference);
                    // define a demension line
                    var  a       = GeoHelper.FindFace(extru, new XYZ(0, 0, 1)).Origin;
                    Line DimLine = Line.CreateBound(TopFace.Origin, BotFace.Origin);
                    // create a dimension
                    Dimension DimDepth = famDoc.FamilyCreate.NewDimension(view, DimLine, refArray);

                    // 将深度参数与其拉伸实体的深度值关联起来
                    DimDepth.FamilyLabel = Para_Depth;

                    // famDoc.Close();
                    tranFam.Commit();
                }
                catch (Exception ex)
                {
                    // Utils.ShowDebugCatch(ex, $"事务“{tranFam.GetName()}” 出错!");
                    tranFam.RollBack();
                    throw new InvalidOperationException($"事务“{tranFam.GetName()}”出错", ex);
                }
            }
        }
Ejemplo n.º 25
0
        private void backgroundWorker4_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                {
                    MessageBox.Show("The Task Has Been Cancelled", "Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    progressBar1.Value  = 0;
                    StatusLabel.Visible = false;
                }
                else if (e.Error != null)
                {
                    MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    progressBar1.Value  = 0;
                    StatusLabel.Visible = false;
                }
                else
                {
                    RevitServices.Transactions.TransactionManager.Instance.ForceCloseTransaction();


                    var distinctItems = deleteParametersWindows.GroupBy(x => x.Id).Select(y => y.First()); //Sorts the list into only unique items

                    foreach (var item in distinctItems)
                    {
                        Document      famDoc        = localDoc.Document.EditFamily(item); //get the family property of the family
                        FamilyManager familyManager = famDoc.FamilyManager;

                        using (Transaction t = new Transaction(famDoc, "Set Parameter")) //Change Door values
                        {
                            t.Start();

                            try
                            {
                                ///delete here
                                ///

                                FamilyParameter param = familyManager.get_Parameter("Fire_Rating");

                                familyManager.RemoveParameter(param);
                            }
                            catch
                            {
                                //silent catch to continue if Fire_Rating is already on a door from a previous activation
                            }

                            t.Commit();

                            LoadOpts famLoadOptions         = new LoadOpts();
                            Autodesk.Revit.DB.Family newFam = famDoc.LoadFamily(localDoc.Document, famLoadOptions);
                        }
                    }



                    MessageBox.Show("The Task Has Been Completed.", "Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    progressBar1.Value = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            DoorToWall.Enabled              = true;
            WindowToWall.Enabled            = true;
            DeleteFireRatingsDoors.Enabled  = true;
            DeleteFireRatingsWindow.Enabled = true;

            deleteParametersWindows.Clear();

            buttonCancel.Enabled = false;
            StatusLabel.Visible  = false;
        }
        /// <summary>
        /// Shuffles all parameter values
        /// </summary>
        /// <param name="uiapp">The Revit application object</param>
        /// <param name="text">Caption of the transaction for the operation.</param>
        /// <param name="operation">A delegate to perform the operation on an instance of a door.</param>
        ///
        public static void ExecuteParameterChange(UIApplication uiapp, String text, List <Tuple <string, double> > values)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message = "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            int    counter = 0;
            int    max     = values.Count();
            string current = "";

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Change"))
                {
                    tg.Start();

                    string s       = "{0} of " + max.ToString() + String.Format(" elements processed. ", counter.ToString()) + "{1}";
                    string caption = "Processing ..";

                    using (ProgressBarView pbv = new ProgressBarView(caption, s, max))
                    {
                        foreach (var value in values)
                        {
                            current = value.Item1;

                            if (pbv.getAbortFlag())
                            {
                                break;
                            }
                            pbv.Increment(current);    //Increment the ProgressBar
                            using (Transaction trans = new Transaction(uidoc.Document))
                            {
                                FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                                FailureHandler         failureHandler         = new FailureHandler();
                                failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                                failureHandlingOptions.SetClearAfterRollback(true);
                                trans.SetFailureHandlingOptions(failureHandlingOptions);

                                FamilyManager   mgr = doc.FamilyManager;
                                FamilyParameter fp  = mgr.get_Parameter(value.Item1);
                                // Since we'll modify the document, we need a transaction
                                // It's best if a transaction is scoped by a 'using' block
                                // The name of the transaction was given as an argument
                                if (trans.Start(text) == TransactionStatus.Started)
                                {
                                    if (fp.IsDeterminedByFormula)
                                    {
                                        continue;                            //Cannot change parameters driven by formulas
                                    }
                                    if (fp.IsReporting)
                                    {
                                        continue;                    //Cannot change reporting parameters
                                    }
                                    mgr.Set(fp, value.Item2);
                                    doc.Regenerate();
                                    trans.Commit();
                                    uidoc.RefreshActiveView();
                                    if (failureHandler.ErrorMessage != "")
                                    {
                                        RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage));
                                    }
                                    else
                                    {
                                        RequestError.NotifyLog += $"{fp.Definition.Name} was shuffled.{Environment.NewLine}";
                                    }
                                }
                            }
                        }
                    }
                    tg.Assimilate();
                    if (!String.IsNullOrEmpty(RequestError.NotifyLog))
                    {
                        var lines = RequestError.NotifyLog.Split('\n').Length - 1;
                        RequestError.NotifyLog += $"{Environment.NewLine}{lines.ToString()} parameters have been processed sucessfully.";
                    }
                }
            }
        }
Ejemplo n.º 27
0
        private List <FamilyTypeData> GetTypes(Family family, Document doc, string path)
        {
            Document              familyDoc     = doc.EditFamily(family);
            FamilyManager         familyManager = familyDoc.FamilyManager;
            FamilyTypeSet         familyTypes   = familyManager.Types;
            FamilyTypeSetIterator iterator      = familyTypes.ForwardIterator();

            iterator.Reset();

            List <FamilyTypeData> types = new List <FamilyTypeData>();

            while (iterator.MoveNext())
            {
                using (Transaction trans = new Transaction(familyDoc, "Getting Parameter"))
                {
                    trans.Start();
                    familyManager.CurrentType = iterator.Current as FamilyType;
                    FamilyType type = familyManager.CurrentType;

                    string paramDescription = string.Empty;
                    //FamilyParameter paramDescription;
                    try
                    {
                        paramDescription = type.AsString(familyManager.get_Parameter("Description"));
                        if (string.IsNullOrEmpty(paramDescription))
                        {
                            try
                            {
                                paramDescription = type.AsString(familyManager.get_Parameter("Beschreibung"));
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramMountType = string.Empty;
                    try
                    {
                        paramMountType = type.AsString(familyManager.get_Parameter("Installationsart"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramPlacement = string.Empty;
                    try
                    {
                        paramPlacement = type.AsString(familyManager.get_Parameter("Installationsort"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramInstallationMedium = string.Empty;
                    try
                    {
                        paramInstallationMedium = type.AsString(familyManager.get_Parameter("Installations Medium"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramDiameter = string.Empty;
                    try
                    {
                        paramDiameter = type.AsString(familyManager.get_Parameter("E_Durchmesser"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramWidth = string.Empty;
                    try
                    {
                        paramWidth = type.AsString(familyManager.get_Parameter("E_Breite"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramHeight = string.Empty;
                    try
                    {
                        paramHeight = type.AsString(familyManager.get_Parameter("E_Hohe"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramDepth = string.Empty;
                    try
                    {
                        paramDepth = type.AsString(familyManager.get_Parameter("E_Tiefe"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string param_eBKP_H = string.Empty;
                    try
                    {
                        param_eBKP_H = type.AsString(familyManager.get_Parameter("eBKP-H"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramBKP = string.Empty;
                    try
                    {
                        paramBKP = type.AsString(familyManager.get_Parameter("BKP"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramManufacturer = string.Empty;
                    try
                    {
                        paramManufacturer = type.AsString(familyManager.get_Parameter("Fabrikat"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramProduct = string.Empty;
                    try
                    {
                        paramProduct = type.AsString(familyManager.get_Parameter("Produkt"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramProductNumber = string.Empty;
                    try
                    {
                        paramProductNumber = type.AsString(familyManager.get_Parameter("Produkte-Nr."));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramE_Number = string.Empty;
                    try
                    {
                        paramE_Number = type.AsString(familyManager.get_Parameter("E-Nummer"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramRevitCategory = String.Empty;
                    try
                    {
                        paramRevitCategory = type.AsString(familyManager.get_Parameter("Revit Kategorie"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    string paramOmniClass = string.Empty;
                    try
                    {
                        paramOmniClass = type.AsString(familyManager.get_Parameter("OmniClass-Nummer"));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    if (true /*type != null && paramMountType!= null && paramPlacement!= null && paramInstallationMedium!=null*/)
                    {
                        FamilyTypeData typeData = new FamilyTypeData
                        {
                            Name               = type.Name,
                            Description        = string.IsNullOrEmpty(paramDescription)? emptyParameter: paramDescription,
                            MountType          = string.IsNullOrEmpty(paramMountType)? emptyParameter: paramMountType,
                            Placement          = string.IsNullOrEmpty(paramPlacement)? emptyParameter :paramPlacement,
                            InstallationMedium = string.IsNullOrEmpty(paramInstallationMedium) ? emptyParameter : paramInstallationMedium,
                            Path               = path,
                            CombinedTypeData   = paramDescription + "\n" + type.Name,
                            Diameter           = string.IsNullOrEmpty(paramDiameter)? emptyParameter: paramDiameter,
                            Width              = string.IsNullOrEmpty(paramWidth) ? emptyParameter : paramWidth,
                            Hight              = string.IsNullOrEmpty(paramHeight) ? emptyParameter : paramHeight,
                            Depth              = string.IsNullOrEmpty(paramDepth) ? emptyParameter : paramDepth,
                            eBKP_H             = string.IsNullOrEmpty(param_eBKP_H) ? emptyParameter : param_eBKP_H,
                            BKP           = string.IsNullOrEmpty(paramBKP) ? emptyParameter : paramBKP,
                            Manufacturer  = string.IsNullOrEmpty(paramManufacturer) ? emptyParameter : paramManufacturer,
                            Product       = string.IsNullOrEmpty(paramProduct) ? emptyParameter : paramProduct,
                            ProductNumber = string.IsNullOrEmpty(paramProductNumber) ? emptyParameter : paramProductNumber,
                            E_Number      = string.IsNullOrEmpty(paramE_Number) ? emptyParameter : paramE_Number,
                            RevitCategory = string.IsNullOrEmpty(paramRevitCategory) ? emptyParameter : paramRevitCategory,
                            OmniClass     = string.IsNullOrEmpty(paramOmniClass) ? emptyParameter : paramOmniClass
                        };
                        types.Add(typeData);
                    }

                    //TaskDialog.Show("Params", paramDescription.Definition.Name + " * " + type.AsString(paramDescription));
                    //TaskDialog.Show("Params", paramMountType.Definition.Name + " * " + type.AsString(paramMountType));
                    //TaskDialog.Show("Params", paramPlacement.Definition.Name + " * " + type.AsString(paramPlacement));
                    //TaskDialog.Show("Params", paramInstallationMedium.Definition.Name + " * " + type.AsString(paramInstallationMedium));
                    trans.Commit();
                }
            }

            return(types);
        }
Ejemplo n.º 28
0
//		public void Rename_Shared_Parameters(string p_name,string new_name)
//		{
        ////			UIDocument uidoc = this.ActiveUIDocument;
        ////			Document CachedDoc = uidoc.Document;
//			Document doc;
//			//Application app;
//			string folder = @"F:\ECG work\ECG_Shared_Parameters\Samples\sample 1\f1";
//
//			// loop through all files in the directory
//
//			foreach (string filename in System.IO.Directory.GetFiles(folder))
//			{
//				try
//				{
//					doc = Application.OpenDocumentFile(filename);
//					if (doc.IsFamilyDocument)
//					{
//
//						Transaction trans = new Transaction(doc, "Remove Param");
//						trans.Start();
//						using(trans)
//						{
//							//ExternalDefinition extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), "CompanyName");
//							FamilyManager fm = doc.FamilyManager;
//							FamilyParameter fp = RawConvertSetToList<FamilyParameter>(fm.Parameters).
//								FirstOrDefault(e => e.Definition.Name.Equals(p_name, StringComparison.CurrentCultureIgnoreCase));
//							if (fp == null) throw new Exception("Invalid ParameterName Input!");
//							if(fp.IsShared)
//							{
//								ExternalDefinition extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), p_name);
        ////									        Guid guid = extdef.GUID;
        ////									        ParameterType type = extdef.ParameterType;
        ////									        string group_name = extdef.ParameterGroup.ToString();
//
//								//Create_SP(new_name,type,group_name);
//
        ////									        fm.ReplaceParameter(fp,"temp_test",BuiltInParameterGroup.PG_TEXT,true);
        ////									        FamilyParameter new_fp = RawConvertSetToList<FamilyParameter>(fm.Parameters).
        ////									        FirstOrDefault(e => e.Definition.Name.Equals("temp_test", StringComparison.CurrentCultureIgnoreCase));
        ////									        ExternalDefinition new_extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), new_name);
        ////									        fm.ReplaceParameter(new_fp,new_extdef,new_extdef.ParameterGroup,true);
//							}
//							trans.Commit();
//							//		doc.SaveAs(filename);
//							doc.Close(true);
//						}
//					}
//
//				}
//				catch (Autodesk.Revit.Exceptions.ArgumentNullException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//				//	return;
//				}
//				catch (Autodesk.Revit.Exceptions.FamilyContextException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//				//	return;
//				}
//				catch (Autodesk.Revit.Exceptions.FileAccessException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//				//	return;
//				}
//				catch (Autodesk.Revit.Exceptions.FileNotFoundException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//				//	return;
//				}
//				catch (Autodesk.Revit.Exceptions.ApplicationException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//					return;
//				}
//				catch (SystemException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//					//return;
//				}
//			}
//
//			//TaskDialog.Show("Iam","Here");
//
//		}

        /*	public static string GetParameterValue(FamilyParameter p)
         *      {
         *              switch(p.StorageType)
         *              {
         *                      case StorageType.Double:
         *                              return p.AsValueString();
         *                      case StorageType.ElementId:
         *                              return p.AsElementId().IntegerValue.ToString();
         *                      case StorageType.Integer:
         *                              return p.AsValueString();
         *                      case StorageType.None:
         *                              return p.AsValueString();
         *                      case StorageType.String:
         *                              return p.AsString();
         *                      default:
         *                              return "";
         *
         *              }
         *      }*/

        public static void Rename_Family_Parameters(List <string> full_files_name)
        {
//			UIDocument uidoc = this.ActiveUIDocument;
//			Document CachedDoc = uidoc.Document;
            Document doc;

            //Application app;
            //string folder = @"F:\ECG work\ECG_Shared_Parameters\Samples\sample 1\f1";

            // loop through all files in the directory

            foreach (string filename in full_files_name)
            {
                doc = CachedApp.OpenDocumentFile(filename);
                try
                {
                    if (doc.IsFamilyDocument)
                    {
                        Transaction trans = new Transaction(doc, "Rename Param");

                        using (trans)
                        {
                            //string s = Globals.new_name_for_rename;


                            trans.Start();
                            FamilyManager   fm = doc.FamilyManager;
                            FamilyParameter fp = RawConvertSetToList <FamilyParameter>(fm.Parameters).
                                                 FirstOrDefault(e => e.Definition.Name.Equals(Globals.parm_to_Replace, StringComparison.CurrentCultureIgnoreCase));
                            //		TaskDialog.Show("Revit","Shared Parameter !!");
                            trans.Commit();
                            if (fp.IsShared)
                            {
                                //		TaskDialog.Show("Revit",fm.Types.Size.ToString());
                                //	Element e = FilteredElementCollector(doc).OfClass(fm.CurrentType);

                                //	Parameter p = fm.Parameter(fp.Definition);
//									if (fp == null) throw new Exception("Invalid ParameterName Input!");
//									string tmp = "Parameter name: "+ fp.Definition.Name + "\n" +"Is Shared!";

                                //TaskDialog.Show("Warrning",tmp);
                                ExternalDefinition edf;
                                //	if(!Globals.all_SP_variables.Contains(fp.Definition.Name))
                                edf = Create_SP(Globals.new_name_for_rename,
                                                Globals.new_type,
                                                Globals.new_group);

                                trans.Start();
                                fm.AddParameter(edf, edf.ParameterGroup, Globals.instance_or_not);
                                //	fm.Parameter(edf.Name).Set(fp.ToString());


                                FamilyParameter fp_tmp = fm.get_Parameter(Globals.new_name_for_rename);
                                foreach (FamilyType t in fm.Types)
                                {
                                    if (t.HasValue(fp))
                                    {
                                        //TaskDialog.Show("R","Here");
                                        fm.CurrentType = t;
                                        if (fp_tmp.StorageType == StorageType.Double)
                                        {
                                            fm.Set(fp_tmp, t.AsDouble(fp).Value);
                                        }
                                        else if (fp_tmp.StorageType == StorageType.Integer)
                                        {
                                            fm.Set(fp_tmp, t.AsInteger(fp).Value);
                                        }
                                        else if (fp_tmp.StorageType == StorageType.ElementId)
                                        {
                                            fm.Set(fp_tmp, t.AsElementId(fp).IntegerValue);
                                        }
                                        else if (fp_tmp.StorageType == StorageType.String)
                                        {
                                            fm.Set(fp_tmp, t.AsString(fp));
                                        }
                                    }
                                    // TaskDialog.Show("R",);
                                }
                                //fm.Types
                                trans.Commit();

                                trans.Start();
                                fm.RemoveParameter(fp);
                                trans.Commit();
                                //	string k = "Parameter name: "+ edf.Name + "\n" +"Is Shared!";

                                //	TaskDialog.Show("Warrning",k);

                                //	fm.AddParameter();
                                //		rename_in_shared_parm_file(fp.Definition.Name,Globals.new_name_for_rename);

                                //doc.Close(false);
                                continue;
                            }
//								if (fp == null) throw new Exception("Invalid ParameterName Input!");
//								fm.RenameParameter(fp,new_name);
                            //      Test();
                            trans.Commit();

                            //ExternalDefinition extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), "CompanyName");
//										FamilyManager fm = doc.FamilyManager;
//										FamilyParameter fp = RawConvertSetToList<FamilyParameter>(fm.Parameters).
//									        FirstOrDefault(e => e.Definition.Name.Equals(p_name, StringComparison.CurrentCultureIgnoreCase));
//									    if (fp == null) throw new Exception("Invalid ParameterName Input!");
//									    fm.RenameParameter(fp,new_name);
                            //                                      trans.Commit();
                            //		doc.SaveAs(filename);
                            doc.Close(true);
                        }
                    }
                }
                catch (Autodesk.Revit.Exceptions.ArgumentNullException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    //trans.Commit();
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FamilyContextException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FileAccessException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FileNotFoundException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.ApplicationException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (SystemException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //		return;
                }
            }

            //TaskDialog.Show("Iam","Here");
        }
Ejemplo n.º 29
0
        public bool BindSharedParameters(string filePath, bool isInstance)
        {
            string         filepath   = filePath;
            bool           isinstance = isInstance;
            DefinitionFile file       = null;

            m_app.SharedParametersFilename = filepath;

            try
            {
                file = m_app.OpenSharedParameterFile();
            }
            catch
            {
                MessageBox.Show("File has an invalid format.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (File.Exists(filepath) &&
                null == file)
            {
                MessageBox.Show("File has an invalid format.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            foreach (DefinitionGroup group in file.Groups)
            {
                foreach (ExternalDefinition def in group.Definitions)
                {
                    // check whether the parameter already exists in the document
                    FamilyParameter param = m_manager.get_Parameter(def.Name);
                    if (null != param)
                    {
                        continue;
                    }

                    BuiltInParameterGroup bpg = BuiltInParameterGroup.INVALID;
                    try
                    {
                        switch (def.OwnerGroup.Name)
                        {
                        case "Dimensions":
                            bpg = BuiltInParameterGroup.PG_GEOMETRY;
                            break;

                        case "Graphics":
                            bpg = BuiltInParameterGroup.PG_GRAPHICS;
                            break;

                        case "Model Properties":
                            bpg = BuiltInParameterGroup.PG_ADSK_MODEL_PROPERTIES;
                            break;

                        case "Overall Legend":
                            bpg = BuiltInParameterGroup.PG_OVERALL_LEGEND;
                            break;

                        case "Electrical":
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL;
                            break;

                        case "Mechanical":
                            bpg = BuiltInParameterGroup.PG_MECHANICAL;
                            break;

                        case "Electrical - Lighting":
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL_LIGHTING;
                            break;

                        case "Identity Data":
                            bpg = BuiltInParameterGroup.PG_IDENTITY_DATA;
                            break;

                        case "Data":
                            bpg = BuiltInParameterGroup.PG_DATA;
                            break;

                        case "Electrical - Loads":
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL_LOADS;
                            break;

                        case "Mechanical - Air Flow":
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_AIRFLOW;
                            break;

                        case "Energy Analysis":
                            bpg = BuiltInParameterGroup.PG_ENERGY_ANALYSIS;
                            break;

                        case "Photometrics":
                            bpg = BuiltInParameterGroup.PG_LIGHT_PHOTOMETRICS;
                            break;

                        case "Mechanical - Loads":
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_LOADS;
                            break;

                        case "Structural":
                            bpg = BuiltInParameterGroup.PG_STRUCTURAL;
                            break;

                        case "Plumbing":
                            bpg = BuiltInParameterGroup.PG_PLUMBING;
                            break;

                        case "Green Building Properties":
                            bpg = BuiltInParameterGroup.PG_GREEN_BUILDING;
                            break;

                        case "Materials and Finishes":
                            bpg = BuiltInParameterGroup.PG_MATERIALS;
                            break;

                        case "Other":
                            bpg = BuiltInParameterGroup.INVALID;
                            break;

                        case "Construction":
                            bpg = BuiltInParameterGroup.PG_CONSTRUCTION;
                            break;

                        case "Phasing":
                            bpg = BuiltInParameterGroup.PG_PHASING;
                            break;

                        default:
                            bpg = BuiltInParameterGroup.INVALID;
                            break;
                        }

                        m_manager.AddParameter(def, bpg, isinstance);
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            return(true);
        }