Пример #1
0
        /// <summary>
        /// Loads a family at the specified path into the current document. Will always overwrite existing families and will never overwrite parameter values.
        /// </summary>
        /// <param name="path">File path of the family to load.</param>
        /// <returns>The family name of the loaded family.</returns>
        public static string LoadFamily(string path)
        {
            var doc = DocumentManager.Instance.CurrentDBDocument;

            Autodesk.Revit.DB.Family outFamily = null;

            /*
             * using (Autodesk.Revit.DB.Transaction transaction = new Autodesk.Revit.DB.Transaction(doc))
             * {
             *  if (transaction.Start("Load family into document") == TransactionStatus.Started)
             *  {
             *      doc.LoadFamily(path, new FamilyOptions(), out outFamily);
             *
             *      if (transaction.Commit() != TransactionStatus.Committed)
             *      {
             *          transaction.RollBack();
             *      }
             *  }
             * }*/

            TransactionManager.Instance.EnsureInTransaction(doc);

            doc.LoadFamily(path, new FamilyOptions(), out outFamily);

            TransactionManager.Instance.TransactionTaskDone();

            return(outFamily.Name);
        }
Пример #2
0
        /// <summary>
        /// find Column which will be used to placed to Wall
        /// </summary>
        /// <param name="rvtDoc">Revit document</param>
        /// <param name="familyName">Family name of Column</param>
        /// <param name="symbolName">Symbol of Column</param>
        /// <returns></returns>
        private FamilySymbol FindFamilySymbol(Document rvtDoc, string familyName, string symbolName)
        {
            FilteredElementCollector collector = new FilteredElementCollector(rvtDoc);
            FilteredElementIterator  itr       = collector.OfClass(typeof(Family)).GetElementIterator();

            itr.Reset();
            while (itr.MoveNext())
            {
                Autodesk.Revit.DB.Element elem = (Autodesk.Revit.DB.Element)itr.Current;
                if (elem.GetType() == typeof(Autodesk.Revit.DB.Family))
                {
                    if (elem.Name == familyName)
                    {
                        Autodesk.Revit.DB.Family family = (Autodesk.Revit.DB.Family)elem;
                        foreach (Autodesk.Revit.DB.ElementId symbolId in family.GetFamilySymbolIds())
                        {
                            Autodesk.Revit.DB.FamilySymbol symbol = (Autodesk.Revit.DB.FamilySymbol)rvtDoc.GetElement(symbolId);
                            if (symbol.Name == symbolName)
                            {
                                return(symbol);
                            }
                        }
                    }
                }
            }
            return(null);
        }
Пример #3
0
        GetFamilySymbol(Autodesk.Revit.DB.Family fam, string famSymName)
        {
            // jeremy migrated from Revit 2014 to 2015:
            //FamilySymbolSetIterator famSymSetIter = fam.Symbols.ForwardIterator(); // 'Autodesk.Revit.DB.Family.Symbols' is obsolete: 'This property is obsolete in Revit 2015.  Use Family.GetFamilySymbolIds() instead.'
            //while( famSymSetIter.MoveNext() )
            //{
            //  FamilySymbol famSymTemp = famSymSetIter.Current as FamilySymbol;

            Document doc = fam.Document;

            foreach (ElementId id in fam.GetFamilySymbolIds())
            {
                FamilySymbol famSymTemp = doc.GetElement(id)
                                          as FamilySymbol;

                if (famSymTemp != null)
                {
                    if (famSymTemp.Name == famSymName)
                    {
                        return(famSymTemp);
                    }
                }
            }
            return(null);
        }
Пример #4
0
        public static Dictionary <string, object> IsInPlace(Revit.Elements.Element[] element)
        {
            List <bool> list = new List <bool>();
            var         doc  = DocumentManager.Instance.CurrentDBDocument;

            foreach (var i in element)
            {
                try
                {
                    AD.ElementId      id        = Elements.UnwrapElement(i);
                    AD.Element        elem      = doc.GetElement(id) as AD.Element;
                    AD.FamilyInstance elFamInst = elem as AD.FamilyInstance;
                    AD.Family         elFam     = elFamInst.Symbol.Family;
                    if (elFam.IsInPlace)
                    {
                        list.Add(true);
                    }
                    else
                    {
                        list.Add(false);
                    }
                }
                catch
                {
                }
            }
            bool contain = list.Any(item => item);

            return(new Dictionary <string, object>
            {
                { "Boolean List", list },
                { "Any True", contain }
            });
        }
