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

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

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

              // same idea for 'Depth'
              //
              FamilyParameter paramD = pFamilyMgr.get_Parameter("Depth");
              double valD = mmToFeet(d);
              if (paramD != null)
              {
            pFamilyMgr.Set(paramD, valD);
              }
        }
        /// <summary>
        /// Creates default family type.
        /// </summary>
        /// <param name="familyManager">The family manager.</param>
        /// <returns></returns>
        /// <exception cref="Exception">Aborted by user.</exception>
        private FamilyType CreateDefaultFamilyType(FamilyManager familyManager)
        {
            FamilyType familyType = null;

            TaskDialog td = new TaskDialog("No Family Type");

            td.MainInstruction = "Create Default Family Type.";
            string s = "This might be a new Family with no existing Parameters or Family Types." + Environment.NewLine + Environment.NewLine +
                       "In order to use this plugin, you can either create a new Parameter/Family Type from the Family Types Dialog" +
                       " and restart the plugin or create a Default Family Type by accepting this message." + Environment.NewLine + Environment.NewLine +
                       "You can always delete the Default Family Parameter later.";

            td.MainContent   = s;
            td.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;

            TaskDialogResult tResult = td.Show();

            if (TaskDialogResult.Yes == tResult)
            {
                using (Transaction t = new Transaction(doc, "Create Family Type"))
                {
                    t.Start();
                    familyType = familyManager.NewType("Default");
                    t.Commit();
                }
            }
            else
            {
                throw new Exception("Aborted by user.");
            }

            return(familyType);
        }
        /// <summary>
        /// the method is used to create new family type
        /// </summary>
        /// <param name="para">WindowParameter</param>
        /// <returns>indicate whether the NewType is successful</returns>
        private bool newFamilyType(WindowParameter para)//string typeName, double height, double width, double sillHeight)
        {
            DoubleHungWinPara dbhungPara  = para as DoubleHungWinPara;
            string            typeName    = dbhungPara.Type;
            double            height      = dbhungPara.Height;
            double            width       = dbhungPara.Width;
            double            sillHeight  = dbhungPara.SillHeight;
            double            windowInset = dbhungPara.Inset;

            switch (m_document.DisplayUnitSystem)
            {
            case Autodesk.Revit.DB.DisplayUnit.METRIC:
                height      = Utility.MetricToImperial(height);
                width       = Utility.MetricToImperial(width);
                sillHeight  = Utility.MetricToImperial(sillHeight);
                windowInset = Utility.MetricToImperial(windowInset);
                break;
            }
            try
            {
                FamilyType type = m_familyManager.NewType(typeName);
                m_familyManager.CurrentType = type;
                m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT), height);
                m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH), width);
                m_familyManager.Set(m_familyManager.get_Parameter("Default Sill Height"), sillHeight);
                m_familyManager.Set(m_familyManager.get_Parameter("Window Inset"), windowInset);
                return(true);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                return(false);
            }
        }
Example #4
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication rvtUIAPP = commandData.Application;
            UIDocument    uidoc    = rvtUIAPP.ActiveUIDocument;
            Configuration config   = ConfigurationManager.OpenExeConfiguration
                                         (System.Reflection.Assembly.GetExecutingAssembly().Location);
            string familyRepo = config.AppSettings.Settings["Family_repo_folder"].Value;
            string serverAPI  = config.AppSettings.Settings["Server_API"].Value;

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

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

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Example #5
0
        /// <summary>
        /// Add type parameters to the family
        /// </summary>
        /// <param name="DWGFileName">Name of imported dwg file</param>
        private void AddParameters(string DWGFileName)
        {
            // Get the family manager
            FamilyManager familyMgr = m_doc.FamilyManager;

            // Add parameter 1: DWGFileName
            familyMgr.NewType("DWGFamilyCreation");
            FamilyParameter paraFileName = familyMgr.AddParameter("DWGFileName", Autodesk.Revit.DB.BuiltInParameterGroup.INVALID,
                                                                  Autodesk.Revit.DB.ParameterType.Text, false);

            familyMgr.Set(paraFileName, DWGFileName);

            // Add parameter 2: ImportTime
            String          time           = DateTime.Now.ToString("yyyy-MM-dd");
            FamilyParameter paraImportTime = familyMgr.AddParameter("ImportTime", Autodesk.Revit.DB.BuiltInParameterGroup.INVALID,
                                                                    Autodesk.Revit.DB.ParameterType.Text, false);

            familyMgr.Set(paraImportTime, time);
        }
