/// <summary>
        /// Get family parameter IsShared
        /// and GUID properties.
        /// </summary>
        /// <returns>True if the family parameter
        /// is shared and has a GUID.</returns>
        bool GetFamilyParamGuid(
            FamilyParameter fp,
            out string guid)
        {
            guid = string.Empty;

              bool isShared = false;

              System.Reflection.FieldInfo fi
            = fp.GetType().GetField( "m_Parameter",
              System.Reflection.BindingFlags.Instance
              | System.Reflection.BindingFlags.NonPublic );

              if( null != fi )
              {
            Parameter p = fi.GetValue( fp ) as Parameter;

            isShared = p.IsShared;

            if( isShared && null != p.GUID )
            {
              guid = p.GUID.ToString();
            }
              }
              return isShared;
        }
 /// <summary>
 /// Check parameter conditions
 /// </summary>
 /// <param name="fp"></param>
 /// <param name="ft"></param>
 /// <returns></returns>
 private Boolean famEdit(FamilyParameter fp, FamilyType ft)
 {
     //double valueDouble;
     //int valueInt;
     if (!fp.StorageType.ToString().Equals("Double") && !fp.StorageType.ToString().Equals("Integer"))
     {
         return false;
     }
     else if (fp.UserModifiable)
     {
         return false;
     }
     else if (fp.IsDeterminedByFormula || fp.Formula != null)
     {
         return false;
     }
     else if (!ft.HasValue(fp))
     {
         return false;
     }
     else if (ft.AsDouble(fp) == null && ft.AsInteger(fp) == null)
     {
         return false;
     }
     //else if (!double.TryParse(ft.AsDouble(fp).ToString(), out valueDouble) && !int.TryParse(ft.AsInteger(fp).ToString(), out valueInt))
     //{
     //    return false;
     //}
     else if (fp.IsReporting)
     {
         return false;
     }
     else if (fp.IsDeterminedByFormula)
     {
         return false;
     }
     return true;
 }
        /// <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);
                }
            }
        }
Exemple #4
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();
                }
            }
        }
        //Create a checkbox FamilyParameterModel item
        internal static FamilyParameterModel FamilyParameterItem(FamilyType ft, FamilyParameter fp, List <FamilyParameter> paramLabel, List <FamilyParameter> paramFormula)
        {
            //Collect data depending on the type of paramter
            FamilyParameterModel newItem = new FamilyParameterModel(); //Create new FamilyParamterModel

            newItem.SuppressUpdate();                                  //When setting the first time, suppress the back-update coming from the UI because of difference in precision
            newItem.Name            = fp.Definition.Name;              //The name of the Parameter
            newItem.StorageType     = fp.StorageType;
            newItem.ParamType       = GetParameterType(fp);
            newItem.DisplayUnitType = GetDisplayUnitType(fp);                      //Set the DisplayUnitType for this parameter
            newItem.Precision       = Utils.GetPrecision(newItem.DisplayUnitType); //Properties.Settings.Default.Precision;  //The precision set by the User in the Settings
            newItem.Type            = fp.Definition.ParameterType.ToString();      //The parameter type
            newItem.Associated      = !fp.AssociatedParameters.IsEmpty;            //If the parameter is being associated
            newItem.BuiltIn         = fp.Id.IntegerValue < 0;
            newItem.Modifiable      = fp.UserModifiable;
            newItem.Formula         = fp.IsDeterminedByFormula;
            newItem.Label           = paramLabel.Any(f => f.Id == fp.Id);
            newItem.Reporting       = fp.IsReporting;
            newItem.UsedInFormula   = paramFormula.Any(f => f.Id == fp.Id);
            newItem.ReadOnly        = fp.IsReadOnly;
            newItem.Shared          = fp.IsShared;
            newItem.TypeOrInstance  = fp.IsInstance ? "Instance" : "Type";
            newItem.IsUsed          = (newItem.Associated || newItem.Label || newItem.UsedInFormula); //Used if any of the three is true
            newItem.Editable        = newItem.IsUsed && !newItem.Formula && !newItem.Reporting;       //If the Parameter is used or if the parameter is not defined by Formula, allow the user to edit
            newItem.Visible         = Properties.Settings.Default.ToggleVisibility;                   //Set the visibility in the UI (user defined Tag property for ALL Tags, regardless of their specific conditions)
            newItem.TagVisible      = Properties.Settings.Default.ToggleTagsVisibility;               //Set the Tags visibility

            newItem.RevitValue = GetParameterValue(ft, fp);                                           //Set the Revit internal value for the Parameter

            if (newItem.RevitValue == 0.0)
            {
                newItem.Value   = Utils.GetDutValueTo(newItem.StorageType, newItem.DisplayUnitType, newItem.RevitValue);                //The unit specific value in double
                newItem.UIValue = ValueConvertUtils.StringFromDoubleConvert(newItem.DisplayUnitType, newItem.Precision, newItem.Value); //The string representation of the value
            }

            return(newItem);
        }
        private void SetFormula(Document familyDoc)
        {
            _type = familyDoc.FamilyManager.NewType(_name);
            string newParamName = "Program Area";
            //
            //familyDoc.FamilyManager.AddParameter("Area", BuiltInParameterGroup.PG_CONSTRAINTS, ParameterType.Area, true);
            // replaced by line below
            ParameterBinding paramBind = new ParameterBinding(familyDoc, "Areas", newParamName);
            //
            //FamilyParameter param = familyDoc.FamilyManager.get_Parameter("Area");
            // replaced by line below
            FamilyParameter param = familyDoc.FamilyManager.get_Parameter(newParamName);

            if (null != param)
            {
                familyDoc.FamilyManager.Set(param, _area);
            }
            param = familyDoc.FamilyManager.get_Parameter("Height");
            if (null != param)
            {
                // familyDoc.FamilyManager.SetFormula(param, @"Area / Width");
                familyDoc.FamilyManager.SetFormula(param, @"Program Area / Width");
            }
        }
Exemple #7
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();
            }
        }
Exemple #8
0
        public static void SetFamilyParam(this Document doc, Param p, string value)
        {
            if (doc.IsFamilyDocument)
            {
                if (doc.FamilyManager.get_Parameter(p.Guid) != null)
                {
                    FamilyParameter param = doc.FamilyManager.get_Parameter(p.Guid);
                    foreach (FamilyType t in doc.FamilyManager.Types)
                    {
                        doc.FamilyManager.CurrentType = t;
                        switch (p.Type)
                        {
                        case ParamType.Text:
                            doc.FamilyManager.Set(param, value);
                            break;

                        case ParamType.Int:
                            doc.FamilyManager.Set(param, int.Parse(value));
                            break;
                        }
                    }
                }
            }
        }
        static string FamilyParamValueString(
            FamilyType t,
            FamilyParameter fp,
            Document doc)
        {
            string value = t.AsValueString( fp );
              switch( fp.StorageType )
              {
            case StorageType.Double:
              value = Util.RealString(
            ( double ) t.AsDouble( fp ) )
            + " (double)";
              break;

            case StorageType.ElementId:
              ElementId id = t.AsElementId( fp );
              Element e = doc.GetElement( id );
              value = id.IntegerValue.ToString() + " ("
            + Util.ElementDescription( e ) + ")";
              break;

            case StorageType.Integer:
              value = t.AsInteger( fp ).ToString()
            + " (int)";
              break;

            case StorageType.String:
              value = "'" + t.AsString( fp )
            + "' (string)";
              break;
              }
              return value;
        }
      Stream(ArrayList data, FamilyParameter famParam)
      {
         data.Add(new Snoop.Data.ClassSeparator(typeof(FamilyParameter)));

         data.Add(new Snoop.Data.Enumerable("Associated parameters", famParam.AssociatedParameters));
         data.Add(new Snoop.Data.Bool("Can assign formula", famParam.CanAssignFormula));
         data.Add(new Snoop.Data.Object("Definition", famParam.Definition));
         try
         {   // this only works for certain types of Parameters
            data.Add(new Snoop.Data.String("Display unit type", famParam.DisplayUnitType.ToString()));
         }
         catch (System.Exception)
         {
            data.Add(new Snoop.Data.String("Display unit type", "N/A"));
         }
         data.Add(new Snoop.Data.String("Formula", famParam.Formula));
         data.Add(new Snoop.Data.Bool("Is determined by formula", famParam.IsDeterminedByFormula));
         data.Add(new Snoop.Data.Bool("Is instance", famParam.IsInstance));
         data.Add(new Snoop.Data.String("Storage type", famParam.StorageType.ToString()));
      }
Exemple #11
0
 public OneParamData(FamilyParameter familyParameter, ParameterJerkerHubCentral jerkHub) : base(jerkHub)
 {
     this.FamilyParameter  = familyParameter;
     CurrentParameterGroup = familyParameter.Definition.ParameterGroup;
 }