Пример #5
0
 public bool OnSharedFamilyFound(
     Autodesk.Revit.DB.Family sharedFamily,
     bool familyInUse,
     out FamilySource source,
     out bool overwriteParameterValues)
 {
     overwriteParameterValues = false;
     source = FamilySource.Family;
     return(true);
 }
Пример #6
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Autodesk.Revit.DB.Family family = null;
            if (!DA.GetData("Family", ref family))
            {
                return;
            }

            DA.SetDataList("Types", family?.GetFamilySymbolIds());
        }
Пример #7
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            DB.Family family = null;
            if (!DA.GetData("Family", ref family))
            {
                return;
            }

            DA.SetDataList("Types", family?.GetFamilySymbolIds().Select(x => Types.ElementType.FromElementId(family.Document, x)));
        }
Пример #8
0
        public Result LoadTitleblock()
        {

            //GET THE REVIT LIBRARY PATH AS DEFINED VIA THE OPTIONS DIALOG - FILE LOCATIONS TAB - PLACES BUTTON
            string libraryPath = "";
            revitUIApp.Application.GetLibraryPaths().TryGetValue("Imperial Library", out libraryPath);

            if (string.IsNullOrEmpty(libraryPath))
            {
                libraryPath = "c:\\";   //DEFAULT PATH
            }

            //ALLOW THE USER TO SELECT A FAMILY FILE.
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = libraryPath;
            openFileDialog1.Filter = "Family Files (*.rfa)|*.rfa";

            //LOAD THE FAMILY FILE
            if (DialogResult.OK == openFileDialog1.ShowDialog())
            {

                //CREATE TRANSACTION
                Transaction trans = new Transaction(revitDoc, "Load Titleblock");
                trans.Start();

                Autodesk.Revit.DB.Family family = null;
                if (revitDoc.LoadFamily(openFileDialog1.FileName, out family))
                {
                    
                    //LOADS ALL TITLEBLOCKS
                    //CREATE A FILTER TO GET ALL THE TITLEBLOCK TYPES
                    FilteredElementCollector titleblockCollector = new FilteredElementCollector(revitDoc);
                    titleblockCollector.OfCategory(BuiltInCategory.OST_TitleBlocks);
                    titleblockCollector.WhereElementIsElementType();

                    this.cbTitleblocks.Items.Clear(); //CLEARS ALL TITLEBLOCKS IN THE LIST AND RELOADS ALL TO INCLUDE THE RECENTLY ADDED TITLEBLOCK

                    this.GetAllTitleblocks(titleblockCollector); //FILLS COMBOBOX WITH ALL THE TITLEBLOCKS IN THE DOCUMENT

                }
                else
                {
                    TaskDialog.Show("Revit", "Can't load the family file.");
                    return Result.Failed;
                }

                trans.Commit();

            }

            return Result.Succeeded;
        }
Пример #9
0
        void Btn_LoadFamilyClick(object sender, EventArgs e)
        {
            // Check if the family is loaded in the project
            Autodesk.Revit.DB.Family family = funct.FindFamilyByName(doc1, typeof(Family), familyName) as Autodesk.Revit.DB.Family;

            if (null == family)
            {
                funct.LoadFamilyinRevit(doc1, GetFilePath(), family);
                Status("Point family loaded.", false);
            }
            else
            {
                TaskDialog.Show("Info", "The family is already present in the project!", TaskDialogCommonButtons.Ok, TaskDialogResult.Ok);
            }
        }
Пример #10
0
        GetFamilySymbol(Autodesk.Revit.DB.Family fam, string famSymName)
        {
            FamilySymbolSetIterator famSymSetIter = fam.Symbols.ForwardIterator();

            while (famSymSetIter.MoveNext())
            {
                FamilySymbol famSymTemp = famSymSetIter.Current as FamilySymbol;
                if (famSymTemp != null)
                {
                    if (famSymTemp.Name == famSymName)
                    {
                        return(famSymTemp);
                    }
                }
            }
            return(null);
        }