Example #6
0
        /// <summary>
        /// Add type parameters to the family
        /// </summary>
        /// <param name="DWGFileName">Name of imported dwg file</param>
        private void AddParameters(string DWGFileName)
        {
            // Get the family manager
            FamilyManager familyMgr = m_doc.FamilyManager;

            // Add parameter 1: DWGFileName
            familyMgr.NewType("DWGFamilyCreation");
            FamilyParameter paraFileName = familyMgr.AddParameter("DWGFileName", new ForgeTypeId(),
                                                                  SpecTypeId.String.Text, false);

            familyMgr.Set(paraFileName, DWGFileName);

            // Add parameter 2: ImportTime
            String          time           = DateTime.Now.ToString("yyyy-MM-dd");
            FamilyParameter paraImportTime = familyMgr.AddParameter("ImportTime", new ForgeTypeId(),
                                                                    SpecTypeId.String.Text, false);

            familyMgr.Set(paraImportTime, time);
        }
Example #7
0
        public FamilySymbol CreatNewSymbol(Document doc, Family doorfamily, int doorwidth, int doorheight, string str)
        {
            Document      familydoc     = doc.EditFamily(doorfamily);
            FamilyManager familymanager = familydoc.FamilyManager;
            string        symbolname    = str;

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

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

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

            return(newsymbol);
        }
Example #8
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 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);
        }
Example #10
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();
            }
        }
Example #11
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);
            }
        }
Example #12
0
        private void EditFamily(Document famDoc, ExternalDefinition ExDef)
        {
            View view = famDoc.FindElement(typeof(View), targetName: "视图 1") as View;

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

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

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

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


                    FM.RemoveParameter(Para_Depth);

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

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

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

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

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

                    // famDoc.Close();
                    tranFam.Commit();
                }
                catch (Exception ex)
                {
                    // Utils.ShowDebugCatch(ex, $"事务“{tranFam.GetName()}” 出错!");
                    tranFam.RollBack();
                    throw new InvalidOperationException($"事务“{tranFam.GetName()}”出错", ex);
                }
            }
        }