Exemple #12
0
        public static void Remove_Parameter(List <string> full_files_name, List <string> parm_to_add)
        {
//			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)
                    {
                        FamilyManager fm    = doc.FamilyManager;
                        Transaction   trans = new Transaction(doc, "Remove Param");

                        using (trans)
                        {
                            //ExternalDefinition extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), "CompanyName");

                            foreach (string s in parm_to_add)
                            {
                                trans.Start();
                                FamilyParameter fp = RawConvertSetToList <FamilyParameter>(fm.Parameters).
                                                     FirstOrDefault(e => e.Definition.Name.Equals(s, StringComparison.CurrentCultureIgnoreCase));
                                //		TaskDialog.Show("Revit","Shared Parameter !!");

                                if (fp == null)
                                {
                                    throw new Exception("Invalid ParameterName Input!");
                                }
                                fm.RemoveParameter(fp);
                                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");
        }
Exemple #13
0
        public void RawSetFamilyParameterValue(FamilyManager fm, FamilyType ft, FamilyParameter fp, object value)
        {
            FamilyType curFamType = fm.CurrentType;

            fm.CurrentType = ft;

            try
            {
                switch (fp.StorageType)
                {
                case StorageType.None:
                    break;

                case StorageType.Double:
                    if (value.GetType().Equals(typeof(string)))
                    {
                        fm.Set(fp, double.Parse(value as string));
                    }
                    else
                    {
                        fm.Set(fp, Convert.ToDouble(value));
                    }
                    break;

                case StorageType.Integer:
                    if (value.GetType().Equals(typeof(string)))
                    {
                        fm.Set(fp, int.Parse(value as string));
                    }
                    else
                    {
                        fm.Set(fp, Convert.ToInt32(value));
                    }
                    break;

                case StorageType.ElementId:
                    if (value.GetType().Equals(typeof(ElementId)))
                    {
                        fm.Set(fp, value as ElementId);
                    }
                    else if (value.GetType().Equals(typeof(string)))
                    {
                        fm.Set(fp, new ElementId(int.Parse(value as string)));
                    }
                    else
                    {
                        fm.Set(fp, new ElementId(Convert.ToInt32(value)));
                    }
                    break;

                case StorageType.String:
                    fm.Set(fp, value.ToString());
                    break;
                }
            }
            catch
            {
                throw new Exception("Invalid Value Input!");
            }
            finally
            {
                fm.CurrentType = curFamType;
            }
        }
Exemple #14
0
        //Here, the families or types will be made
        private static void CreateFamilyTypesFromTable(UIApplication uiApp, MainUI uiForm, string saveDirectory, DataGridView dgv, SaveAsOptions saveAsOptions, string familyFileToUse)
        {
            //First thing to do is open the family document and access the FamilyManager
            RVTDocument   famDoc = RVTOperations.OpenRevitFile(uiApp, familyFileToUse);
            FamilyManager famMan = famDoc.FamilyManager;

            string tempFamilyPath = "";

            //Next, delete all of the family types except one from the family and save the file off for temporary use
            try
            {
                //This is in a Try/Catch becuse there is a possibility for failure
                RVTOperations.DeleteFamilyTypes(famDoc, famMan);
                tempFamilyPath = saveDirectory + "\\" + String.Format(famDoc.Title).Replace(".rfa", "") + "_temp.rfa";
                famDoc.SaveAs(tempFamilyPath, saveAsOptions);
            }
            catch { MessageBox.Show("Could not save out a temporary family file to the location where the families are to be saved. Verify the location is not read-only."); }
            //Ensure the open family gets closed
            finally { famDoc.Close(); }

            //Then, reopen the temporary family if it exists
            if (tempFamilyPath != "")
            {
                //Get all of the parameters in the family and add them to a dictionary indexed by the parameter name
                RVTDocument        newFamDoc  = RVTOperations.OpenRevitFile(uiApp, tempFamilyPath);
                FamilyManager      newFamMan  = newFamDoc.FamilyManager;
                FamilyParameterSet parameters = newFamMan.Parameters;
                Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                foreach (FamilyParameter param in parameters)
                {
                    famParamDict.Add(param.Definition.Name, param);
                }

                //These integer values will be used to increment loops
                int rowsCount    = dgv.Rows.Count;
                int columnsCount = dgv.Columns.Count;

                //Keep track of what family types were made so the script can later delete out the one that pre-existed in the family but is not needed.
                List <string> familyTypesMade = new List <string>();
                //If the user decide to make types per row instead of families per row...
                if (uiForm.multiCatCFFEFamilyCreationComboBox.SelectedItem.ToString() == "Combine Types (1 File)")
                {
                    //The progress bar should be prepared using the number of rows multipled by the number of columns for the number of steps to perform. This gives a better indication of progress than doing it based on the number of rows
                    uiForm.multiCatCFFEFamiliesProgressBar.Minimum = 0;
                    uiForm.multiCatCFFEFamiliesProgressBar.Maximum = (rowsCount - 1) * (columnsCount - 1);
                    uiForm.multiCatCFFEFamiliesProgressBar.Step    = 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Visible = true;

                    //Open the transaction
                    Transaction t2 = new Transaction(newFamDoc, "MakeNewTypes");
                    t2.Start();
                    //The maximum of rows is greater than the maximum index value by 1, so this uses < to stop before an index out of range exception occurs. Also, the index starts at 1 instead of 0 because the top row is the info about the data type
                    for (int i = 1; i < rowsCount; i++)
                    {
                        //The type name is in the first column.
                        string newTypeName = dgv.Rows[i].Cells[0].Value.ToString();
                        //This operation will get the existing type names in the family as new ones are added to avoide duplication
                        Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(newFamMan);
                        //If the type does not exist in the dictionary...
                        if (!existingTypeNames.Keys.Contains(newTypeName))
                        {
                            //Create a new type and add it to the list of types made
                            FamilyType newType = newFamMan.NewType(newTypeName);
                            newFamMan.CurrentType = newType;
                            familyTypesMade.Add(newType.Name);
                        }
                        else
                        {
                            //Otherwise set the current type in the family manager to the pre-existing one with the name of the one to be created
                            newFamMan.CurrentType = existingTypeNames[newTypeName];
                            //Add that one to the list of types made, though it wasn't actually made
                            familyTypesMade.Add(newFamMan.CurrentType.Name);
                        }

                        //Next, cycle through the columns, again starting with the column at index 1 and incrementing the columns to one less than the number of columns
                        for (int j = 1; j < columnsCount; j++)
                        {
                            //Get the parameter name from the first column's header text
                            string paramName = dgv.Columns[j].HeaderText;
                            //Get the storage type from the first row
                            string paramStorageTypeString = dgv.Rows[0].Cells[j].Value.ToString();
                            var    paramValue             = dgv.Rows[i].Cells[j].Value;
                            //Assuming the parameter value is set...
                            if (paramValue.ToString() != "")
                            {
                                //Set the parameter given the information about the FamilyManager, parameter definition, parameter type, parameter data type, value to set, and whether or not to convert inches to feet. Because this script relies on inch input, this needs done to convert to feet used by the Revit API
                                FamilyParameter param     = famParamDict[paramName];
                                ParameterType   paramType = param.Definition.ParameterType;
                                RVTOperations.SetFamilyParameterValue(newFamMan, param, paramType, paramStorageTypeString, paramValue, true);
                            }
                            //Step forward the progress bar for this parameter
                            uiForm.multiCatCFFEFamiliesProgressBar.PerformStep();
                        }
                    }
                    t2.Commit();

                    //In another transaction, delete the pre-existing type used to generate the other types
                    Transaction t3 = new Transaction(newFamDoc, "DeleteOldTypes");
                    t3.Start();
                    foreach (FamilyType type in newFamMan.Types)
                    {
                        //Set the current type to the one with the pre-existing type name and delete it
                        if (!familyTypesMade.Contains(type.Name))
                        {
                            newFamMan.CurrentType = type;
                            newFamMan.DeleteCurrentType();
                        }
                    }
                    t3.Commit();

                    //Save out the family to the directory and remove the _temp from the name
                    newFamDoc.SaveAs(saveDirectory + "\\" + String.Format(newFamDoc.Title).Replace("_temp", "") + ".rfa", saveAsOptions);
                    newFamDoc.Close();
                }

                //If the user chose to make a family file per row, the family will be saved out multiple times
                else if (uiForm.multiCatCFFEFamilyCreationComboBox.SelectedItem.ToString() == "1 Family Per Type (Multiple Files)")
                {
                    //Set the number of steps for the progress bar to the number of rows with families to make
                    uiForm.multiCatCFFEFamiliesProgressBar.Minimum = 0;
                    uiForm.multiCatCFFEFamiliesProgressBar.Maximum = rowsCount - 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Step    = 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Visible = true;

                    //Again, starting at row index 1 because the first is the information about the data types. This loop will produce a family per row. One familly will be opened and saved off multiple times, performing the process of deleting types, adding a default type, and setting parameters before each save
                    for (int i = 1; i < rowsCount; i++)
                    {
                        Transaction t2 = new Transaction(newFamDoc, "MakeNewTypes");
                        t2.Start();
                        //Create a new type using the name of the type in the first column
                        FamilyType newType = newFamMan.NewType(dgv.Rows[i].Cells[0].Value.ToString());
                        //Clean up the family file name by leaving everything that does not pass the regular expression in CleanFileName

                        string saveName = GeneralOperations.CleanFileName(newType.Name);
                        if (saveName != "")
                        {
                            //Assuming nothing went wrong modifying the family name...
                            newFamMan.CurrentType = newType;
                            //Cycle through the columns to set the parameter values this performs the same operations as those above for making 1 family with multiple types
                            for (int j = 1; j < columnsCount; j++)
                            {
                                string paramName = dgv.Columns[j].HeaderText;
                                string paramStorageTypeString = dgv.Rows[0].Cells[j].Value.ToString();
                                var    paramValue             = dgv.Rows[i].Cells[j].Value;
                                if (paramValue.ToString() != "")
                                {
                                    FamilyParameter param     = famParamDict[paramName];
                                    ParameterType   paramType = param.Definition.ParameterType;
                                    RVTOperations.SetFamilyParameterValue(newFamMan, param, paramType, paramStorageTypeString, paramValue, true);
                                }
                            }
                            t2.Commit();

                            //Again, do another transaction to delete the pre-existing type
                            Transaction t3 = new Transaction(newFamDoc, "DeleteOldTypes");
                            t3.Start();
                            foreach (FamilyType type in newFamMan.Types)
                            {
                                newFamMan.CurrentType = type;
                                if (newFamMan.CurrentType.Name != newType.Name)
                                {
                                    newFamMan.DeleteCurrentType();
                                }
                            }
                            t3.Commit();
                            //Save out the family and continue the loop
                            newFamDoc.SaveAs(saveDirectory + "\\" + saveName + ".rfa", saveAsOptions);
                            uiForm.multiCatCFFEFamiliesProgressBar.PerformStep();
                        }
                    }
                    // The family document is finally closed after saving off itself for each row
                    newFamDoc.Close();
                }
                else
                {
                    MessageBox.Show("No Creation Method was selected");
                }

                //Delete the _temp file
                File.Delete(tempFamilyPath);

                //Clean up the backup files too
                List <string> backupFiles = GeneralOperations.GetAllRvtBackupFamilies(uiForm.multiCatCFFEFamilySaveLocation, false);
                GeneralOperations.CleanRfaBackups(backupFiles);
            }
        }
        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
            Color color = e.ObjToSnoop as Color;

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

            LayoutRule layoutRule = e.ObjToSnoop as LayoutRule;

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

            FormatOptions formatOptions = e.ObjToSnoop as FormatOptions;

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

            CurtainGrid curtainGrid = e.ObjToSnoop as CurtainGrid;

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

            CurtainCell curtainCell = e.ObjToSnoop as CurtainCell;

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

            RebarHostData rebarHostData = e.ObjToSnoop as RebarHostData;

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

            Leader leader = e.ObjToSnoop as Leader;

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

            AreaVolumeSettings areaSettings = e.ObjToSnoop as AreaVolumeSettings;

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

            ViewSheetSetting viewSheetSetting = e.ObjToSnoop as ViewSheetSetting;

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

            Autodesk.Revit.UI.Events.DialogBoxData dlgBoxData = e.ObjToSnoop as Autodesk.Revit.UI.Events.DialogBoxData;
            if (dlgBoxData != null)
            {
                Stream(snoopCollector.Data(), dlgBoxData);
                return;
            }

            Construction construct = e.ObjToSnoop as Construction;

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

            FamilyElementVisibility famElemVisib = e.ObjToSnoop as FamilyElementVisibility;

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

            FamilyManager famManager = e.ObjToSnoop as FamilyManager;

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

            FamilyParameter famParam = e.ObjToSnoop as FamilyParameter;

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

            FamilyType famType = e.ObjToSnoop as FamilyType;

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

            MEPSpaceConstruction mepSpaceConstuct = e.ObjToSnoop as MEPSpaceConstruction;

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

            BuildingSiteExportOptions bldSiteExpOptions = e.ObjToSnoop as BuildingSiteExportOptions;

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

            DGNExportOptions dgnExpOptions = e.ObjToSnoop as DGNExportOptions;

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

            DWFExportOptions dwfExpOptions = e.ObjToSnoop as DWFExportOptions;

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

            DWGExportOptions dwgExpOptions = e.ObjToSnoop as DWGExportOptions;

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

            DWGImportOptions dwgImpOptions = e.ObjToSnoop as DWGImportOptions;

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

            FBXExportOptions fbxExpOptions = e.ObjToSnoop as FBXExportOptions;

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

            TrussMemberInfo trussInfo = e.ObjToSnoop as TrussMemberInfo;

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

            VertexIndexPair vertIndPair = e.ObjToSnoop as VertexIndexPair;

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

            PointElementReference ptElemRef = e.ObjToSnoop as PointElementReference;

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

            Autodesk.Revit.DB.Architecture.BoundarySegment boundSeg = e.ObjToSnoop as Autodesk.Revit.DB.Architecture.BoundarySegment;
            if (boundSeg != null)
            {
                Stream(snoopCollector.Data(), boundSeg);
                return;
            }

            PointLocationOnCurve ptLocOnCurve = e.ObjToSnoop as PointLocationOnCurve;

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

            Entity entity = e.ObjToSnoop as Entity;

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

            Field field = e.ObjToSnoop as Field;

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

            ExtensibleStorageField storeagefield = e.ObjToSnoop as ExtensibleStorageField;

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

            IList <Autodesk.Revit.DB.BoundarySegment> boundSegs = e.ObjToSnoop as
                                                                  IList <Autodesk.Revit.DB.BoundarySegment>;

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

            if (e.ObjToSnoop is KeyValuePair <String, String> )
            {
                KeyValuePair <String, String> stringspair = (KeyValuePair <String, String>)e.ObjToSnoop;
                Stream(snoopCollector.Data(), stringspair);
                return;
            }

            Schema schema = e.ObjToSnoop as Schema;

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

            ElementId elemId = e.ObjToSnoop as ElementId;

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

            PlanViewRange plvr = e.ObjToSnoop as PlanViewRange;

            if (plvr != null)
            {
                Stream(snoopCollector.Data(), plvr);
                return;
            }
            //TF
            RebarConstraintsManager rbcm = e.ObjToSnoop as RebarConstraintsManager;

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

            RebarConstrainedHandle rbch = e.ObjToSnoop as RebarConstrainedHandle;

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

            RebarConstraint rbc = e.ObjToSnoop as RebarConstraint;

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

            //TFEND

            if (Utils.IsSupportedType(e.ObjToSnoop) && e.ObjToSnoop != null)
            {
                Utils.StreamWithReflection(snoopCollector.Data(), e.ObjToSnoop.GetType(), e.ObjToSnoop);
            }
        }
        /// <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;
                }
            }
        }
        /// <summary>
        /// The implementation of CreateFrame()
        /// </summary>
        public override void CreateFrame()
        {
            SubTransaction subTransaction = new SubTransaction(m_document);

            subTransaction.Start();

            //create sash referenceplane and exterior referenceplane
            CreateRefPlane refPlaneCreator = new CreateRefPlane();

            if (m_sashPlane == null)
            {
                m_sashPlane = refPlaneCreator.Create(m_document, m_centerPlane, m_rightView, new Autodesk.Revit.DB.XYZ(0, m_wallThickness / 2 - m_windowInset, 0), new Autodesk.Revit.DB.XYZ(0, 0, 1), "Sash");
            }
            if (m_exteriorPlane == null)
            {
                m_exteriorPlane = refPlaneCreator.Create(m_document, m_centerPlane, m_rightView, new Autodesk.Revit.DB.XYZ(0, m_wallThickness / 2, 0), new Autodesk.Revit.DB.XYZ(0, 0, 1), "MyExterior");
            }
            m_document.Regenerate();

            //get the wall in the document and retrieve the exterior face
            List <Wall> walls            = Utility.GetElements <Wall>(m_application, m_document);
            Face        exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);

            if (exteriorWallFace == null)
            {
                return;
            }

            //add dimension between sash reference plane and wall face,and add parameter "Window Inset",label the dimension with window-inset parameter
            Dimension       windowInsetDimension = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, exteriorWallFace);
            FamilyParameter windowInsetPara      = m_familyManager.AddParameter("Window Inset", BuiltInParameterGroup.INVALID, ParameterType.Length, false);

            m_familyManager.Set(windowInsetPara, m_windowInset);
            windowInsetDimension.FamilyLabel = windowInsetPara;

            //create the exterior frame
            double        frameCurveOffset1 = 0.075;
            CurveArray    curveArr1         = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + m_height, m_sillHeight, 0);
            CurveArray    curveArr2         = m_extrusionCreator.CreateCurveArrayByOffset(curveArr1, frameCurveOffset1);
            CurveArrArray curveArrArray1    = new CurveArrArray();

            curveArrArray1.Append(curveArr1);
            curveArrArray1.Append(curveArr2);
            Extrusion extFrame = m_extrusionCreator.NewExtrusion(curveArrArray1, m_sashPlane, m_wallThickness / 2 + m_wallThickness / 12, -m_windowInset);

            extFrame.SetVisibility(CreateVisibility());
            m_document.Regenerate();

            //add alignment between wall face and exterior frame face
            exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);  // Get the face again as the document is regenerated.
            Face            exteriorExtrusionFace1 = GeoHelper.GetExtrusionFace(extFrame, m_rightView, true);
            Face            interiorExtrusionFace1 = GeoHelper.GetExtrusionFace(extFrame, m_rightView, false);
            CreateAlignment alignmentCreator       = new CreateAlignment(m_document);

            alignmentCreator.AddAlignment(m_rightView, exteriorWallFace, exteriorExtrusionFace1);

            //add dimension between sash referenceplane and exterior frame face and lock the dimension
            Dimension extFrameWithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, interiorExtrusionFace1);

            extFrameWithSashPlane.IsLocked = true;
            m_document.Regenerate();

            //create the interior frame
            double     frameCurveOffset2 = 0.125;
            CurveArray curveArr3         = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + m_height, m_sillHeight, 0);
            CurveArray curveArr4         = m_extrusionCreator.CreateCurveArrayByOffset(curveArr3, frameCurveOffset2);

            m_document.Regenerate();

            CurveArrArray curveArrArray2 = new CurveArrArray();

            curveArrArray2.Append(curveArr3);
            curveArrArray2.Append(curveArr4);
            Extrusion intFrame = m_extrusionCreator.NewExtrusion(curveArrArray2, m_sashPlane, m_wallThickness - m_windowInset, m_wallThickness / 2 + m_wallThickness / 12);

            intFrame.SetVisibility(CreateVisibility());
            m_document.Regenerate();

            //add alignment between interior face of wall and interior frame face
            Face interiorWallFace       = GeoHelper.GetWallFace(walls[0], m_rightView, false);
            Face interiorExtrusionFace2 = GeoHelper.GetExtrusionFace(intFrame, m_rightView, false);
            Face exteriorExtrusionFace2 = GeoHelper.GetExtrusionFace(intFrame, m_rightView, true);

            alignmentCreator.AddAlignment(m_rightView, interiorWallFace, interiorExtrusionFace2);

            //add dimension between sash referenceplane and interior frame face and lock the dimension
            Dimension intFrameWithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, exteriorExtrusionFace2);

            intFrameWithSashPlane.IsLocked = true;

            //create the sill frame
            CurveArray    sillCurs       = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + frameCurveOffset1, m_sillHeight, 0);
            CurveArrArray sillCurveArray = new CurveArrArray();

            sillCurveArray.Append(sillCurs);
            Extrusion sillFrame = m_extrusionCreator.NewExtrusion(sillCurveArray, m_sashPlane, -m_windowInset, -m_windowInset - 0.1);

            m_document.Regenerate();

            //add alignment between wall face and sill frame face
            exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);  // Get the face again as the document is regenerated.
            Face sillExtFace = GeoHelper.GetExtrusionFace(sillFrame, m_rightView, false);

            alignmentCreator.AddAlignment(m_rightView, sillExtFace, exteriorWallFace);
            m_document.Regenerate();

            //set subcategories of the frames
            if (m_frameCat != null)
            {
                extFrame.Subcategory  = m_frameCat;
                intFrame.Subcategory  = m_frameCat;
                sillFrame.Subcategory = m_frameCat;
            }
            subTransaction.Commit();
        }
        private bool CreateExtrusion(Document fdoc, FloorProperties fp)
        {
            bool result = false;

            try
            {
                if (true == fdoc.IsFamilyDocument)
                {
                    double maxCircum = 0;//to find out the largest outer loop.
                    List <ReferenceArray> profiles = new List <ReferenceArray>();

                    foreach (EdgeArray edgeArray in fp.EdgeArrayArray)
                    {
                        Curve          curve         = null;
                        List <XYZ>     pointList     = new List <XYZ>();
                        ReferenceArray refArray      = new ReferenceArray();
                        bool           first         = true;
                        double         circumference = 0;

                        foreach (Edge edge in edgeArray)
                        {
                            circumference += edge.ApproximateLength;
                            int pointCount = edge.Tessellate().Count;
                            if (pointCount > 2)//edge from a circular face
                            {
                                IList <XYZ> tPoints = edge.Tessellate();
                                tPoints.RemoveAt(tPoints.Count - 1);
                                foreach (XYZ point in tPoints)
                                {
                                    XYZ tempPoint = new XYZ(point.X, point.Y, 0);
                                    pointList.Add(tempPoint);
                                }
                            }
                            else if (pointCount == 2)
                            {
                                curve = edge.AsCurve();
#if RELEASE2013
                                XYZ point = curve.get_EndPoint(0);
#elif RELEASE2014 || RELEASE2015 || RELEASE2016
                                XYZ point = curve.GetEndPoint(0);
#endif
                                XYZ tempPoint = new XYZ(point.X, point.Y, 0);
                                if (first)
                                {
                                    pointList.Add(tempPoint); first = false;
                                }
                                else if (pointList[pointList.Count - 1].DistanceTo(tempPoint) > 0.0026)
                                {
                                    pointList.Add(tempPoint);
                                }
                            }
                        }

                        if (maxCircum == 0)
                        {
                            maxCircum = circumference;
                        }
                        else if (maxCircum < circumference)
                        {
                            maxCircum = circumference;
                        }

                        int num = pointList.Count;
                        if (num > 0)
                        {
                            Plane plane = fdoc.Application.Create.NewPlane(XYZ.BasisZ, new XYZ(0, 0, 0));
#if RELEASE2013
                            SketchPlane skPlane = fdoc.FamilyCreate.NewSketchPlane(plane);
#elif RELEASE2014 || RELEASE2015 || RELEASE2016
                            SketchPlane skPlane = SketchPlane.Create(fdoc, plane);
#endif

                            for (int i = 0; i < num; i++)
                            {
                                if (i == num - 1)
                                {
#if RELEASE2013
                                    curve = fdoc.Application.Create.NewLineBound(pointList[i], pointList[0]);
#elif RELEASE2014 || RELEASE2015 || RELEASE2016
                                    curve = Autodesk.Revit.DB.Line.CreateBound(pointList[i], pointList[0]);
#endif
                                }
                                else
                                {
#if RELEASE2013
                                    curve = fdoc.Application.Create.NewLineBound(pointList[i], pointList[i + 1]);
#elif RELEASE2014 || RELEASE2015 || RELEASE2016
                                    curve = Autodesk.Revit.DB.Line.CreateBound(pointList[i], pointList[i + 1]);
#endif
                                }
                                ModelCurve modelCurve = fdoc.FamilyCreate.NewModelCurve(curve, skPlane);
                                refArray.Append(modelCurve.GeometryCurve.Reference);
                            }
                            //first index of profile list will be the outer loop
                            if (maxCircum == circumference)
                            {
                                profiles.Insert(0, refArray);
                            }
                            else
                            {
                                profiles.Add(refArray);
                            }
                        }
                    }

                    if (profiles.Count > 0)
                    {
                        XYZ             direction = new XYZ(0, 0, fp.Height);
                        FamilyParameter fparam    = fdoc.FamilyManager.get_Parameter("Height");
                        fdoc.FamilyManager.Set(fparam, fp.Height);

                        for (int i = 0; i < profiles.Count; i++)
                        {
                            Autodesk.Revit.DB.Form solidForm = fdoc.FamilyCreate.NewExtrusionForm(true, profiles[i], direction);
                            CreateHeightLabel(fdoc, solidForm);

                            if (i > 0)
                            {
                                Parameter param = solidForm.get_Parameter(BuiltInParameter.ELEMENT_IS_CUTTING);
                                param.Set(1); //void form
                            }
                        }
                    }
                    result = true;
                }
                else
                {
                    result = false;
                    throw new Exception("Please open a Family document before invoking this command.");
                }
                return(result);
            }
            catch (Exception ex)
            {
                result = false;
                MessageBox.Show("Failed to create an extruded form.\n\nFloorName: " + fp.TypeName + "  FloorLevel: " + fp.Level + "\nBoundary lines of floor cannot create a profile..\n\n" + ex.Message, "MassCreator: CreateExtrusion", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(result);
            }
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            if (!doc.IsFamilyDocument)
            {
                message =
                    "Please run this command in a family document.";
            }
            else
            {
                FamilyManager mgr = doc.FamilyManager;

                int n = mgr.Parameters.Size;

                Debug.Print(
                    "\nFamily {0} has {1} parameter{2}.",
                    doc.Title, n, Util.PluralSuffix(n));

                Dictionary <string, FamilyParameter> fps
                    = new Dictionary <string, FamilyParameter>(n);

                foreach (FamilyParameter fp in mgr.Parameters)
                {
                    string name = fp.Definition.Name;
                    fps.Add(name, fp);

                    #region Look at associated parameters
#if LOOK_AT_ASSOCIATED_PARAMETERS
                    ParameterSet ps = fp.AssociatedParameters;
                    n = ps.Size;

                    string values = string.Empty;
                    foreach (Parameter p in ps)
                    {
                        if (0 == values.Length)
                        {
                            values = " ";
                        }
                        else
                        {
                            values += ", ";
                        }
                        values += p.AsValueString();
                    }

                    Debug.Print(
                        "Parameter {0} has {1} associated parameter{2}{3}{4}.",
                        name,
                        n,
                        PluralSuffix(n),
                        (0 < n ? ":" : ""),
                        values);
#endif // LOOK_AT_ASSOCIATED_PARAMETERS
                    #endregion // Look at associated parameters
                }
                List <string> keys = new List <string>(fps.Keys);
                keys.Sort();

                n = mgr.Types.Size;

                Debug.Print(
                    "Family {0} has {1} type{2}{3}",
                    doc.Title,
                    n,
                    Util.PluralSuffix(n),
                    Util.DotOrColon(n));

                foreach (FamilyType t in mgr.Types)
                {
                    string name = t.Name;
                    Debug.Print("  {0}:", name);
                    foreach (string key in keys)
                    {
                        FamilyParameter fp = fps[key];
                        if (t.HasValue(fp))
                        {
                            string value
                                = FamilyParamValueString(t, fp, doc);

                            Debug.Print("    {0} = {1}", key, value);
                        }
                    }
                }
            }

            #region Exercise ExtractPartAtomFromFamilyFile

            // by the way, here is a completely different way to
            // get at all the parameter values, and all the other
            // family information as well:

            bool exercise_this_method = false;

            if (doc.IsFamilyDocument && exercise_this_method)
            {
                string path = doc.PathName;
                if (0 < path.Length)
                {
                    app.Application.ExtractPartAtomFromFamilyFile(
                        path, path + ".xml");
                }
            }
            #endregion // Exercise ExtractPartAtomFromFamilyFile

            return(Result.Failed);
        }
 public Pomocna(FamilyParameter familyParameter)
 {
     this.familyParameter = familyParameter;
 }
        public void settingFamilyParamentersValue(Document doc, string familyFilePath, string parameterFilePath)
        {
            //读取xls文件
            ExcelHelper ExcelHelper = new ExcelHelper();
            DataTable   dt          = ExcelHelper.Reading_Excel_Information(parameterFilePath);

            //获取参数集
            FamilyParameterSet rfadocParas         = doc.FamilyManager.Parameters;
            List <string>      rfadocParasListName = new List <string>();

            foreach (FamilyParameter rfadocPara in rfadocParas)
            {
                rfadocParasListName.Add(rfadocPara.Definition.Name);
            }

            #region
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                List <string> ls_ParameterNames = new List <string>();
                //ls_ParameterNames.Add(dt.Rows[i][0].ToString);
            }
            #endregion

            #region 族参数操作1
            FamilyManager familyMgr = doc.FamilyManager;

            //清空族内所有类型 仅保留默认族类型
            int typesizes = familyMgr.Types.Size;
            if (familyMgr.Types.Size > 1 && familyMgr.Types.Size != 0)
            {
                for (int typenumber = 0; typenumber < typesizes - 1; typenumber++)
                {
                    if (familyMgr.CurrentType != null)
                    {
                        Transaction DeleteType = new Transaction(doc, "DeleteType");
                        DeleteType.Start();
                        familyMgr.DeleteCurrentType();
                        DeleteType.Commit();
                    }
                }
            }

            //清空族内所有参数条目
            foreach (FamilyParameter fp in familyMgr.Parameters)
            {
                if (fp.Definition.ParameterGroup == BuiltInParameterGroup.PG_ELECTRICAL)
                {
                    Transaction RemoveParameter = new Transaction(doc, "RemoveParameter");
                    RemoveParameter.Start();
                    familyMgr.RemoveParameter(fp);
                    RemoveParameter.Commit();
                }
            }

            //开始添加

            Transaction addParameter = new Transaction(doc, "AddParameters");
            addParameter.Start();

            List <string> paraNames   = new List <string>();
            List <bool>   isInstances = new List <bool>();
            List <string> paravalues  = new List <string>();
            //设置族参数的类别和类型
            BuiltInParameterGroup paraGroup   = BuiltInParameterGroup.PG_ELECTRICAL;
            BuiltInParameterGroup paraGroupEx = BuiltInParameterGroup.PG_GENERAL;
            ParameterType         paraType    = ParameterType.Text;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string paraName = dt.Rows[i]["paraname"].ToString();
                paraNames.Add(paraName);

                //设置族参数为实例参数
                bool isInstance = true;
                if (dt.Rows[i]["paratag"].ToString() == "是")
                {
                    isInstance = true;
                }
                else
                {
                    isInstance = false;
                }
                isInstances.Add(isInstance);

                paravalues.Add(dt.Rows[i]["paravalue"].ToString());
            }

            for (int k = 0; k < paraNames.Count(); k++)
            {
                int tag = 0;
                if (paraNames[k].Contains("M_") || paraNames[k].Contains("D_") || paraNames[k].Contains("设计-") || paraNames[k].Contains("管理-"))
                {
                    FamilyParameter newParameter = familyMgr.AddParameter(paraNames[k], paraGroup, paraType, isInstances[k]);
                    //创建族参数(每个参数两秒)
                    familyMgr.Set(newParameter, paravalues[k]);
                }
                else
                {
                    foreach (var fpln in rfadocParasListName)
                    {
                        if (paraNames[k] == fpln)
                        {
                            tag = 1;
                        }
                    }
                    if (tag == 1)
                    {
                        continue;
                    }
                    else
                    {
                        FamilyParameter newParameter = familyMgr.AddParameter(paraNames[k], paraGroupEx, paraType, isInstances[k]);
                    }
                }
            }
            SaveOptions opt = new SaveOptions();
            //doc.Save(opt);
            //doc.SaveAs(@"D:\"+);
            //doc.Close();
            addParameter.Commit();
            #endregion
        }