Пример #11
0
        void Btn_CreateClick(object sender, EventArgs e)
        {
            Autodesk.Revit.DB.Family family = funct.FindFamilyByName(doc1, typeof(Family), familyName) as Autodesk.Revit.DB.Family;

            if (null == family)
            {
                TaskDialog.Show("Error", "The family is not loaded!", TaskDialogCommonButtons.Ok, TaskDialogResult.Ok);
            }
            else
            {
                double x = 0;
                double y = 0;
                double z = 0;

                if (double.TryParse(txt_X1.Text, out x) && double.TryParse(txt_Y1.Text, out y) && double.TryParse(txt_Z1.Text, out z))
                {
                    if (rdbtn_meter.Checked)
                    {
                        x = UnitUtils.Convert(x, DisplayUnitType.DUT_METERS, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
                        y = UnitUtils.Convert(y, DisplayUnitType.DUT_METERS, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
                        z = UnitUtils.Convert(z, DisplayUnitType.DUT_METERS, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
                    }


                    // Step 1 : Get the Project Base Point (PBP).
                    Tuple <XYZ, double> basePoint = funct.GetProjectBasePoint(doc1);

                    //Step 2 : Determine the relative distance of the palcement point with respect to the PBP
                    XYZ relativePoint = funct.GetRelativeDistanceTobasePoint(basePoint, new XYZ(x, y, z));

                    // Step 3 : Incase the True North is rotated, As the Co-Ordinate asis is fixed, we need to move the point in clockwise direction.
                    XYZ rotated = funct.RotatePointClockwise(relativePoint.X, relativePoint.Y, relativePoint.Z, basePoint.Item2);


                    Autodesk.Revit.DB.FamilySymbol fs = funct.GetFamilySymbol(doc1);

                    try {
                        using (Transaction tx = new Transaction(doc1)) {
                            tx.Start("Create Adaptive Component");
                            funct.CreateOrMoveAdaptiveComponent(doc1, rotated, fs);
                            tx.Commit();
                        }

                        Clean_Text();
                        string result;

                        if (rdbtn_meter.Checked)
                        {
                            result = "Point created @  " + "(" + UnitUtils.Convert(rotated.X, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES, DisplayUnitType.DUT_METERS).ToString("#.000") + " m " + "," + UnitUtils.Convert(rotated.Y, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES, DisplayUnitType.DUT_METERS).ToString("#.000") + " m " + "," + UnitUtils.Convert(rotated.Z, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES, DisplayUnitType.DUT_METERS).ToString("#.000") + " m " + ")";
                        }
                        else
                        {
                            result = "Point created @ " + "(" + (rotated.X).ToString("#.000") + "'" + "," + (rotated.Y).ToString("#.000") + "'" + "," + (rotated.Z).ToString("#.000") + "'" + ")";
                        }

                        Status(result, false);
                    } catch (Exception) {
                        Status("Failed to create point", true);
                    }
                }
                else
                {
                    TaskDialog.Show("Error", "Please enter the X,Y and Z Co-Ordinates.", TaskDialogCommonButtons.Ok, TaskDialogResult.Ok);
                }
            }
        }
Пример #12
0
        public static Dictionary <string, object> ByRoom(string familyTemplatePath, global::Revit.Elements.Room room, string materialName, global::Revit.Elements.Category category, string subcategory = "")
        {
            //variables
            global::Revit.Elements.Element   famInstance = null;
            Autodesk.Revit.DB.FamilyInstance internalFam = null;
            bool fileFound = false;

            //the current document
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            UIApplication uiapp            = new UIApplication(doc.Application);

            //convert the room to an Autodesk.Revit.DB representation
            Autodesk.Revit.DB.Architecture.Room internalRoom = (Autodesk.Revit.DB.Architecture.Room)room.InternalElement;
            string name = internalRoom.Name;

            //we close all of the families because we need to swap documents
            foreach (Document d in uiapp.Application.Documents)
            {
                if (d.IsFamilyDocument)
                {
                    d.Close(false);
                }
            }
            //create the new family document in the background and store it in memory
            Document familyDocument = uiapp.Application.NewFamilyDocument(familyTemplatePath);
            //instantiate a material element id and try to get the material that was specified
            ElementId material = null;
            FilteredElementCollector materialCollector = new FilteredElementCollector(familyDocument).OfClass(typeof(Autodesk.Revit.DB.Material));

            foreach (var m in materialCollector)
            {
                if (m.Name.ToLower().Replace(" ", "") == materialName.ToLower().Replace(" ", ""))
                {
                    material = m.Id;
                }
            }
            //close Dynamo's open transaction, we need to do this because we open a new Revit API transaction in the family document (This is document switching)
            TransactionManager.Instance.ForceCloseTransaction();
            //start creating the families.
            Transaction trans = new Transaction(familyDocument, "Generate Families Ya'll");

            trans.Start();
            //set the family category
            Autodesk.Revit.DB.Category familyCategory = familyDocument.Settings.Categories.get_Item(category.Name);
            familyDocument.OwnerFamily.FamilyCategory = familyCategory;
            //get the subcategory for the solids
            Autodesk.Revit.DB.Category subCategory = null;
            foreach (Autodesk.Revit.DB.Category c in familyCategory.SubCategories)
            {
                if (c.Name.ToLower() == subcategory.ToLower())
                {
                    subCategory = c;
                }
            }
            //get the height of the thing
            double height = room.Height;
            //get the curves
            IList <IList <BoundarySegment> > boundary = internalRoom.GetBoundarySegments(new SpatialElementBoundaryOptions());

            //generate a plane
            Autodesk.Revit.DB.Plane       revitPlane  = Autodesk.Revit.DB.Plane.CreateByNormalAndOrigin(Vector.ZAxis().ToXyz(), new XYZ(0, 0, 0));
            Autodesk.Revit.DB.SketchPlane sketchPlane = SketchPlane.Create(familyDocument, revitPlane);
            //the curve arrays to generate solids and voids in family
            CurveArray    curveArray        = new CurveArray();
            CurveArrArray curveArrArray     = new CurveArrArray();
            CurveArray    curveArrayVoid    = new CurveArray();
            CurveArrArray curveArrArrayVoid = new CurveArrArray();
            //to perform  the cut action on the solid with the voids
            CombinableElementArray ceArray = new CombinableElementArray();
            //transform bizness
            Point            roomCentroid  = room.BoundingBox.ToCuboid().Centroid();
            Point            locationPoint = Point.ByCoordinates(roomCentroid.X, roomCentroid.Y, 0);
            CoordinateSystem oldCS         = CoordinateSystem.ByOrigin(locationPoint);
            CoordinateSystem newCS         = CoordinateSystem.ByOrigin(0, 0, 0);

            //flag to step through the boundaries.
            int flag = 0;

            while (flag < boundary.Count)
            {
                //the first set of curves is the solid's boundary
                if (flag == 0)
                {
                    //generate the solid form which is the first item in the boundary segments.
                    foreach (BoundarySegment b in boundary[flag])
                    {
                        Autodesk.DesignScript.Geometry.Curve c          = b.GetCurve().ToProtoType();
                        Autodesk.DesignScript.Geometry.Curve movedCurve = c.Transform(oldCS, newCS) as Autodesk.DesignScript.Geometry.Curve;
                        curveArray.Append(movedCurve.ToRevitType());
                    }
                    curveArrArray.Append(curveArray);
                    Extrusion solidExtrusion = familyDocument.FamilyCreate.NewExtrusion(true, curveArrArray, sketchPlane, height);
                    if (material != null)
                    {
                        //Set the material
                        Autodesk.Revit.DB.Parameter matParam = solidExtrusion.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM);
                        matParam.Set(material);
                    }
                    //try to set the subcategory
                    if (subCategory != null)
                    {
                        solidExtrusion.Subcategory = subCategory;
                    }
                }
                //subsequent lists of curves are representative of the voids
                else
                {
                    //clear the curves from the collection for all items after the second one. (index 2+)
                    if (!curveArrayVoid.IsEmpty)
                    {
                        curveArrayVoid.Clear();
                        curveArrArrayVoid.Clear();
                        ceArray.Clear();
                    }
                    //generate the void form
                    foreach (BoundarySegment b in boundary[flag])
                    {
                        Autodesk.DesignScript.Geometry.Curve c          = b.GetCurve().ToProtoType();
                        Autodesk.DesignScript.Geometry.Curve movedCurve = c.Transform(oldCS, newCS) as Autodesk.DesignScript.Geometry.Curve;
                        curveArrayVoid.Append(movedCurve.ToRevitType());
                    }
                    curveArrArrayVoid.Append(curveArrayVoid);
                    Extrusion voidExtrusion = familyDocument.FamilyCreate.NewExtrusion(false, curveArrArrayVoid, sketchPlane, height);

                    //try to combine things
                    foreach (Extrusion genericForm in new FilteredElementCollector(familyDocument).OfClass(typeof(Extrusion))
                             .Cast <Extrusion>())
                    {
                        ceArray.Append(genericForm);
                    }
                    //to add the void to the solid
                    familyDocument.CombineElements(ceArray);
                }
                flag++;
            }
            familyDocument.Regenerate();
            trans.Commit();

            Autodesk.Revit.DB.Family fam = null;
            //build the temporary path
            string familyFilePath = Path.GetTempPath() + name + ".rfa";

            SaveAsOptions opt = new SaveAsOptions();

            opt.OverwriteExistingFile = true;
            familyDocument.SaveAs(familyFilePath, opt);
            familyDocument.Close(false);

            TransactionManager.Instance.ForceCloseTransaction();
            Transaction trans2 = new Transaction(doc, "Attempting to place or update Room family instances.");

            trans2.Start();
            IFamilyLoadOptions loadOptions = new FamilyImportOptions();
            bool variable = true;

            loadOptions.OnFamilyFound(true, out variable);
            doc.LoadFamily(familyFilePath, loadOptions, out fam);

            FamilySymbol familySymbol = (FamilySymbol)doc.GetElement(fam.GetFamilySymbolIds().First());
            //try to find if it is placed already
            FilteredElementCollector col = new FilteredElementCollector(doc);
            //get built in category from user viewable category
            BuiltInCategory myCatEnum =
                (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());

            foreach (Autodesk.Revit.DB.Element e in col.WhereElementIsNotElementType().OfCategory(myCatEnum).ToElements())
            {
                Autodesk.Revit.DB.FamilySymbol type = (FamilySymbol)doc.GetElement(e.GetTypeId());
                if (type.FamilyName.Equals(name))
                {
                    fileFound   = true;
                    internalFam = e as Autodesk.Revit.DB.FamilyInstance;
                }
            }
            //place families that are not placed
            if (fileFound == false)
            {
                if (!familySymbol.IsActive)
                {
                    familySymbol.Activate();
                }

                internalFam = doc.Create.NewFamilyInstance(new XYZ(roomCentroid.X, roomCentroid.Y, 0), familySymbol, internalRoom.Level,
                                                           StructuralType.NonStructural);
            }
            trans2.Commit();
            //delete the temp file
            File.Delete(familyFilePath);
            //cast to Dynamo type for output and location updating (if necessary)
            famInstance = internalFam.ToDSType(true);
            if (fileFound)
            {
                famInstance.SetLocation(locationPoint);
            }
            //returns the outputs
            var outInfo = new Dictionary <string, object>
            {
                { "familyInstance", famInstance }
            };

            return(outInfo);
        }
Пример #13
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Autodesk.Revit.DB.Family family = null;
            if (!DA.GetData("Family", ref family))
            {
                return;
            }

            var filePath = string.Empty;

            DA.GetData("Path", ref filePath);

            var overrideFile = false;

            if (!DA.GetData("OverrideFile", ref overrideFile))
            {
                return;
            }

            var compact = false;

            if (!DA.GetData("Compact", ref compact))
            {
                return;
            }

            var backups = -1;

            if (!DA.GetData("Backups", ref backups))
            {
                return;
            }

            if (Revit.ActiveDBDocument.EditFamily(family) is Document familyDoc)
            {
                using (familyDoc)
                {
                    try
                    {
                        var options = new SaveAsOptions()
                        {
                            OverwriteExistingFile = overrideFile, Compact = compact
                        };
                        if (backups > -1)
                        {
                            options.MaximumBackups = backups;
                        }

                        if (string.IsNullOrEmpty(filePath))
                        {
                            filePath = familyDoc.PathName;
                        }

                        if (string.IsNullOrEmpty(filePath))
                        {
                            filePath = familyDoc.Title;
                        }

                        if (Directory.Exists(filePath))
                        {
                            filePath = Path.Combine(filePath, filePath);
                        }

                        if (!Path.HasExtension(filePath))
                        {
                            filePath += ".rfa";
                        }

                        if (Path.IsPathRooted(filePath))
                        {
                            familyDoc.SaveAs(filePath, options);
                            DA.SetData("Family", family);
                        }
                        else
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Path should be absolute.");
                        }
                    }
                    catch (Autodesk.Revit.Exceptions.InvalidOperationException e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message); }
                    finally { familyDoc.Close(false); }
                }
            }
            else
            {
                DA.SetData("Family", null);
            }
        }