Example #13
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Application app = commandData.Application.Application;

            string filename = Path.Combine(_folder, _template);

            Document familyDoc = app.NewFamilyDocument(filename);

            Family family = familyDoc.OwnerFamily;

            Autodesk.Revit.Creation.FamilyItemFactory factory
                = familyDoc.FamilyCreate;

            Extrusion extrusion = null;

            using (Transaction trans = new Transaction(
                       familyDoc))
            {
                trans.Start("Create Extrusion");

                XYZ arcCenter = new XYZ(0.0, 3.0, -2.0);

                // Get the "left" view

                View view = GetView(ViewType.Elevation,
                                    XYZ.BasisY.Negate(), XYZ.BasisZ, familyDoc);

                // 2D offsets from view 'left'

                XYZ xOffset = new XYZ(0.0, 10.0, 0.0);
                XYZ yOffset = new XYZ(0.0, 0.0, -10.0);

                //################## Reference planes ################################

                // Origin's reference planes

                ReferencePlane referencePlaneOriginX
                    = factory.NewReferencePlane(XYZ.BasisX,
                                                XYZ.Zero, XYZ.BasisY, view);

                referencePlaneOriginX.Name   = "ReferencePlane_OriginX";
                referencePlaneOriginX.Pinned = true;

                ReferencePlane referencePlaneOriginY
                    = factory.NewReferencePlane(XYZ.BasisZ,
                                                XYZ.Zero, -XYZ.BasisX, view);

                referencePlaneOriginY.Name   = "ReferencePlane_OriginY";
                referencePlaneOriginY.Pinned = true;

                // Reference planes the extruded arc should stick to

                ReferencePlane referencePlaneX
                    = factory.NewReferencePlane(
                          XYZ.BasisX + yOffset,
                          XYZ.Zero + yOffset,
                          XYZ.BasisY, view);
                referencePlaneX.Name = "ReferencePlane_X";

                ReferencePlane referencePlaneY
                    = factory.NewReferencePlane(
                          XYZ.BasisZ + xOffset,
                          XYZ.Zero + xOffset,
                          -XYZ.BasisX, view);
                referencePlaneY.Name = "ReferencePlane_Y";

                familyDoc.Regenerate();

                //################## Create dimensions ###############################

                // Dimension x

                ReferenceArray refArrayX = new ReferenceArray();
                refArrayX.Append(referencePlaneX.GetReference());
                refArrayX.Append(referencePlaneOriginX.GetReference());

                Line      lineX      = Line.CreateUnbound(arcCenter, XYZ.BasisZ);
                Dimension dimensionX = factory.NewDimension(
                    view, lineX, refArrayX);

                // Dimension y

                ReferenceArray refArrayY = new ReferenceArray();
                refArrayY.Append(referencePlaneY.GetReference());
                refArrayY.Append(referencePlaneOriginY.GetReference());

                Line      lineY      = Line.CreateUnbound(arcCenter, XYZ.BasisY);
                Dimension dimensionY = factory.NewDimension(
                    view, lineY, refArrayY);

                familyDoc.Regenerate();

                //################## Create arc ######################################

                double arcRadius = 1.0;

                Arc arc = Arc.Create(
                    XYZ.Zero + xOffset + yOffset,
                    arcRadius, 0.0, 2 * Math.PI,
                    XYZ.BasisZ, XYZ.BasisY.Negate());

                CurveArray curves = new CurveArray();
                curves.Append(arc);

                CurveArrArray profile = new CurveArrArray();
                profile.Append(curves);

                Plane plane = new Plane(XYZ.BasisX.Negate(),
                                        arcCenter);

                SketchPlane sketchPlane = SketchPlane.Create(
                    familyDoc, plane);

                Debug.WriteLine("Origin: " + sketchPlane.GetPlane().Origin);
                Debug.WriteLine("Normal: " + sketchPlane.GetPlane().Normal);
                Debug.WriteLine("XVec:   " + sketchPlane.GetPlane().XVec);
                Debug.WriteLine("YVec:   " + sketchPlane.GetPlane().YVec);

                extrusion = factory.NewExtrusion(true,
                                                 profile, sketchPlane, 10);

                familyDoc.Regenerate();

                //################## Add family parameters ###########################

                FamilyManager fmgr = familyDoc.FamilyManager;

                FamilyParameter paramX = fmgr.AddParameter("X",
                                                           BuiltInParameterGroup.PG_GEOMETRY,
                                                           ParameterType.Length, true);
                dimensionX.FamilyLabel = paramX;

                FamilyParameter paramY = fmgr.AddParameter("Y",
                                                           BuiltInParameterGroup.PG_GEOMETRY,
                                                           ParameterType.Length, true);
                dimensionY.FamilyLabel = paramY;

                // Set their values

                FamilyType familyType = fmgr.NewType(
                    "Standard");

                fmgr.Set(paramX, 10);
                fmgr.Set(paramY, 10);

                trans.Commit();
            }

            // Save it to inspect

            SaveAsOptions opt = new SaveAsOptions();

            opt.OverwriteExistingFile = true;

            filename = Path.Combine(Path.GetTempPath(),
                                    "test.rfa");

            familyDoc.SaveAs(filename, opt);

            return(Result.Succeeded);
        }