Exemple #22
0
        //----------------------------------------------------------
        public string Get_Parameter_Information_Family(FamilyParameter para, Document familyDoc, FamilyManager manager, All_Data myAll_Data)
        {
            string defValue = string.Empty;

            try
            {
                switch (para.StorageType)
                {
                case StorageType.Double:
                    if (para.DisplayUnitType.ToString() == "DUT_DECIMAL_DEGREES")
                    {
                        defValue = Math.Round((double)manager.CurrentType.AsDouble(para) * myAll_Data.list_unit_value_data[5], mySource.lam_tron).ToString();
                    }
                    else
                    {
                        defValue = Math.Round((double)manager.CurrentType.AsDouble(para) * myAll_Data.list_unit_value_data[2], mySource.lam_tron).ToString();
                    }
                    break;

                case StorageType.ElementId:
                    ElementId id = manager.CurrentType.AsElementId(para);
                    if (id.IntegerValue >= 0)
                    {
                        defValue = familyDoc.GetElement(id).Name;
                    }
                    else
                    {
                        defValue = id.IntegerValue.ToString();
                    }
                    break;

                case StorageType.Integer:
                    if (ParameterType.YesNo == para.Definition.ParameterType)
                    {
                        if (manager.CurrentType.AsInteger(para) == 0)
                        {
                            defValue = "False";
                        }
                        else
                        {
                            defValue = "True";
                        }
                    }
                    else
                    {
                        defValue = manager.CurrentType.AsInteger(para).ToString();
                    }
                    break;

                case StorageType.String:
                    if (manager.CurrentType.AsString(para) != null)
                    {
                        defValue = manager.CurrentType.AsString(para);
                    }
                    else
                    {
                        defValue = "";
                    }
                    break;

                default:
                    defValue = "Unexposed parameter.";
                    break;
                }
            }
            catch (Exception)
            {
            }
            return(defValue);
        }
        public Document settingParamenters(string eleName, string eleXPath, string elefName, Document Revit_Doc)
        {
            //MessageBox.Show(elefName);
            //根据名称在工程文件中查找出对应族
            FilteredElementCollector allElements  = new FilteredElementCollector(Revit_Doc);
            ElementClassFilter       familyFilter = new ElementClassFilter(typeof(Family));

            allElements = allElements.WherePasses(familyFilter);
            var filterFamilyList = from f in allElements
                                   where f.Name.ToString() == elefName
                                   select f as Family;
            //MessageBox.Show(filterFamilyList.ToList<Family>()[0].ToString());

            //allElements = new FilteredElementCollector(Revit_Doc);
            //ElementClassFilter familySymbolFilter = new ElementClassFilter(typeof(FamilySymbol));
            //allElements = allElements.WherePasses(familySymbolFilter);
            //var filterList = from f in allElements
            //                 where f.Name.ToString() == eleName && (f as FamilySymbol).Family.ToString() == elefName
            //                 select (f as FamilySymbol).Family ;
            //Family filtedFamily = filterList.ToList<Family>().FirstOrDefault();
            ////if (filterList != null)
            ////{ MessageBox.Show(filterList.ToList<Family>()[0].ToString()); }

            Family filtedFamily = filterFamilyList.ToList <Family>().FirstOrDefault();;

            MessageBox.Show(filtedFamily.Name.ToString());
            //---------------------------------------------------
            //MessageBox.Show(eleName);
            //if (filtedFamily == null)
            //{ MessageBox.Show("filtedFamily is null!!"); }
            //---------------------------------------------------
            //
            Document familyDoc = Revit_Doc.EditFamily(filtedFamily);

            if (null != familyDoc && familyDoc.IsFamilyDocument == true)
            {
                DataTable xdte = new DataTable();
                //读取xls文件
                ExcelHelper ExcelHelper = new ExcelHelper();
                DataTable   xdt         = ExcelHelper.Reading_Excel_Information(eleXPath);
                //获取参数集
                FamilyParameterSet rfadocParas         = familyDoc.FamilyManager.Parameters;
                List <string>      rfadocParasListName = new List <string>();
                foreach (FamilyParameter rfadocPara in rfadocParas)
                {
                    rfadocParasListName.Add(rfadocPara.Definition.Name);
                }

                FamilyManager familyMgr = familyDoc.FamilyManager;

                if (clearsymbol == true)
                {
                    //清空族内所有类型 仅保留默认族类型
                    int typesizes = familyMgr.Types.Size;
                    if (familyMgr.Types.Size > 1 && familyMgr.Types.Size != 0)
                    {
                        for (int typenumber = 0; typenumber < typesizes - 1; typenumber++)
                        {
                            if (familyMgr.CurrentType != null)
                            {
                                Transaction DeleteType = new Transaction(familyDoc, "DeleteType");
                                DeleteType.Start();
                                familyMgr.DeleteCurrentType();
                                DeleteType.Commit();
                            }
                        }
                    }
                }

                if (clearpara == true)
                {
                    //清空族内所有参数条目
                    foreach (FamilyParameter fp in familyMgr.Parameters)
                    {
                        if (fp.Definition.ParameterGroup == BuiltInParameterGroup.PG_ELECTRICAL)
                        {
                            Transaction RemoveParameter = new Transaction(familyDoc, "RemoveParameter");
                            RemoveParameter.Start();
                            familyMgr.RemoveParameter(fp);
                            RemoveParameter.Commit();
                        }
                    }
                }
                //开始添加

                Transaction addParameter = new Transaction(familyDoc, "AddParameters");
                addParameter.Start();

                string paraname = null;
                BuiltInParameterGroup paragroup = BuiltInParameterGroup.PG_ELECTRICAL;;
                ParameterType         paraType  = ParameterType.Text;;
                bool isInstance = false;

                string        paravalue         = null;
                List <string> distinctparanames = new List <string>();

                //判断xls表中与原有rfa文件内重复的条目  放入distinctparanames列表
                for (int i = 0; i < xdt.Rows.Count; i++)
                {
                    foreach (FamilyParameter fp in familyMgr.Parameters)
                    {
                        if (fp.Definition.Name == xdt.Rows[i]["paraname"].ToString())
                        {
                            distinctparanames.Add(fp.Definition.Name);
                            MessageBox.Show(fp.Definition.Name);
                        }
                    }
                }
                //遍历xls添加属性条目
                for (int i = 0; i < xdt.Rows.Count; i++)
                {
                    //获取表中条目名称判断是否重复 重复则继续下一次循环
                    paraname = xdt.Rows[i]["paraname"].ToString();

                    foreach (string disstr in distinctparanames)
                    {
                        if (disstr == paraname)
                        {
                            continue;
                        }
                    }

                    //通过的条目名称
                    if (xdt.Rows[i]["paragroup"] == null)
                    {
                        paragroup = BuiltInParameterGroup.PG_ELECTRICAL;
                    }
                    else
                    {
                        #region  参数分组对照  用于RevitAPI2016A
                        switch (xdt.Rows[i]["paragroup"].ToString())
                        {
                        case "PG_RELEASES_MEMBER_FORCES": paragroup = BuiltInParameterGroup.PG_RELEASES_MEMBER_FORCES; break;

                        case "PG_SECONDARY_END": paragroup = BuiltInParameterGroup.PG_SECONDARY_END; break;

                        case "PG_PRIMARY_END": paragroup = BuiltInParameterGroup.PG_PRIMARY_END; break;

                        case "PG_MOMENTS": paragroup = BuiltInParameterGroup.PG_MOMENTS; break;

                        case "PG_FORCES": paragroup = BuiltInParameterGroup.PG_FORCES; break;

                        case "PG_FABRICATION_PRODUCT_DATA": paragroup = BuiltInParameterGroup.PG_GEOMETRY_POSITIONING; break;

                        case "PG_REFERENCE": paragroup = BuiltInParameterGroup.PG_REFERENCE; break;

                        case "PG_GEOMETRY_POSITIONING": paragroup = BuiltInParameterGroup.PG_GEOMETRY_POSITIONING; break;

                        case "PG_DIVISION_GEOMETRY": paragroup = BuiltInParameterGroup.PG_DIVISION_GEOMETRY; break;

                        case "PG_SEGMENTS_FITTINGS": paragroup = BuiltInParameterGroup.PG_SEGMENTS_FITTINGS; break;

                        case "PG_CONTINUOUSRAIL_END_TOP_EXTENSION": paragroup = BuiltInParameterGroup.PG_CONTINUOUSRAIL_END_TOP_EXTENSION; break;

                        case "PG_CONTINUOUSRAIL_BEGIN_BOTTOM_EXTENSION": paragroup = BuiltInParameterGroup.PG_CONTINUOUSRAIL_BEGIN_BOTTOM_EXTENSION; break;

                        case "PG_STAIRS_WINDERS": paragroup = BuiltInParameterGroup.PG_STAIRS_WINDERS; break;

                        case "PG_STAIRS_SUPPORTS": paragroup = BuiltInParameterGroup.PG_STAIRS_SUPPORTS; break;

                        case "PG_STAIRS_OPEN_END_CONNECTION": paragroup = BuiltInParameterGroup.PG_STAIRS_OPEN_END_CONNECTION; break;

                        case "PG_RAILING_SYSTEM_SECONDARY_FAMILY_HANDRAILS": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SECONDARY_FAMILY_HANDRAILS; break;

                        case "PG_TERMINTATION": paragroup = BuiltInParameterGroup.PG_TERMINTATION; break;

                        case "PG_STAIRS_TREADS_RISERS": paragroup = BuiltInParameterGroup.PG_STAIRS_TREADS_RISERS; break;

                        case "PG_STAIRS_CALCULATOR_RULES": paragroup = BuiltInParameterGroup.PG_STAIRS_CALCULATOR_RULES; break;

                        case "PG_SPLIT_PROFILE_DIMENSIONS": paragroup = BuiltInParameterGroup.PG_SPLIT_PROFILE_DIMENSIONS; break;

                        case "PG_LENGTH": paragroup = BuiltInParameterGroup.PG_LENGTH; break;

                        case "PG_NODES": paragroup = BuiltInParameterGroup.PG_NODES; break;

                        case "PG_ANALYTICAL_PROPERTIES": paragroup = BuiltInParameterGroup.PG_ANALYTICAL_PROPERTIES; break;

                        case "PG_ANALYTICAL_ALIGNMENT": paragroup = BuiltInParameterGroup.PG_ANALYTICAL_ALIGNMENT; break;

                        case "PG_SYSTEMTYPE_RISEDROP": paragroup = BuiltInParameterGroup.PG_SYSTEMTYPE_RISEDROP; break;

                        case "PG_LINING": paragroup = BuiltInParameterGroup.PG_LINING; break;

                        case "PG_INSULATION": paragroup = BuiltInParameterGroup.PG_INSULATION; break;

                        case "PG_OVERALL_LEGEND": paragroup = BuiltInParameterGroup.PG_OVERALL_LEGEND; break;

                        case "PG_VISIBILITY": paragroup = BuiltInParameterGroup.PG_VISIBILITY; break;

                        case "PG_SUPPORT": paragroup = BuiltInParameterGroup.PG_SUPPORT; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_V_GRID": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_V_GRID; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_U_GRID": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_U_GRID; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_POSTS": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_POSTS; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_PATTERN_REMAINDER": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_PATTERN_REMAINDER; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_PATTERN_REPEAT": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_PATTERN_REPEAT; break;

                        case "PG_RAILING_SYSTEM_FAMILY_SEGMENT_PATTERN": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_FAMILY_SEGMENT_PATTERN; break;

                        case "PG_RAILING_SYSTEM_FAMILY_HANDRAILS": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_FAMILY_HANDRAILS; break;

                        case "PG_RAILING_SYSTEM_FAMILY_TOP_RAIL": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_FAMILY_TOP_RAIL; break;

                        case "PG_CONCEPTUAL_ENERGY_DATA_BUILDING_SERVICES": paragroup = BuiltInParameterGroup.PG_CONCEPTUAL_ENERGY_DATA_BUILDING_SERVICES; break;

                        case "PG_DATA": paragroup = BuiltInParameterGroup.PG_DATA; break;

                        case "PG_ELECTRICAL_CIRCUITING": paragroup = BuiltInParameterGroup.PG_ELECTRICAL_CIRCUITING; break;

                        case "PG_GENERAL": paragroup = BuiltInParameterGroup.PG_GENERAL; break;

                        case "PG_FLEXIBLE": paragroup = BuiltInParameterGroup.PG_FLEXIBLE; break;

                        case "PG_ENERGY_ANALYSIS_CONCEPTUAL_MODEL": paragroup = BuiltInParameterGroup.PG_ENERGY_ANALYSIS_CONCEPTUAL_MODEL; break;

                        case "PG_ENERGY_ANALYSIS_DETAILED_MODEL": paragroup = BuiltInParameterGroup.PG_ENERGY_ANALYSIS_DETAILED_MODEL; break;

                        case "PG_ENERGY_ANALYSIS_DETAILED_AND_CONCEPTUAL_MODELS": paragroup = BuiltInParameterGroup.PG_ENERGY_ANALYSIS_DETAILED_AND_CONCEPTUAL_MODELS; break;

                        case "PG_FITTING": paragroup = BuiltInParameterGroup.PG_FITTING; break;

                        case "PG_CONCEPTUAL_ENERGY_DATA": paragroup = BuiltInParameterGroup.PG_CONCEPTUAL_ENERGY_DATA; break;

                        case "PG_AREA": paragroup = BuiltInParameterGroup.PG_AREA; break;

                        case "PG_ADSK_MODEL_PROPERTIES": paragroup = BuiltInParameterGroup.PG_ADSK_MODEL_PROPERTIES; break;

                        case "PG_CURTAIN_GRID_V": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_V; break;

                        case "PG_CURTAIN_GRID_U": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_U; break;

                        case "PG_DISPLAY": paragroup = BuiltInParameterGroup.PG_DISPLAY; break;

                        case "PG_ANALYSIS_RESULTS": paragroup = BuiltInParameterGroup.PG_ANALYSIS_RESULTS; break;

                        case "PG_SLAB_SHAPE_EDIT": paragroup = BuiltInParameterGroup.PG_SLAB_SHAPE_EDIT; break;

                        case "PG_LIGHT_PHOTOMETRICS": paragroup = BuiltInParameterGroup.PG_LIGHT_PHOTOMETRICS; break;

                        case "PG_PATTERN_APPLICATION": paragroup = BuiltInParameterGroup.PG_PATTERN_APPLICATION; break;

                        case "PG_GREEN_BUILDING": paragroup = BuiltInParameterGroup.PG_GREEN_BUILDING; break;

                        case "PG_PROFILE_2": paragroup = BuiltInParameterGroup.PG_PROFILE_2; break;

                        case "PG_PROFILE_1": paragroup = BuiltInParameterGroup.PG_PROFILE_1; break;

                        case "PG_PROFILE": paragroup = BuiltInParameterGroup.PG_PROFILE; break;

                        case "PG_TRUSS_FAMILY_BOTTOM_CHORD": paragroup = BuiltInParameterGroup.PG_TRUSS_FAMILY_BOTTOM_CHORD; break;

                        case "PG_TRUSS_FAMILY_TOP_CHORD": paragroup = BuiltInParameterGroup.PG_TRUSS_FAMILY_TOP_CHORD; break;

                        case "PG_TRUSS_FAMILY_DIAG_WEB": paragroup = BuiltInParameterGroup.PG_TRUSS_FAMILY_DIAG_WEB; break;

                        case "PG_TRUSS_FAMILY_VERT_WEB": paragroup = BuiltInParameterGroup.PG_TRUSS_FAMILY_VERT_WEB; break;

                        case "PG_TITLE": paragroup = BuiltInParameterGroup.PG_TITLE; break;

                        case "PG_FIRE_PROTECTION": paragroup = BuiltInParameterGroup.PG_FIRE_PROTECTION; break;

                        case "PG_ROTATION_ABOUT": paragroup = BuiltInParameterGroup.PG_ROTATION_ABOUT; break;

                        case "PG_TRANSLATION_IN": paragroup = BuiltInParameterGroup.PG_TRANSLATION_IN; break;

                        case "PG_ANALYTICAL_MODEL": paragroup = BuiltInParameterGroup.PG_ANALYTICAL_MODEL; break;

                        case "PG_REBAR_ARRAY": paragroup = BuiltInParameterGroup.PG_REBAR_ARRAY; break;

                        case "PG_REBAR_SYSTEM_LAYERS": paragroup = BuiltInParameterGroup.PG_REBAR_SYSTEM_LAYERS; break;

                        case "PG_CURTAIN_GRID": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID; break;

                        case "PG_CURTAIN_MULLION_2": paragroup = BuiltInParameterGroup.PG_CURTAIN_MULLION_2; break;

                        case "PG_CURTAIN_MULLION_HORIZ": paragroup = BuiltInParameterGroup.PG_CURTAIN_MULLION_HORIZ; break;

                        case "PG_CURTAIN_MULLION_1": paragroup = BuiltInParameterGroup.PG_CURTAIN_MULLION_1; break;

                        case "PG_CURTAIN_MULLION_VERT": paragroup = BuiltInParameterGroup.PG_CURTAIN_MULLION_VERT; break;

                        case "PG_CURTAIN_GRID_2": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_2; break;

                        case "PG_CURTAIN_GRID_HORIZ": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_HORIZ; break;

                        case "PG_CURTAIN_GRID_1": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_1; break;

                        case "PG_CURTAIN_GRID_VERT": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_VERT; break;

                        case "PG_IFC": paragroup = BuiltInParameterGroup.PG_IFC; break;

                        case "PG_AELECTRICAL": paragroup = BuiltInParameterGroup.PG_AELECTRICAL; break;

                        case "PG_ENERGY_ANALYSIS": paragroup = BuiltInParameterGroup.PG_ENERGY_ANALYSIS; break;

                        case "PG_STRUCTURAL_ANALYSIS": paragroup = BuiltInParameterGroup.PG_STRUCTURAL_ANALYSIS; break;

                        case "PG_MECHANICAL_AIRFLOW": paragroup = BuiltInParameterGroup.PG_MECHANICAL_AIRFLOW; break;

                        case "PG_MECHANICAL_LOADS": paragroup = BuiltInParameterGroup.PG_MECHANICAL_LOADS; break;

                        case "PG_ELECTRICAL_LOADS": paragroup = BuiltInParameterGroup.PG_ELECTRICAL_LOADS; break;

                        case "PG_ELECTRICAL_LIGHTING": paragroup = BuiltInParameterGroup.PG_ELECTRICAL_LIGHTING; break;

                        case "PG_TEXT": paragroup = BuiltInParameterGroup.PG_TEXT; break;

                        case "PG_VIEW_CAMERA": paragroup = BuiltInParameterGroup.PG_VIEW_CAMERA; break;

                        case "PG_VIEW_EXTENTS": paragroup = BuiltInParameterGroup.PG_VIEW_EXTENTS; break;

                        case "PG_PATTERN": paragroup = BuiltInParameterGroup.PG_PATTERN; break;

                        case "PG_CONSTRAINTS": paragroup = BuiltInParameterGroup.PG_CONSTRAINTS; break;

                        case "PG_PHASING": paragroup = BuiltInParameterGroup.PG_PHASING; break;

                        case "PG_MECHANICAL": paragroup = BuiltInParameterGroup.PG_MECHANICAL; break;

                        case "PG_STRUCTURAL": paragroup = BuiltInParameterGroup.PG_STRUCTURAL; break;

                        case "PG_PLUMBING": paragroup = BuiltInParameterGroup.PG_PLUMBING; break;

                        case "PG_ELECTRICAL": paragroup = BuiltInParameterGroup.PG_ELECTRICAL; break;

                        case "PG_STAIR_STRINGERS": paragroup = BuiltInParameterGroup.PG_STAIR_STRINGERS; break;

                        case "PG_STAIR_RISERS": paragroup = BuiltInParameterGroup.PG_STAIR_RISERS; break;

                        case "PG_STAIR_TREADS": paragroup = BuiltInParameterGroup.PG_STAIR_TREADS; break;

                        case "PG_MATERIALS": paragroup = BuiltInParameterGroup.PG_MATERIALS; break;

                        case "PG_GRAPHICS": paragroup = BuiltInParameterGroup.PG_GRAPHICS; break;

                        case "PG_CONSTRUCTION": paragroup = BuiltInParameterGroup.PG_CONSTRUCTION; break;

                        case "PG_GEOMETRY": paragroup = BuiltInParameterGroup.PG_GEOMETRY; break;

                        case "PG_IDENTITY_DATA": paragroup = BuiltInParameterGroup.PG_IDENTITY_DATA; break;

                        case "INVALID": paragroup = BuiltInParameterGroup.INVALID; break;
                        }
                        #endregion
                    }
                    if (xdt.Rows[i]["paratype"] == null)
                    {
                        paraType = ParameterType.Text;
                    }
                    else
                    {
                        #region 参数类型对照 用于RevitAPI2016
                        switch (xdt.Rows[i]["paratype"].ToString())
                        {
                        case "Text": paraType = ParameterType.Text; break;

                            //case "Invalid": paraType = ParameterType.Invalid; break;
                            //case "Integer": paraType = ParameterType.Integer; break;

                            //case "Number": paraType = ParameterType.Number; break;
                            //case "Length": paraType = ParameterType.Length; break;
                            //case "Volume": paraType = ParameterType.Volume; break;
                            //case "Area": paraType = ParameterType.Area; break;
                            //case "Angle": paraType = ParameterType.Angle; break;
                            //case "URL": paraType = ParameterType.URL; break;
                            //case "Material": paraType = ParameterType.Material; break;
                            //case "YesNo": paraType = ParameterType.YesNo; break;
                            //case "Force": paraType = ParameterType.Force; break;
                            //case "NumberOfPoles": paraType = ParameterType.NumberOfPoles; break;
                            //case "AreaForce": paraType = ParameterType.AreaForce; break;
                            //case "Moment": paraType = ParameterType.Moment; break;
                            //case "FixtureUnit": paraType = ParameterType.FixtureUnit; break;
                            //case "FamilyType": paraType = ParameterType.FamilyType; break;
                            //case "LoadClassification": paraType = ParameterType.LoadClassification; break;
                            //case "Image": paraType = ParameterType.Image; break;
                            //case "HVACDensity": paraType = ParameterType.HVACDensity; break;
                            //case "HVACEnergy": paraType = ParameterType.HVACEnergy; break;
                            //case "HVACFriction": paraType = ParameterType.HVACFriction; break;
                            //case "HVACPower": paraType = ParameterType.HVACPower; break;
                            //case "HVACPowerDensity": paraType = ParameterType.HVACPowerDensity; break;
                            //case "HVACPressure": paraType = ParameterType.HVACPressure; break;
                            //case "HVACTemperature": paraType = ParameterType.HVACTemperature; break;
                            //case "HVACVelocity": paraType = ParameterType.HVACVelocity; break;
                            //case "HVACAirflow": paraType = ParameterType.HVACAirflow; break;
                            //case "HVACDuctSize": paraType = ParameterType.HVACDuctSize; break;
                            //case "HVACCrossSection": paraType = ParameterType.HVACCrossSection; break;
                            //case "HVACHeatGain": paraType = ParameterType.HVACHeatGain; break;
                            //case "ElectricalCurrent": paraType = ParameterType.ElectricalCurrent; break;
                            //case "ElectricalPotential": paraType = ParameterType.ElectricalPotential; break;
                            //case "ElectricalFrequency": paraType = ParameterType.ElectricalFrequency; break;
                            //case "ElectricalIlluminance": paraType = ParameterType.ElectricalIlluminance; break;
                            //case "ElectricalLuminousFlux": paraType = ParameterType.ElectricalLuminousFlux; break;
                            //case "ElectricalPower": paraType = ParameterType.ElectricalPower; break;
                            //case "HVACRoughness": paraType = ParameterType.HVACRoughness; break;
                            //case "ElectricalApparentPower": paraType = ParameterType.ElectricalApparentPower; break;
                            //case "ElectricalPowerDensity": paraType = ParameterType.ElectricalPowerDensity; break;
                            //case "PipingDensity": paraType = ParameterType.PipingDensity; break;
                            //case "PipingFlow": paraType = ParameterType.PipingFlow; break;
                            //case "PipingFriction": paraType = ParameterType.PipingFriction; break;
                            //case "PipingPressure": paraType = ParameterType.PipingPressure; break;
                            //case "PipingTemperature": paraType = ParameterType.PipingTemperature; break;
                            //case "PipingVelocity": paraType = ParameterType.PipingVelocity; break;
                            //case "PipingViscosity": paraType = ParameterType.PipingViscosity; break;
                            //case "PipeSize": paraType = ParameterType.PipeSize; break;
                            //case "PipingRoughness": paraType = ParameterType.PipingRoughness; break;
                            //case "Stress": paraType = ParameterType.Stress; break;
                            //case "UnitWeight": paraType = ParameterType.UnitWeight; break;
                            //case "ThermalExpansion": paraType = ParameterType.ThermalExpansion; break;
                            //case "LinearMoment": paraType = ParameterType.LinearMoment; break;
                            //case "ForcePerLength": paraType = ParameterType.ForcePerLength; break;
                            //case "ForceLengthPerAngle": paraType = ParameterType.ForceLengthPerAngle; break;
                            //case "LinearForcePerLength": paraType = ParameterType.LinearForcePerLength; break;
                            //case "LinearForceLengthPerAngle": paraType = ParameterType.LinearForceLengthPerAngle; break;
                            //case "AreaForcePerLength": paraType = ParameterType.AreaForcePerLength; break;
                            //case "PipingVolume": paraType = ParameterType.PipingVolume; break;
                            //case "HVACViscosity": paraType = ParameterType.HVACViscosity; break;
                            //case "HVACCoefficientOfHeatTransfer": paraType = ParameterType.HVACCoefficientOfHeatTransfer; break;
                            //case "HVACAirflowDensity": paraType = ParameterType.HVACAirflowDensity; break;
                            //case "Slope": paraType = ParameterType.Slope; break;
                            //case "HVACCoolingLoad": paraType = ParameterType.HVACCoolingLoad; break;
                            //case "HVACCoolingLoadDividedByArea": paraType = ParameterType.HVACCoolingLoadDividedByArea; break;
                            //case "HVACCoolingLoadDividedByVolume": paraType = ParameterType.HVACCoolingLoadDividedByVolume; break;
                            //case "HVACHeatingLoad": paraType = ParameterType.HVACHeatingLoad; break;
                            //case "HVACHeatingLoadDividedByArea": paraType = ParameterType.HVACHeatingLoadDividedByArea; break;
                            //case "Weight": paraType = ParameterType.Weight; break;
                        }
                        #endregion
                    }
                    if (xdt.Rows[i]["paratag"].ToString() == "是")
                    {
                        isInstance = true;
                    }
                    else if (xdt.Rows[i]["paratag"].ToString() == "否")
                    {
                        isInstance = false;
                    }
                    if (xdt.Rows[i]["paravalue"].ToString() == null)
                    {
                        paravalue = "NA";
                    }
                    else
                    {
                        paravalue = xdt.Rows[i]["paravalue"].ToString();
                    }

                    //bool checkDistinct = false;
                    //foreach (FamilyParameter fp in familyMgr.Parameters)
                    //{
                    //    if (fp.Definition.Name == xdt.Rows[i]["paraname"].ToString())
                    //    {
                    //        checkDistinct = true;
                    //    }
                    //}
                    //if (checkDistinct == true)
                    //{
                    //    continue;
                    //}
                    //else
                    //{
                    try
                    {
                        FamilyParameter newParameter = familyMgr.AddParameter(paraname, paragroup, paraType, isInstance);
                    }
                    catch (Exception efec)
                    {
                        MessageBox.Show(efec.ToString());
                        continue;
                    }
                    //创建族参数(每个参数两秒)
                    //familyMgr.Set(newParameter, paravalue);
                    //}
                }

                try
                {
                    for (int i = 0; i < xdt.Rows.Count; i++)
                    {
                        paraname = xdt.Rows[i]["paraname"].ToString();
                        foreach (FamilyParameter fp in familyMgr.Parameters)
                        {
                            StorageType fst = fp.StorageType;
                            if (fp.Definition.Name == xdt.Rows[i]["paraname"].ToString())
                            {
                                if (xdt.Rows[i]["paravalue"].ToString() == null && fst.ToString() == "String")
                                {
                                    paravalue = "NA";
                                    familyMgr.Set(fp, paravalue);
                                }
                                else
                                {
                                    //paravalue = xdt.Rows[i]["paravalue"].ToString();
                                    #region
                                    switch (fst.ToString())
                                    {
                                    case "Integer": int paravint = Convert.ToInt32(xdt.Rows[i]["paravalue"].ToString()); familyMgr.Set(fp, paravint);; break;

                                    case "Double": double paravdouble = Convert.ToDouble(xdt.Rows[i]["paravalue"].ToString()); familyMgr.Set(fp, paravdouble); break;

                                    case "String": string paravstring = xdt.Rows[i]["paravalue"].ToString(); familyMgr.Set(fp, paravstring); break;

                                    case "ElementId": ElementId paravid = new ElementId(Convert.ToInt32(xdt.Rows[i]["paravalue"].ToString())); familyMgr.Set(fp, paravid); break;

                                    case "None":   break;
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                }
                catch (Exception eeef)
                { /*MessageBox.Show(eeef.ToString());*/ }

                SaveOptions opt = new SaveOptions();
                addParameter.Commit();
            }

            return(familyDoc);
        }
Exemple #24
0
        public void EmbedStandard(Document doc, c.Application app, Dictionary <string, string> dic)
        {
            FamilyManager familyManager = doc.FamilyManager;
            string        origfile      = app.SharedParametersFilename;
            string        tempFile      = @"C:\Program Files\Autodesk\CEGCustomMenu\Shared_Params_2015_v01.json";
            Transaction   tran          = new Transaction(doc, "add parameter");

            tran.Start();
            app.SharedParametersFilename = tempFile;
            DefinitionFile shareParameterfile = app.OpenSharedParameterFile();

            foreach (DefinitionGroup i in shareParameterfile.Groups)
            {
                if (i.Name == "IDENTITY")
                {
                    //group data
                    FamilyParameter p1  = _AddParameter(doc, i, "CONTROL_MARK", BuiltInParameterGroup.PG_DATA, false);
                    string          vp1 = Getvalueparameter("CONTROL_MARK", dic);
                    familyManager.Set(p1, vp1);
                    FamilyParameter p2  = _AddParameter(doc, i, "IDENTITY_COMMENT", BuiltInParameterGroup.PG_DATA, false);
                    string          vp2 = Getvalueparameter("IDENTITY_COMMENT", dic);
                    familyManager.Set(p2, vp2);
                    FamilyParameter p3  = _AddParameter(doc, i, "IDENTITY_DESCRIPTION", BuiltInParameterGroup.PG_DATA, false);
                    string          vp3 = Getvalueparameter("IDENTITY_DESCRIPTION", dic);
                    familyManager.Set(p3, vp3);
                    FamilyParameter p4  = _AddParameter(doc, i, "IDENTITY_DESCRIPTION_SHORT", BuiltInParameterGroup.PG_DATA, false);
                    string          vp4 = Getvalueparameter("IDENTITY_DESCRIPTION_SHORT", dic);
                    familyManager.Set(p4, vp4);
                    FamilyParameter p5  = _AddParameter(doc, i, "MANUFACTURER_PLANT_DESCRIPTION", BuiltInParameterGroup.PG_DATA, false);
                    string          vp5 = Getvalueparameter("MANUFACTURER_PLANT_DESCRIPTION", dic);
                    familyManager.Set(p5, vp5);
                    FamilyParameter p6  = _AddParameter(doc, i, "MANUFACTURER_PLANT_ID", BuiltInParameterGroup.PG_DATA, false);
                    string          vp6 = Getvalueparameter("MANUFACTURER_PLANT_ID", dic);
                    familyManager.Set(p6, vp6);
                    FamilyParameter p7 = _AddParameter(doc, i, "MANUFACTURE_COMPONENT", BuiltInParameterGroup.PG_DATA, false);
                    FamilyParameter p8 = _AddParameter(doc, i, "SORTING_ORDER", BuiltInParameterGroup.PG_DATA, false);
                    familyManager.Set(p7, "EMBED STANDARD");
                    familyManager.Set(p8, int.Parse("100"));
                }
                if (i.Name == "DIMENSIONS_GENERAL")
                {
                    FamilyParameter p1  = _AddParameter(doc, i, "DIM_HEIGHT", BuiltInParameterGroup.PG_GEOMETRY, false);
                    string          vp1 = Getvalueparameter("DIM_HEIGHT", dic);
                    if (!string.IsNullOrEmpty(vp1))
                    {
                        familyManager.Set(p1, Convert.ToDouble(vp1));
                    }
                    FamilyParameter p2  = _AddParameter(doc, i, "DIM_THICKNESS", BuiltInParameterGroup.PG_GEOMETRY, false);
                    string          vp2 = Getvalueparameter("DIM_THICKNESS", dic);
                    if (!string.IsNullOrEmpty(vp2))
                    {
                        familyManager.Set(p2, Convert.ToDouble(vp2));
                    }
                    FamilyParameter p3  = _AddParameter(doc, i, "DIM_WIDTH", BuiltInParameterGroup.PG_GEOMETRY, false);
                    string          vp3 = Getvalueparameter("DIM_WIDTH", dic);
                    if (!string.IsNullOrEmpty(vp3))
                    {
                        familyManager.Set(p3, Convert.ToDouble(vp3));
                    }
                    FamilyParameter _p3  = _AddParameter(doc, i, "DBA_Length", BuiltInParameterGroup.PG_GEOMETRY, false);
                    string          _vp3 = Getvalueparameter("DBA_Length", dic);
                    if (!string.IsNullOrEmpty(_vp3))
                    {
                        familyManager.Set(_p3, Convert.ToDouble(_vp3));
                    }
                }
            }
            tran.Commit();
        }
        //Create family for each building
        //http://thebuildingcoder.typepad.com/blog/2011/06/creating-and-inserting-an-extrusion-family.html
        private bool CreateFamilyFile(ProcessPolygon polygon, double height, string familyFileName, XYZ translation)
        {
            bool     success = true;
            Document FamDoc  = null;

            Autodesk.Revit.DB.Form form = null;
            using (Transaction CreateFamily = new Transaction(_doc))
            {
                CreateFamily.Start("Create a new Family");
                FamDoc = _doc.Application.NewFamilyDocument(this.FamilyTemplateAddress);
                CreateFamily.Commit();
            }
            ReferenceArray refAr = polygon.Get_ReferenceArray(FamDoc, translation);

            using (Transaction CreateExtrusion = new Transaction(FamDoc))
            {
                FailureHandlingOptions failOpt = CreateExtrusion.GetFailureHandlingOptions();
                failOpt.SetFailuresPreprocessor(new WarningSwallower());
                CreateExtrusion.SetFailureHandlingOptions(failOpt);
                CreateExtrusion.Start("Create Extrusion");
                /*Mohammad took this out of try */
                try
                {
                    form = FamDoc.FamilyCreate.NewExtrusionForm(true, refAr, height * XYZ.BasisZ);
                }
                catch (Exception)
                {
                    this.FailedAttemptsToCreateBuildings++;
                    success = false;
                }
                CreateExtrusion.Commit();
            }

            //Added by Mohammad
            using (Transaction AddParamTrans = new Transaction(FamDoc))
            {
                AddParamTrans.Start("Add Parameter");
                Autodesk.Revit.ApplicationServices.Application app = FamDoc.Application;
                View3D view3d = createView3d();

                Dimension windowInsetDimension = null;
                FaceArray faces = new FaceArray();
                if (form.IsSolid)
                {
                    Options options = new Options();
                    options.ComputeReferences = true;
                    //options.View = new Autodesk.Revit.DB.View();
                    //GeometryObjectArray geoArr = extrusion.get_Geometry(options).Objects;
                    IEnumerator <GeometryObject> Objects = form.get_Geometry(options).GetEnumerator();
                    //foreach (GeometryObject geoObj in geoArr)
                    while (Objects.MoveNext())
                    {
                        GeometryObject geoObj = Objects.Current;

                        if (geoObj is Solid)
                        {
                            Solid s = geoObj as Solid;
                            foreach (Face fc in s.Faces)
                            {
                                //MessageBox.Show(fc.ComputeNormal(new UV(0, 0)).X.ToString() + "/n" + fc.ComputeNormal(new UV(0, 0)).Y.ToString() + "/n" + fc.ComputeNormal(new UV(0, 0)).Z.ToString());
                                if (Math.Round((fc.ComputeNormal(new UV(0, 0))).Z) == 1 || Math.Round((fc.ComputeNormal(new UV(0, 0))).Z) == -1)
                                {
                                    faces.Append(fc);
                                }
                            }
                            //**************************************************************************************************************
                            //****************************Here is the Error **********************************************************************
                            //************************************************************************************************************************
                            //windowInsetDimension = AddDimension( FamDoc, view3d, faces.get_Item( 0 ), faces.get_Item( 1 ) );
                            View viewElevation = new FilteredElementCollector(FamDoc).OfClass(typeof(View)).Cast <View>().Where <View>(v => ViewType.Elevation == v.ViewType).FirstOrDefault <View>();
                            windowInsetDimension = AddDimension(FamDoc, viewElevation, faces.get_Item(0), faces.get_Item(1));
                        }
                    }
                }

                //Test for creating dimension
                #region two lines creating dimenstion
                //// first create two lines
                //XYZ pt1 = new XYZ(5, 0, 5);
                //XYZ pt2 = new XYZ(5, 0, 10);
                //Line line = Line.CreateBound(pt1, pt2);
                //Plane plane = app.Create.NewPlane(pt1.CrossProduct(pt2), pt2);

                //SketchPlane skplane = SketchPlane.Create(FamDoc, plane);

                //ModelCurve modelcurve1 = FamDoc.FamilyCreate.NewModelCurve(line, skplane);

                //pt1 = new XYZ(10, 0, 5);
                //pt2 = new XYZ(10, 0, 10);
                //line = Line.CreateBound(pt1, pt2);
                //plane = app.Create.NewPlane(pt1.CrossProduct(pt2), pt2);

                //skplane = SketchPlane.Create(FamDoc, plane);

                //ModelCurve modelcurve2 = FamDoc.FamilyCreate.NewModelCurve(line, skplane);



                //// now create a linear dimension between them
                //ReferenceArray ra = new ReferenceArray();
                //ra.Append(modelcurve1.GeometryCurve.Reference);
                //ra.Append(modelcurve2.GeometryCurve.Reference);

                //pt1 = new XYZ(5, 0, 10);
                //pt2 = new XYZ(10, 0, 10);
                //line = Line.CreateBound(pt1, pt2);


                //Dimension dim = FamDoc.FamilyCreate.NewLinearDimension(view3d, line, ra);
                #endregion

                //creates a prameter named index for each family.
                BuiltInParameterGroup paramGroup = (BuiltInParameterGroup)Enum.Parse(typeof(BuiltInParameterGroup), "PG_GENERAL");
                ParameterType         paramType  = (ParameterType)Enum.Parse(typeof(ParameterType), "Length");
                FamilyManager         m_manager  = FamDoc.FamilyManager;

                FamilyParameter famParam = m_manager.AddParameter("Height", paramGroup, paramType, true);

                //Set the value for the parameter
                if (m_manager.Types.Size == 0)
                {
                    m_manager.NewType("Type 1");
                }

                m_manager.Set(famParam, height);

                //connects dimension to lable called with
                //windowInsetDimension.FamilyLabel = famParam;

                AddParamTrans.Commit();
            }


            SaveAsOptions opt = new SaveAsOptions();
            opt.OverwriteExistingFile = true;
            FamDoc.SaveAs(familyFileName, opt);
            FamDoc.Close(false);
            return(success);
        }
        private object ParamSwitch(FamilyParameter param, FamilyType type)
        {
            object value = String.Empty;
            try
            {
                var paramType = param.StorageType;
                switch (paramType)
                {
                    case StorageType.String:
                        value = type.AsString(param);
                        if (value != null)
                        {
                            value = value as String;
                        }
                        break;
                    case StorageType.Integer:
                        value = type.AsValueString(param);
                        break;
                    case StorageType.Double:
                        value = type.AsValueString(param);
                        break;
                    case StorageType.ElementId:
                        value = String.Empty;
                        break;
                }
            }
            catch (Exception)
            {

            }
            return value;
        }
        // ======================================
        //   (3.2) add dimensions
        // ======================================
        void addDimensions()
        {
            // find the plan view
              //
              View pViewPlan = findElement(typeof(ViewPlan), "Lower Ref. Level") as View;

              // find reference planes
              //
              ReferencePlane refLeft = findElement(typeof(ReferencePlane), "Left") as ReferencePlane;
              ReferencePlane refFront = findElement(typeof(ReferencePlane), "Front") as ReferencePlane;
              ReferencePlane refOffsetV = findElement(typeof(ReferencePlane), "OffsetV") as ReferencePlane; // OffsetV is added for L-shape
              ReferencePlane refOffsetH = findElement(typeof(ReferencePlane), "OffsetH") as ReferencePlane; // OffsetH is added for L-shape

              //
              // (1)  add dimension between the reference planes 'Left' and 'OffsetV', and label it as 'Tw'
              //

              // define a dimension line
              //
              XYZ p0 = refLeft.FreeEnd;
              XYZ p1 = refOffsetV.FreeEnd;
              //Line pLine = _app.Create.NewLineBound(p0, p1);  // Revit 2013
              Line pLine = Line.CreateBound(p0, p1);

              // define references
              //
              ReferenceArray pRefArray = new ReferenceArray();
              pRefArray.Append(refLeft.GetReference());
              pRefArray.Append(refOffsetV.GetReference());

              // create a dimension
              //
              Dimension pDimTw = _doc.FamilyCreate.NewDimension(pViewPlan, pLine, pRefArray);

              // add label to the dimension
              //
              FamilyParameter paramTw = _doc.FamilyManager.get_Parameter("Tw");
              // pDimTw.Label = paramTw;  // Revit 2013
              pDimTw.FamilyLabel = paramTw;  // Revit 2014

              //
              // (2)  do the same for dimension between 'Front' and 'OffsetH', and lable it as 'Td'
              //

              // define a dimension line
              //
              p0 = refFront.FreeEnd;
              p1 = refOffsetH.FreeEnd;
              // pLine = _app.Create.NewLineBound(p0, p1);  // Revit 2013
              pLine = Line.CreateBound(p0, p1);  // Revit 2014

              // define references
              //
              pRefArray = new ReferenceArray();
              pRefArray.Append(refFront.GetReference());
              pRefArray.Append(refOffsetH.GetReference());

              // create a dimension
              //
              Dimension pDimTd = _doc.FamilyCreate.NewDimension(pViewPlan, pLine, pRefArray);

              // add label to the dimension
              //
              FamilyParameter paramTd = _doc.FamilyManager.get_Parameter("Td");
              // pDimTd.Label = paramTd;  // Revit 2013
              pDimTd.FamilyLabel = paramTd;  // Revit 2014
        }
Exemple #28
0
        /// <summary>
        /// Ask the user to open a revit family template and then add FamilyTypes and FamilyParameters
        /// to it. Say the user opens a Door template, he can then save the family as a new door family and load
        /// it into a new project for use.
        /// </summary>
        public void AddFamilyParameterAndType()
        {
            Document doc;

            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title  = "Select family document";
            openFileDialog.Filter = "RFT Files (*.rft)|*.rft";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                doc = m_revitApp.Application.NewFamilyDocument(openFileDialog.FileName);
            }
            else
            {
                return;
            }

            using (Transaction transaction = new Transaction(m_revitApp.ActiveUIDocument.Document))
            {
                transaction.Start("AddFamilyParameterAndType");

                if (doc.IsFamilyDocument)
                { // has to be a family document to be able to use the Family Manager.
                    FamilyManager famMgr = doc.FamilyManager;

                    //Add a family param.
                    FamilyParameter famParam = famMgr.AddParameter("RevitLookup_Param", BuiltInParameterGroup.PG_TITLE, ParameterType.Text, false);
                    famMgr.Set(famParam, "Default text.");

                    //Create a couple of new family types. Note that we can set different values for the param
                    //in different family types.

                    FamilyType newFamType = famMgr.NewType("RevitLookup_Type1");
                    famMgr.CurrentType = newFamType;

                    if (newFamType.HasValue(famParam))
                    {
                        famMgr.Set(famParam, "Text1.");
                    }

                    FamilyType newFamType1 = famMgr.NewType("RevitLookup_Type2");
                    famMgr.CurrentType = newFamType;

                    if (newFamType.HasValue(famParam))
                    {
                        famMgr.Set(famParam, "Text2.");
                    }

                    famMgr.MakeType(famParam);

                    if ((famParam != null) && (newFamType != null))
                    {
                        MessageBox.Show("New family types/params added successfully.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Family types/params addition failed.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                transaction.Commit();
            }
        }
Exemple #29
0
 public void RawSetFamilyParameterValue(FamilyManager fm, string familyTypeName, FamilyParameter fp, object value)
 {
     RawSetFamilyParameterValue(fm, RawFindFamilyType(fm, familyTypeName), fp, value);
 }
Exemple #30
0
        public bool createSharedParameter(bool replaceExisting, Autodesk.Revit.DB.Document targetDoc)
        {
            // we should not be able to get here unless the stage is not set up correctly
            // we need to check
            // 1) does the parameter need to be created
            // 2) if it is aleady created, do they need to manually delete it and create anew?
            FamilyParameter existingParameter = this.DoesParameterExistInFile(_paramName, targetDoc);
            bool            isSuccessful      = false;
            string          failReason        = "";
            bool            okToProceed       = true;

            if (!(existingParameter == null))
            {
                JerkHub.Ptr2Debug.AddToDebug("Matching Existing - what is the user option?");
                if (replaceExisting)
                {
                    JerkHub.Ptr2Debug.AddToDebug("User Chooses to delete matching existing.");
                    this.deleteExistingParameter(existingParameter, targetDoc);
                    // -------
                    JerkHub.Ptr2Debug.AddToDebug("Testing for matching parameter again, to make sure we successfully deleted it.");
                    existingParameter = this.DoesParameterExistInFile(_paramName, targetDoc);
                    if ((existingParameter == null))
                    {
                        okToProceed = true;
                    }
                    else
                    {
                        JerkHub.Ptr2Debug.AddToDebug("Deleting existing parameter failed. This import fails.");
                        isSuccessful = false;
                        okToProceed  = false;
                    }
                }
                else
                {
                    // do nothing
                    JerkHub.Ptr2Debug.AddToDebug("User DOES NOT Choose to delete matching existing. This import fails.");
                    MessageBox.Show("parameter not added because it already exists in the file and you have not elected to overwrite it");
                    isSuccessful = false;
                    failReason   = "Parameter exist, no permission given to overwrite";
                    okToProceed  = false;
                }
            }

            if (okToProceed)
            {
                // --- we are guaranteed not to have a matching existing parameter here
                this.importOneParameter(_paramName, targetDoc);
                JerkHub.Ptr2Debug.AddToDebug("Post import, test if the parameter exists in the file...it should");
                existingParameter = this.DoesParameterExistInFile(_paramName, targetDoc);
                if ((existingParameter == null))
                {
                    isSuccessful = false;
                    failReason   = "Unable to add parameter";
                    JerkHub.Ptr2Debug.AddToDebug("Import failed");
                }
                else
                {
                    JerkHub.Ptr2Debug.AddToDebug("Import successful");
                    isSuccessful = true;
                }
            }

            ClassOneImportResult thisResult = new ClassOneImportResult();

            thisResult.ParameterName = _paramName;
            thisResult.fileNameLong  = targetDoc.PathName;
            // but what if we were not able to delete the existing parameter
            thisResult.ResultSuccessful = isSuccessful;
            thisResult.ResultLong       = failReason;
            JerkHub.AddToResults(thisResult);
            return(isSuccessful);
        }
Exemple #31
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");
        }
Exemple #32
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);
        }
        //Returns a single FamilyParameterModel
        internal static FamilyParameterModel GetFamilyParameterModel(FamilyType ft, FamilyParameter fp, List <FamilyParameter> paramLabel, List <FamilyParameter> paramFormula)
        {
            FamilyParameterModel fpmodel = FamilyParameterItem(ft, fp, paramLabel, paramFormula);

            return(fpmodel);
        }
Exemple #34
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            if (!doc.IsFamilyDocument)
            {
                message = "Please run this command in afamily document.";
                return(Result.Failed);
            }

            Autodesk.Revit.Creation.Application creApp = app.Application.Create;
            Autodesk.Revit.Creation.Document    creDoc = doc.Create;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("New Dimension Label");


                SketchPlane skplane = findSketchPlane(doc, XYZ.BasisZ);

                if (null == skplane)
                {
                    //Plane geometryPlane = creApp.NewPlane( XYZ.BasisZ, XYZ.Zero ); // 2016
                    Plane geometryPlane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero); // 2017

                    //skplane = doc.FamilyCreate.NewSketchPlane( geometryPlane ); // 2013

                    skplane = SketchPlane.Create(doc, geometryPlane); // 2014
                }

                double length = 1.23;

                XYZ start = XYZ.Zero;
                XYZ end   = creApp.NewXYZ(0, length, 0);

                //Line line = creApp.NewLine( start, end, true ); // 2013

                Line line = Line.CreateBound(start, end); // 2014

                ModelCurve modelCurve
                    = doc.FamilyCreate.NewModelCurve(
                          line, skplane);

                ReferenceArray ra = new ReferenceArray();

                ra.Append(modelCurve.GeometryCurve.Reference);

                start = creApp.NewXYZ(length, 0, 0);
                end   = creApp.NewXYZ(length, length, 0);

                line = Line.CreateBound(start, end);

                modelCurve = doc.FamilyCreate.NewModelCurve(
                    line, skplane);

                ra.Append(modelCurve.GeometryCurve.Reference);

                start = creApp.NewXYZ(0, 0.2 * length, 0);
                end   = creApp.NewXYZ(length, 0.2 * length, 0);

                line = Line.CreateBound(start, end);

                Dimension dim
                    = doc.FamilyCreate.NewLinearDimension(
                          doc.ActiveView, line, ra);

                FamilyParameter familyParam
                    = doc.FamilyManager.AddParameter(
                          "length",
                          BuiltInParameterGroup.PG_IDENTITY_DATA,
                          ParameterType.Length, false);

                //dim.Label = familyParam; // 2013
                dim.FamilyLabel = familyParam; // 2014

                t.Commit();
            }
            return(Result.Succeeded);
        }
        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);
                    }
                }
            }
        }