Пример #14
0
 public FamilyAdapter(Rvt.Family rvtFamily)
 {
     family = rvtFamily;
 }
Пример #15
0
 public Family(DB.Family family) : base(family)
 {
 }
Пример #16
0
        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                {
                    MessageBox.Show("The Task Has Been Cancelled", "Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    progressBar1.Value  = 0;
                    StatusLabel.Visible = false;
                }
                else if (e.Error != null)
                {
                    MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    progressBar1.Value  = 0;
                    StatusLabel.Visible = false;
                }
                else
                {
                    RevitServices.Transactions.TransactionManager.Instance.ForceCloseTransaction();

                    var distinctItems = windowFamilies.GroupBy(x => x.Id).Select(y => y.First()); //Make List Have Only Unique Families

                    Document famDoc;

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

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

                            try
                            {
                                FamilyParameter newParam = familyManager.AddParameter("Fire_Rating", BuiltInParameterGroup.PG_IDENTITY_DATA, ParameterType.Text, true);
                            }
                            catch
                            {
                                //silent catch to continue if Fire_Rating is already on a door from a previous activation
                            }


                            t.Commit();

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


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

                        foreach (var item in windowElementsDictionary)
                        {
                            ParameterSet ps = item.Key.Parameters;

                            foreach (Parameter p in ps)
                            {
                                if (p.Definition.Name == "Fire_Rating")
                                {
                                    p.Set(item.Value);
                                }
                            }
                        }


                        t.Commit();
                    }


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


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


            buttonCancel.Enabled = false;
            StatusLabel.Visible  = false;
        }