Example #14
0
        private void SetParameters(UIApplication uiApp, string familyFile, ExternalDefinition externalDefinition)
        {
            try
            {
                //Get the FileInfo of the family file and then get the LastWriteTime value as a date string in MM/DD/YYYY format
                FileInfo fileInfo     = new FileInfo(familyFile);
                string   lastModified = fileInfo.LastWriteTime.ToShortDateString();

                //Open the family file
                RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, familyFile);
                if (famDoc != null)
                {
                    //Get the family manager for the family file
                    FamilyManager famMan = famDoc.FamilyManager;
                    //Get the family parameters and add them to a dictionary indexed by parameter name
                    FamilyParameter famParameter = null;
                    Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                    foreach (FamilyParameter famParam in famMan.Parameters)
                    {
                        famParamDict.Add(famParam.Definition.Name, famParam);
                    }

                    //Get the number of family types because there must be at least one family type to make this work
                    FamilyTypeSet types         = famMan.Types;
                    int           numberOfTypes = types.Size;

                    Transaction t1 = new Transaction(famDoc, "SetParameters");
                    t1.Start();
                    if (numberOfTypes == 0)
                    {
                        //If the number of family types was 0, then one must be made. Thus Default is a family type created
                        try
                        {
                            famMan.NewType("Default");
                        }
                        catch { MessageBox.Show(String.Format("Could not make a default type or find any type for {0}", familyFile)); }
                    }

                    //Once the existence of a family type is confirmed, move on with determining if the version parameter already exists. If it doesn't add the parameter to the family and regenerate the document
                    if (!famParamDict.Keys.Contains(BARevitTools.Properties.Settings.Default.RevitUFVPParameter))
                    {
                        famParameter = famMan.AddParameter(externalDefinition, BuiltInParameterGroup.PG_IDENTITY_DATA, false);
                        famDoc.Regenerate();
                    }
                    else
                    {
                        famParameter = famParamDict[BARevitTools.Properties.Settings.Default.RevitUFVPParameter];
                    }

                    //Check to see if the value for the parameter is equal to the date last modified
                    if (famMan.CurrentType.AsString(famParameter) == lastModified)
                    {
                        //If so, roll back the transaction and just close the file.
                        t1.RollBack();
                        famDoc.Close(false);
                    }
                    else
                    {
                        //Otherwise set the formula of the version parameter to the quote encapsulated date, just like it would appear in Revit, commit it, then save.
                        famMan.SetFormula(famParameter, "\"" + lastModified + "\"");
                        t1.Commit();
                        RVTOperations.SaveRevitFile(uiApp, famDoc, true);
                    }
                }
                else
                {
                    //If the family could not be opened for any reason, let the user know
                    MessageBox.Show(String.Format("{0} could not be opened.", familyFile));
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Example #15
0
        public MaterialsCMSRequest(UIApplication uiApp, String text)
        {
            MainUI        uiForm          = BARevitTools.Application.thisApp.newMainUi;
            ProgressBar   progressBar     = uiForm.materialsCMSExcelCreateSymbolsProgressBar;
            DataGridView  dgv             = uiForm.materialsCMSExcelDataGridView;
            int           rowsCount       = dgv.Rows.Count;
            int           columnsCount    = dgv.Columns.Count;
            List <string> familyTypesMade = new List <string>();

            //Prepare the progress bar. The column count is one less because the first column is the column for family type names
            progressBar.Minimum = 0;
            progressBar.Maximum = (rowsCount) * (columnsCount - 1);
            progressBar.Step    = 1;
            progressBar.Visible = true;

            RVTDocument doc = uiApp.ActiveUIDocument.Document;

            //Reset the progress bar
            uiForm.materialsCMSExcelCreateSymbolsProgressBar.Value = 0;

            //First, try to use the family from the project. If that fails, use the family file
            Family familyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));

            //Assuming nothing went to hell in the process of loading one famiy...
            if (familyToUse != null)
            {
                //Save out the family to use
                RVTDocument tempFamDoc = doc.EditFamily(familyToUse);
                RVTOperations.SaveRevitFile(uiApp, tempFamDoc, @"C:\Temp\" + tempFamDoc.Title, true);

                //Open the family to use and get its FamilyManager
                RVTDocument   famDoc = RVTOperations.OpenRevitFile(uiApp, @"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
                FamilyManager famMan = famDoc.FamilyManager;

                //Get the parameters from the Family Manager and add them to a dictionary
                FamilyParameterSet parameters = famMan.Parameters;
                Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                foreach (FamilyParameter param in parameters)
                {
                    famParamDict.Add(param.Definition.Name, param);
                }

                //Start a new transaction to make the new family types in the family to use
                using (Transaction t1 = new Transaction(famDoc, "MakeNewTypes"))
                {
                    t1.Start();
                    //Cycle through the rows in the dgv
                    for (int i = 0; i < rowsCount; i++)
                    {
                        //The first column cell will be the type name
                        string newTypeName = dgv.Rows[i].Cells[0].Value.ToString();
                        //Get the family type names in the family
                        Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(famMan);
                        //If the family to make from the DGV does not exist in the dictionary keys...
                        if (!existingTypeNames.Keys.Contains(newTypeName))
                        {
                            //Make the family type and add it to the list of types made
                            FamilyType newType = famMan.NewType(newTypeName);
                            famMan.CurrentType = newType;
                            familyTypesMade.Add(newType.Name);
                        }
                        else
                        {
                            //If the type exists, set the current type it from the dictionary and add it to the list of types made
                            famMan.CurrentType = existingTypeNames[newTypeName];
                            familyTypesMade.Add(famMan.CurrentType.Name);
                        }

                        //Next, evaluate the columns that contain parameters
                        for (int j = 1; j < columnsCount; j++)
                        {
                            //The parameter names will be retrieved from the column HeaderText property
                            string paramName = dgv.Columns[j].HeaderText;
                            //Meanwhile the parameter value will come from the DGV cells
                            var paramValue = dgv.Rows[i].Cells[j].Value;

                            try
                            {
                                //If the parameter dictionary contains the parameter and the value to assign it is not empty, continue.
                                if (paramValue.ToString() != "" && famParamDict.Keys.Contains(paramName))
                                {
                                    //Get the family parameter and check if it is locked by a formula
                                    FamilyParameter param = famParamDict[paramName];
                                    if (!param.IsDeterminedByFormula)
                                    {
                                        //If it is not locked by a formula, set the parameter
                                        ParameterType paramType = param.Definition.ParameterType;
                                        RVTOperations.SetFamilyParameterValue(famMan, param, paramValue);
                                    }
                                }
                            }
                            catch
                            {; }
                            finally
                            {
                                //Always perform the step to indicate the progress.
                                progressBar.PerformStep();
                            }
                        }
                    }
                    t1.Commit();
                }

                //Use another transaction to delete the types that were not needed
                using (Transaction t2 = new Transaction(famDoc, "DeleteOldTypes"))
                {
                    t2.Start();
                    //Cycle through the family types and determine if it is in the list of types made
                    foreach (FamilyType type in famMan.Types)
                    {
                        if (!familyTypesMade.Contains(type.Name))
                        {
                            //If the type is not in the list of types made, delete it from the family file
                            famMan.CurrentType = type;
                            famMan.DeleteCurrentType();
                        }
                    }
                    t2.Commit();
                }

                //Save the family document at this point as all of the types and their parameters have been set
                famDoc.Close(true);

                using (Transaction t3 = new Transaction(doc, "LoadFamily"))
                {
                    t3.Start();
                    doc.LoadFamily(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule), new RVTFamilyLoadOptions(), out Family loadedFamily);
                    t3.Commit();
                }

                //Get the drafting view type in the project for BA Drafting View, else just get the first drafting view type
                ViewDrafting   placementView    = null;
                var            draftingViews    = new FilteredElementCollector(doc).OfClass(typeof(ViewDrafting)).WhereElementIsNotElementType().ToElements();
                ViewFamilyType draftingViewType = null;
                try
                {
                    //From the view family types collection, get the first one where its name is BA Drafting View
                    draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().Where(elem => elem.Name == "BA Drafting View").First() as ViewFamilyType;
                }
                catch
                {
                    //Well, crap. It doesn't exist. Just get the first type then and call it good.
                    draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().First() as ViewFamilyType;
                }

                //Start a transaction for making the ID Material View and placing the family symbol types
                using (Transaction t4 = new Transaction(doc, "MakeIDMaterialView"))
                {
                    t4.Start();
                    foreach (ViewDrafting view in draftingViews)
                    {
                        //Find the view named ID Material View, or whatever jibberish someone typed in the CMS text box for the name to use. in the drafting views
                        if (view.Name == "ID Material View" || view.Name == uiForm.materialsCMSSetViewNameTextBox.Text)
                        {
                            //Delete the drafting view
                            doc.Delete(view.Id);
                            doc.Regenerate();
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    //Make a new view
                    placementView       = ViewDrafting.Create(doc, draftingViewType.Id);
                    placementView.Scale = 1;
                    if (uiForm.materialsCMSSetViewNameTextBox.Text != "")
                    {
                        //If someone defined a custom view name, use that and strip out brackets if they exist
                        placementView.Name = uiForm.materialsCMSSetViewNameTextBox.Text.Replace("{", "").Replace("}", "");
                    }
                    else
                    {
                        //Otherwise, this will be the new ID Material View
                        placementView.Name = "ID Material View";
                    }

                    try
                    {
                        //Set the view sort parameters if they exist
                        placementView.GetParameters(Properties.Settings.Default.BAViewSort1).First().Set("2 Plans");
                        placementView.GetParameters(Properties.Settings.Default.BAViewSort2).First().Set("230 Finish Plans");
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.ToString());
                    }
                    doc.Regenerate();
                    t4.Commit();
                }


                //Do magic to place each symbol in its view by calling the method below in this class
                PlaceSymbolsInView(uiApp, "ID Use", "Mark", placementView);

                //Clean up the files from the operations
                GeneralOperations.CleanRfaBackups(GeneralOperations.GetAllRvtBackupFamilies(@"C:\Temp\", false));
                File.Delete(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
                Application.thisApp.newMainUi.materialsCMSFamilyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
            }
            else
            {
                //If the family could not be found, well, let the user know of this.
                MessageBox.Show(String.Format("The {0} family could not be found in the project.",
                                              Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)));
            }
        }