Exemple #36
0
        public Dimension CreateLinearDimension(
            Document doc)
        {
            Application app = doc.Application;

            // first create two lines

            XYZ  pt1  = new XYZ(5, 5, 0);
            XYZ  pt2  = new XYZ(5, 10, 0);
            Line line = Line.CreateBound(pt1, pt2);

            //Plane plane = app.Create.NewPlane( pt1.CrossProduct( pt2 ), pt2 ); // 2016

            Plane plane = Plane.CreateByNormalAndOrigin(pt1.CrossProduct(pt2), pt2); // 2017

            //SketchPlane skplane = doc.FamilyCreate.NewSketchPlane( plane ); // 2013

            SketchPlane skplane = SketchPlane.Create(doc, plane); // 2014

            ModelCurve modelcurve1 = doc.FamilyCreate
                                     .NewModelCurve(line, skplane);

            pt1  = new XYZ(10, 5, 0);
            pt2  = new XYZ(10, 10, 0);
            line = Line.CreateBound(pt1, pt2);
            //plane = app.Create.NewPlane( pt1.CrossProduct( pt2 ), pt2 ); // 2016
            plane = Plane.CreateByNormalAndOrigin(pt1.CrossProduct(pt2), pt2); // 2017

            //skplane = doc.FamilyCreate.NewSketchPlane( plane ); // 2013

            skplane = SketchPlane.Create(doc, plane); // 2014

            ModelCurve modelcurve2 = doc.FamilyCreate
                                     .NewModelCurve(line, skplane);

            // now create a linear dimension between them

            ReferenceArray ra = new ReferenceArray();

            ra.Append(modelcurve1.GeometryCurve.Reference);
            ra.Append(modelcurve2.GeometryCurve.Reference);

            pt1  = new XYZ(5, 10, 0);
            pt2  = new XYZ(10, 10, 0);
            line = Line.CreateBound(pt1, pt2);
            Dimension dim = doc.FamilyCreate
                            .NewLinearDimension(doc.ActiveView, line, ra);

            // create a label for the dimension called "width"

            FamilyParameter param = doc.FamilyManager
                                    .AddParameter("width",
                                                                           //BuiltInParameterGroup.PG_CONSTRAINTS, // 2021
                                                  GroupTypeId.Constraints, // 2022
                                                                           //ParameterType.Length, // 2021
                                                  SpecTypeId.Length,       // 2022
                                                  false);

            //dim.Label = param; // 2013
            dim.FamilyLabel = param; // 2014

            return(dim);
        }