Пример #17
0
 bool DB.IFamilyLoadOptions.OnSharedFamilyFound(DB.Family sharedFamily, bool familyInUse, out DB.FamilySource source, out bool overwriteParameterValues)
 {
     source = DB.FamilySource.Family;
     overwriteParameterValues = !familyInUse | OverrideParameters;
     return(!familyInUse | OverrideFamily);
 }
Пример #18
0
        private void backgroundWorker4_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                {
                    MessageBox.Show("The Task Has Been Cancelled", "Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    progressBar1.Value  = 0;
                    StatusLabel.Visible = false;
                }
                else if (e.Error != null)
                {
                    MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    progressBar1.Value  = 0;
                    StatusLabel.Visible = false;
                }
                else
                {
                    RevitServices.Transactions.TransactionManager.Instance.ForceCloseTransaction();


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

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

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

                            try
                            {
                                ///delete here
                                ///

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

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

                            t.Commit();

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



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

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

            deleteParametersWindows.Clear();

            buttonCancel.Enabled = false;
            StatusLabel.Visible  = false;
        }
Пример #19
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            DB.Family family = null;
            if (!DA.GetData("Family", ref family))
            {
                return;
            }

            var filePath = string.Empty;

            DA.GetData("Path", ref filePath);

            var overrideFile = false;

            if (!DA.GetData("OverrideFile", ref overrideFile))
            {
                return;
            }

            var compact = false;

            if (!DA.GetData("Compact", ref compact))
            {
                return;
            }

            var backups = -1;

            if (!DA.GetData("Backups", ref backups))
            {
                return;
            }

            if (Revit.ActiveDBDocument.EditFamily(family) is DB.Document familyDoc)
            {
                using (familyDoc)
                {
                    var view = default(DB.View);
                    if (DA.GetData("PreviewView", ref view))
                    {
                        if (!view.Document.Equals(familyDoc))
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"View '{view.Title}' is not a valid view in document {familyDoc.Title}");
                            return;
                        }
                    }

                    try
                    {
                        if (string.IsNullOrEmpty(filePath))
                        {
                            if (overrideFile)
                            {
                                using (var saveOptions = new DB.SaveOptions()
                                {
                                    Compact = compact
                                })
                                {
                                    if (view is object)
                                    {
                                        saveOptions.PreviewViewId = view.Id;
                                    }

                                    familyDoc.Save(saveOptions);
                                    DA.SetData("Family", family);
                                }
                            }
                            else
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Failed to collect data from 'Path'.");
                            }
                        }
                        else
                        {
                            bool isFolder = filePath.Last() == Path.DirectorySeparatorChar;
                            if (isFolder)
                            {
                                filePath = Path.Combine(filePath, familyDoc.Title);
                            }

                            if (Path.IsPathRooted(filePath) && filePath.Contains(Path.DirectorySeparatorChar))
                            {
                                if (!Path.HasExtension(filePath))
                                {
                                    filePath += ".rfa";
                                }

                                using (var saveAsOptions = new DB.SaveAsOptions()
                                {
                                    OverwriteExistingFile = overrideFile, Compact = compact
                                })
                                {
                                    if (backups > -1)
                                    {
                                        saveAsOptions.MaximumBackups = backups;
                                    }

                                    if (view is object)
                                    {
                                        saveAsOptions.PreviewViewId = view.Id;
                                    }

                                    familyDoc.SaveAs(filePath, saveAsOptions);
                                    DA.SetData("Family", family);
                                }
                            }
                            else
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Path should be absolute.");
                            }
                        }
                    }
                    catch (Autodesk.Revit.Exceptions.InvalidOperationException e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message); }
                    finally
                    {
                        familyDoc.Release();
                    }
                }
            }
        }
        public static int copy(Equipment target)
        {
            int id = -1;
            ////
            Transaction tr = null;

            try
            {
                File.Create(target.name + ".rfa").Close();
                File.WriteAllBytes(target.name + ".rfa", target.bytedFile);

                Document doc = commandData.Application.ActiveUIDocument.Document;
                Autodesk.Revit.DB.Family family = null;

                tr = new Transaction(doc);
                tr.Start("My Super trans");
                //попытка найти существующее семейство
                var  search = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Cast <FamilySymbol>().ToList();
                bool good   = false;
                foreach (FamilySymbol symbq in search)
                {
                    if (symbq.Family.Name == target.name)
                    {
                        if (!symbq.IsActive)
                        {
                            symbq.Activate();
                        }
                        var buffInstance = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), symbq, structuralType: Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                        buffInstance.Id.ToString();
                        id   = Convert.ToInt32(buffInstance.Id.ToString());
                        good = true;
                        break;
                    }
                }
                tr.Commit();
            }
            catch (Exception ex)
            {
                id = -1;
                try
                {
                    tr.Commit();
                }
                catch (Exception eeee)
                {
                }
            }
            if (id == -1)
            {
                id = -1;
                ////
                int max = int.MinValue;
                foreach (var i in Schemes_Editor.mainWorkList)
                {
                    if (i.localID > max)
                    {
                        max = i.localID;
                    }
                }
                max++;
                return(max);
            }
            return(id);
        }
Пример #21
0
 public static Family Wrap(Autodesk.Revit.DB.Family ele, bool isRevitOwned)
 {
     return(Family.FromExisting(ele, isRevitOwned));
 }
Пример #22
0
        public Result LoadFamilyinRevit(Autodesk.Revit.DB.Document document, string familyPath, Autodesk.Revit.DB.Family family)
        {
            if (null == familyPath)
            {
                familyPath = Path.Combine(familyPath, familyName);
                familyPath = Path.ChangeExtension(familyPath, _family_ext);
            }
            if (!File.Exists(familyPath))
            {
                TaskDialog.Show("Error", "Please ensure that the family :" + familyName + "exist in the given path :" + familyPath, TaskDialogCommonButtons.Close, TaskDialogResult.Close);
                return(Result.Failed);
            }

            using (Transaction trans = new Autodesk.Revit.DB.Transaction(document)) {
                trans.Start("LoadFamily");
                document.LoadFamily(familyPath, out family);
                trans.Commit();
            }
            return(Result.Succeeded);
        }
Пример #23
0
    public Result Execute(
        ExternalCommandData commandData,
        ref string message,
        ElementSet elements)
    {
        UIApplication uiApp = commandData.Application;

        string      keystr    = @"Software\FamilyToDWG";
        string      revityear = "2017";
        string      subkeystr = "TemplateLocation" + revityear;
        RegistryKey key       = Registry.CurrentUser.OpenSubKey(keystr, true);

        if (key == null)
        {
            key = Registry.CurrentUser.CreateSubKey(keystr);
            key.SetValue(subkeystr, "");
        }

        if (key.GetValue(subkeystr, null).ToString() == "" || File.Exists(key.GetValue(subkeystr).ToString()) == false)
        {
            var templateFD = new OpenFileDialog();
            templateFD.Filter = "rte files (*.rte)|*.rte";
            templateFD.Title  = "Choose a Template";
            templateFD.ShowDialog();
            string docdir = templateFD.FileName;
            key.SetValue(subkeystr, @docdir);
        }

        if (key.GetValue(subkeystr, null).ToString() == null)
        {
            return(Result.Failed);
        }

        Autodesk.Revit.DB.Document uiDoc;

        try
        {
            uiDoc = uiApp.Application.NewProjectDocument(key.GetValue(subkeystr).ToString());
        }
        catch
        {
            return(Result.Failed);
        }

        if (uiDoc == null)
        {
            return(Result.Failed);
        }

        if (!Directory.Exists(@"C:\temp\"))
        {
            Directory.CreateDirectory(@"C:\temp\");
        }

        if (File.Exists(@"C:\temp\new_project.rvt"))
        {
            File.Delete(@"C:\temp\new_project.rvt");
        }

        SaveAsOptions options1 = new SaveAsOptions();

        options1.OverwriteExistingFile = true;
        uiDoc.SaveAs(@"C:/temp/new_project.rvt", options1);

        uiApp.OpenAndActivateDocument(@"C:/temp/new_project.rvt");

        var FD = new OpenFileDialog();

        FD.Filter = "rfa files (*.rfa)|*.rfa";
        FD.Title  = "Choose A RevitRFA Family file";
        FD.ShowDialog();

        string filename = FD.SafeFileName;
        string filedir  = FD.FileName.Replace(filename, "");

        if (File.Exists(FD.FileName))
        {
            using (Transaction tx = new Transaction(uiDoc))
            {
                tx.Start("Load Family");
                Autodesk.Revit.DB.Family family = null;
                uiDoc.LoadFamily(FD.FileName, out family);
                tx.Commit();

                string name = family.Name;
                foreach (ElementId id in family.GetFamilySymbolIds())
                {
                    FamilySymbol famsymbol = family.Document.GetElement(id) as FamilySymbol;
                    XYZ          origin    = new XYZ(0, 0, 0);
                    tx.Start("Load Family Member");
                    famsymbol.Activate();
                    FamilyInstance instance = uiDoc.Create.NewFamilyInstance(origin, famsymbol, StructuralType.NonStructural);
                    tx.Commit();

                    DWGExportOptions options = new DWGExportOptions();
                    options.FileVersion             = ACADVersion.R2007;
                    options.ExportOfSolids          = SolidGeometry.ACIS;
                    options.HideUnreferenceViewTags = true;
                    //options.FileVersion = (ACADVersion)(3);

                    var collector = new FilteredElementCollector(uiDoc);

                    var viewFamilyType = collector
                                         .OfClass(typeof(ViewFamilyType))
                                         .OfType <ViewFamilyType>()
                                         .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);

                    // Export the active view
                    ICollection <ElementId> views = new List <ElementId>();
                    tx.Start("ChangeView");
                    View3D view = View3D.CreateIsometric(uiDoc, viewFamilyType.Id);
                    view.DisplayStyle = DisplayStyle.Shading;
                    tx.Commit();
                    views.Add(view.Id);
                    string dwgfilename     = famsymbol.Name + ".dwg";
                    string dwgfullfilename = filedir + dwgfilename;
                    if (File.Exists(dwgfullfilename))
                    {
                        File.Delete(dwgfullfilename);
                    }
                    uiDoc.Export(@filedir, @dwgfilename, views, options);

                    tx.Start("Delete Family Member");
                    uiDoc.Delete(instance.Id);
                    tx.Commit();
                }
            }
        }
        else
        {
            Console.WriteLine("Please Create Export Directory For the chosen CAPS file.");
        }

        return(Result.Succeeded);
    }
        public static int createInstance(byte[] bytes, string familyname)
        {
            Transaction tr = null;
            int         id = -1;

            try
            {
                File.Create(familyname + ".rfa").Close();
                File.WriteAllBytes(familyname + ".rfa", bytes);
                Document doc = commandData.Application.ActiveUIDocument.Document;
                Autodesk.Revit.DB.Family family = null;

                tr = new Transaction(doc);
                tr.Start("My Super trans");
                //попытка найти существующее семейство
                var  search = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Cast <FamilySymbol>().ToList();
                bool good   = false;
                foreach (FamilySymbol symbq in search)
                {
                    if (symbq.Family.Name == familyname)
                    {
                        if (!symbq.IsActive)
                        {
                            symbq.Activate();
                        }
                        var buffInstance = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), symbq, structuralType: Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                        buffInstance.Id.ToString();
                        id   = Convert.ToInt32(buffInstance.Id.ToString());
                        good = true;
                        break;
                    }
                }
                if (!good)
                {
                    doc.LoadFamily(familyname + ".rfa", out family);

                    var fsym = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Cast <FamilySymbol>().ToList();

                    String name = family.Name;
                    foreach (FamilySymbol symbq in fsym)
                    {
                        if (symbq.Family.Name == name)
                        {
                            if (!symbq.IsActive)
                            {
                                symbq.Activate();
                            }
                            var buffInstance = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), symbq, structuralType: Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                            buffInstance.Id.ToString();
                            id = Convert.ToInt32(buffInstance.Id.ToString());
                            break;
                        }
                    }
                }
                tr.Commit();
            }
            catch (Exception ex)
            {
                id = -1;
                try
                {
                    tr.Commit();
                }
                catch (Exception eeee)
                {
                }
            }
            return(id);
        }