Category GetCategory(
            Document doc,
            BuiltInCategory target)
        {
            Category cat = null;

            if (target.Equals(BuiltInCategory.OST_IOSModelGroups))
            {
                // determine model group category:

                FilteredElementCollector collector
                    = Util.GetElementsOfType(doc, typeof(Group), // GroupType works as well
                                             BuiltInCategory.OST_IOSModelGroups);

                IList <Element> modelGroups = collector.ToElements();

                if (0 == modelGroups.Count)
                {
                    Util.ErrorMsg("Please insert a model group.");
                    return(cat);
                }
                else
                {
                    cat = modelGroups[0].Category;
                }
            }
            else
            {
                try
                {
                    cat = doc.Settings.Categories.get_Item(target);
                }
                catch (Exception ex)
                {
                    Util.ErrorMsg(string.Format(
                                      "Error obtaining document {0} category: {1}",
                                      target.ToString(), ex.Message));
                    return(cat);
                }
            }
            if (null == cat)
            {
                Util.ErrorMsg(string.Format(
                                  "Unable to obtain the document {0} category.",
                                  target.ToString()));
            }
            return(cat);
        }
        private int ConnectionCheck(Connector con)
        {
            int          tempInt        = 0;
            ConnectorSet secondary      = con.AllRefs;
            ConnectorSet TempConnectors = null;

            foreach (Connector f in secondary)
            {
                Element         tempElem = this._doc.GetElement(f.Owner.Id);
                Category        cat      = tempElem.Category;
                BuiltInCategory enumCat  = (BuiltInCategory)cat.Id.IntegerValue;

                if (enumCat.ToString() == "OST_FabricationDuctwork")
                {
                    TempConnectors = this.getConnectorSetFromElement(tempElem);
                }
            }

            if (TempConnectors != null)
            {
                foreach (Connector connec in TempConnectors)
                {
                    if (MainForm.CloseEnoughForMe(connec.Origin.X, con.Origin.X) &&
                        MainForm.CloseEnoughForMe(connec.Origin.Y, con.Origin.Y) &&
                        MainForm.CloseEnoughForMe(connec.Origin.Z, con.Origin.Z))
                    {
                        tempInt = 1;
                    }
                }
            }

            return(tempInt);
        }
Esempio n. 3
0
        private int ConnectionCheck(Connector con)
        {
            List <string> categorias     = new List <string>(new string[] { "OST_CableTrayFitting", "OST_CableTray", "OST_ConduitFitting", "OST_Conduit", "OST_DuctFitting", "OST_DuctCurves", "OST_DuctAccessory", "OST_FabricationParts", "OST_FabricationPipework", "OST_FabricationHangers", "OST_PipeAccessory", "OST_PipeFitting", "OST_PipeCurves", "OST_FabricationDuctwork" });
            int           tempInt        = 0;
            ConnectorSet  secondary      = con.AllRefs;
            ConnectorSet  TempConnectors = null;

            foreach (Connector f in secondary)
            {
                Element         tempElem = _doc.GetElement(f.Owner.Id);
                Category        cat      = tempElem.Category;
                BuiltInCategory enumCat  = (BuiltInCategory)cat.Id.IntegerValue;

                if (categorias.Contains(enumCat.ToString()))
                {
                    TempConnectors = getConnectorSetFromElement(tempElem);
                    foreach (Connector connec in TempConnectors)
                    {
                        if (MainForm.CloseEnoughForMe(connec.Origin.X, con.Origin.X) &&
                            MainForm.CloseEnoughForMe(connec.Origin.Y, con.Origin.Y) &&
                            MainForm.CloseEnoughForMe(connec.Origin.Z, con.Origin.Z))
                        {
                            tempInt = 1;
                        }
                    }
                }
            }

            if (TempConnectors != null)
            {
            }

            return(tempInt);
        }
Esempio n. 4
0
        /// <summary>
        /// Return the first family symbol found in the given document
        /// matching the given built-in category or null if none is found.
        /// </summary>
        public static FamilySymbol GetFirstFamilySymbol(Document doc, BuiltInCategory bic)
        {
            FamilySymbol s = GetFamilySymbols(doc, bic).FirstElement() as FamilySymbol;

            Debug.Assert(s != null, $"expected at least one {bic.ToString()} symbol in project");

            return(s);
        }
Esempio n. 5
0
 public static string Description(
     this BuiltInCategory bic)
 {
     //string s = bic.ToString().ToLower();
     //s = s.Substring(4);
     //s = s.Substring(0, s.Length - 1);
     //return s;
     return(bic.ToString().ToLower());
 }
Esempio n. 6
0
        /// <summary>
        /// Return a descriptive string for a built-in
        /// category by removing the trailing plural 's'
        /// and the OST_ prefix.
        /// </summary>
        public static string Description(this BuiltInCategory bic)
        {
            string s = bic.ToString().ToLower();

            s = s.Substring(4);
            Debug.Assert(s.EndsWith("s"), "expected plural suffix 's'");
            s = s.Substring(0, s.Length - 1);
            return(s);
        }
Esempio n. 7
0
        public static void ListCategory(UIDocument uiDoc)
        {
            Document  currentDoc = uiDoc.Document;
            Selection sel        = uiDoc.Selection;

            Reference       Object    = sel.PickObject(ObjectType.Element);
            Element         ele       = currentDoc.GetElement(Object.ElementId);
            BuiltInCategory mycatenum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), ele.Category.Id.IntegerValue.ToString());

            TaskDialog.Show("Category", ele.Category.Name + "\r\n" + mycatenum.ToString());
        }
Esempio n. 8
0
        public static string GetTableKey(Category category, bool isSymbol)
        {
            if (category == null)
            {
                return(null);
            }
            BuiltInCategory integerValue = (BuiltInCategory)category.Id.IntegerValue;
            string          str          = isSymbol ? "_SYMBOL" : "_INSTANCE";

            return("TabN_" + integerValue.ToString() + str);
        }
        /// <summary>
        /// Return the first family symbol found in the given document
        /// matching the given built-in category or null if none is found.
        /// </summary>
        public static FamilySymbol GetFirstFamilySymbol(
            Document doc,
            BuiltInCategory bic)
        {
            FamilySymbol s = GetFamilySymbols(doc, bic).FirstElement() as FamilySymbol;

            Debug.Assert(null != s, string.Format(
                             "expected at least one {0} symbol in project",
                             bic.ToString()));

            return(s);
        }
Esempio n. 10
0
        /// <summary>
        /// Save an element on a temporary list and override its color
        /// </summary>
        public static void AddToSelection(Element ReferenceElem, List <string> ListElemntsStrings, List <Element> completeList, bool checkBox)
        {
            Category        category      = ReferenceElem.Category;
            BuiltInCategory enumCategory  = (BuiltInCategory)category.Id.IntegerValue;
            BuiltInCategory builtCategory = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), ReferenceElem.Category.Id.ToString());

            if (checkBox == true)
            {
                foreach (Element elem in completeList)
                {
                    Category        cat     = elem.Category;
                    BuiltInCategory enumCat = (BuiltInCategory)cat.Id.IntegerValue;

                    if (enumCat.ToString() == "OST_FabricationDuctwork" &&
                        getNumber(elem) == "" && elem.get_Parameter(BuiltInParameter.FABRICATION_PART_DEPTH_IN) != null)
                    {
                        if (filterParam(ReferenceElem, elem, BuiltInParameter.ELEM_FAMILY_PARAM,
                                        BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM, BuiltInParameter.FABRICATION_PART_DEPTH_IN,
                                        BuiltInParameter.FABRICATION_PART_WIDTH_IN, BuiltInParameter.FABRICATION_SERVICE_PARAM,
                                        BuiltInParameter.FABRICATION_PART_LENGTH))
                        {
                            selectedElements.Add(elem);
                        }
                    }
                }
                if (!selectedElements.Contains(ReferenceElem) && tools.getNumber(ReferenceElem) == "")
                {
                    selectedElements.Add(ReferenceElem);
                }
            }
            else
            {
                if (getNumber(ReferenceElem) == "")
                {
                    selectedElements.Add(ReferenceElem);
                }
            }


            OverrideGraphicSettings overrideGraphicSettings = new OverrideGraphicSettings();

            System.Drawing.Color colorSelect = MainForm.ColorSelected;
            byte r = colorSelect.R;
            byte b = colorSelect.B;
            byte g = colorSelect.G;

            overrideGraphicSettings.SetProjectionFillColor(new Autodesk.Revit.DB.Color(r, g, b));
            overrideGraphicSettings.SetProjectionLineColor(new Autodesk.Revit.DB.Color(r, g, b));
            foreach (Element x in tools.selectedElements)
            {
                tools.doc.ActiveView.SetElementOverrides(x.Id, overrideGraphicSettings);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RevitBuiltInCategory"/> class.
 /// </summary>
 /// <param name="builtInCategory"><see cref="Autodesk.Revit.DB.BuiltInCategory"/></param>
 public RevitBuiltInCategory(BuiltInCategory builtInCategory)
 {
     BuiltInCategory     = builtInCategory;
     BuiltInCategoryName = builtInCategory.ToString();
     try
     {
         DisplayName = GetDisplayName(builtInCategory);
     }
     catch
     {
         DisplayName = string.Empty;
     }
 }
Esempio n. 12
0
        public void CategorySample()
        {
            Element    selectedElement = null;
            UIDocument uidoc           = this.ActiveUIDocument;
            Document   document        = this.ActiveUIDocument.Document;

            foreach (ElementId id in uidoc.Selection.GetElementIds())
            {
                selectedElement = document.GetElement(id);
                break;              // just get one selected element
            }

            // Get the category instance from the Category property
            Category category = selectedElement.Category;

            BuiltInCategory enumCategory = (BuiltInCategory)category.Id.IntegerValue;

            // Format the prompt string, which contains the category information
            String prompt = "The category information of the selected element is: ";

            prompt += "\n\tName:\t" + category.Name;               // Name information

            prompt += "\n\tId:\t" + enumCategory.ToString();       // Id information
            prompt += "\n\tParent:\t";
            if (null == category.Parent)
            {
                prompt += "No Parent Category";               // Parent information, it may be null
            }
            else
            {
                prompt += category.Parent.Name;
            }

            prompt += "\n\tSubCategories:";             // SubCategories information,
            CategoryNameMap subCategories = category.SubCategories;

            if (null == subCategories || 0 == subCategories.Size)             // It may be null or has no item in it
            {
                prompt += "No SubCategories;";
            }
            else
            {
                foreach (Category ii in subCategories)
                {
                    prompt += "\n\t\t" + ii.Name;
                }
            }

            // Give the user some information
            TaskDialog.Show("Revit", prompt);
        }
Esempio n. 13
0
        /// <summary>
        /// 2017/12/30 為作業3改造參數新增與賦值函式
        /// </summary>
        /// <param name="uidoc"></param>
        /// <param name="doc"></param>
        /// <param name="category"></param>
        /// <param name="dr"></param>
        private void hw3_setNewParametersToCategory(UIDocument uidoc, Document doc, BuiltInCategory category, DataTable dt)
        {
            string cateName = category.ToString();

            Transaction trans = new Transaction(doc);

            trans.Start("設定新增參數,綁定於實體之上");
            //必須先新增共用參數檔案
            FileStream fileStream = File.Create(Directory.GetCurrentDirectory() + "ShareParameter.txt");

            fileStream.Close();
            //然後將共用參數檔案綁定到Document之上
            doc.Application.SharedParametersFilename = Directory.GetCurrentDirectory() + "ShareParameter.txt";
            DefinitionFile defFile = doc.Application.OpenSharedParameterFile(); //打開共用參數檔

            List <string> fieldNames = new List <string>();

            fieldNames.Add("製造商");

            this.AddNewParametersToCategories(uidoc.Application, defFile, category, fieldNames); //呼叫方法以新增參數

            if (category == BuiltInCategory.OST_Windows)
            {
                DataRow[] drs = dt.Select("categoryType='窗'");
                for (int i = 0; i != drs.Length; i++)
                {
                    string    id   = drs[i]["ElementID"].ToString();
                    string    manu = drs[i]["manufacturer"].ToString();
                    ElementId eid  = new ElementId(Convert.ToInt32(id));
                    this.setSingleParameter(eid, doc, fieldNames[0], manu);
                }
            }

            else if (category == BuiltInCategory.OST_Doors)
            {
                DataRow[] drs = dt.Select("categoryType='門'");
                for (int i = 0; i != drs.Length; i++)
                {
                    string    id   = drs[i]["ElementID"].ToString();
                    string    manu = drs[i]["manufacturer"].ToString();
                    ElementId eid  = new ElementId(Convert.ToInt32(id));
                    this.setSingleParameter(eid, doc, fieldNames[0], manu);
                }
            }
            else
            {
            }

            trans.Commit();
        }
Esempio n. 14
0
        public void setNewParametersToCategory(Document doc, UIDocument uidoc, BuiltInCategory category)
        {
            string       cateName = category.ToString();
            StreamReader sr       = new StreamReader("D:\\revitAPI\\" + cateName + ".txt");

            string[]      titles     = sr.ReadLine().Split('\t');
            List <string> fieldNames = new List <string>();

            for (int i = 1; i != titles.Length; i++)
            {
                fieldNames.Add(titles[i]);
            }

            Transaction trans = new Transaction(doc);

            trans.Start("設定新增參數,綁定於實體之上");
            //必須先新增共用參數檔案
            FileStream fileStream = File.Create(Directory.GetCurrentDirectory() + "ShareParameter.txt");

            fileStream.Close();
            //然後將共用參數檔案綁定到Document之上
            doc.Application.SharedParametersFilename = Directory.GetCurrentDirectory() + "ShareParameter.txt";
            DefinitionFile defFile = doc.Application.OpenSharedParameterFile();                  //打開共用參數檔

            this.AddNewParametersToCategories(uidoc.Application, defFile, category, fieldNames); //呼叫方法以新增參數
            while (sr.Peek() >= 0)                                                               //從文字檔中逐行讀取每個元件的對應參數並且填寫參數值到BIM模型中
            {
                string[]  data = sr.ReadLine().Split('\t');
                ElementId eid  = new ElementId(Convert.ToInt32(data[0]));
                for (int i = 1; i != data.Length; i++)
                {
                    string columnName  = fieldNames[i - 1];
                    string columnValue = data[i];
                    this.setSingleParameter(eid, doc, columnName, columnValue);
                }
            }
            sr.Close();
            trans.Commit();
        }
    /// <summary>
    /// Return the first family symbol found in the given document
    /// matching the given built-in category or null if none is found.
    /// </summary>
    public static FamilySymbol GetFirstFamilySymbol(
      Document doc,
      BuiltInCategory bic)
    {
      FamilySymbol s = GetFamilySymbols(doc, bic).FirstElement() as FamilySymbol;

      Debug.Assert(null != s, string.Format(
        "expected at least one {0} symbol in project",
        bic.ToString()));

      return s;
    }
Esempio n. 16
0
        /// <summary>
        /// Save an element on a temporary list and override its color
        /// </summary>
        public static void AddToSelection()
        {
            selectedElements.Clear();

            var filterS = new SelectionFilter();

            var refElement = uidoc.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, new SelectionFilter());

            if (refElement != null)
            {
                var element = uidoc.Document.GetElement(refElement);

                Category        category     = element.Category;
                BuiltInCategory enumCategory = (BuiltInCategory)category.Id.IntegerValue;


                //Check for other rectangular ducts with the same parameters
                if (enumCategory.ToString() == "OST_DuctCurves" &&
                    element.get_Parameter(BuiltInParameter.RBS_CURVE_DIAMETER_PARAM)?.AsValueString() == null)
                {
                    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_DuctCurves, BuiltInParameter.RBS_DUCT_SYSTEM_TYPE_PARAM, BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM, BuiltInParameter.CURVE_ELEM_LENGTH,
                                BuiltInParameter.RBS_CURVE_WIDTH_PARAM, BuiltInParameter.RBS_CURVE_HEIGHT_PARAM);
                }

                //Check for other ducts fittings with the same parameters
                if (enumCategory.ToString() == "OST_DuctFitting" &&
                    element.get_Parameter(BuiltInParameter.RBS_CURVE_DIAMETER_PARAM)?.AsValueString() == null)
                {
                    string elemParam01 = element.get_Parameter(BuiltInParameter.RBS_SYSTEM_CLASSIFICATION_PARAM).AsValueString();
                    string elemParam02 = element.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString();
                    string elemParam03 = element.get_Parameter(BuiltInParameter.RBS_REFERENCE_FREESIZE).AsString();
                    string elemParam04 = element.get_Parameter(BuiltInParameter.RBS_REFERENCE_OVERALLSIZE).AsString();
                    string elemParam05 = element.get_Parameter(BuiltInParameter.RBS_CALCULATED_SIZE).AsString();

                    FilteredElementCollector viewCollector = new FilteredElementCollector(doc, uidoc.ActiveView.Id);
                    List <Element>           ducts         = new FilteredElementCollector(doc, uidoc.ActiveView.Id)
                                                             .OfCategory(Autodesk.Revit.DB.BuiltInCategory.OST_DuctFitting)
                                                             .Where(a => a.get_Parameter(BuiltInParameter.RBS_SYSTEM_CLASSIFICATION_PARAM).AsValueString() == elemParam01)
                                                             .Where(a => a.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString() == elemParam02)
                                                             .Where(a => a.get_Parameter(BuiltInParameter.RBS_REFERENCE_FREESIZE).AsString() == elemParam03)
                                                             .Where(a => a.get_Parameter(BuiltInParameter.RBS_REFERENCE_OVERALLSIZE).AsString() == elemParam04)
                                                             .Where(a => a.get_Parameter(BuiltInParameter.RBS_CALCULATED_SIZE).AsString() == elemParam05)
                                                             .ToList();

                    foreach (Element x in ducts)
                    {
                        selectedElements.Add(x);
                        ListOfElements.Add(x);
                    }
                }


                bool boolTest = false;

                var familyTypee = element.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString();
                if (familyTypee.Contains("Bend"))
                {
                    boolTest = true;
                }


                bool TapTest = false;

                var familyTapType = element.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString();
                if (familyTapType.Contains("Tap"))
                {
                    TapTest = true;
                }


                //Check for other round ducts with the same parameters
                if (enumCategory.ToString() == "OST_DuctCurves" &&
                    element.get_Parameter(BuiltInParameter.RBS_CURVE_DIAMETER_PARAM)?.AsValueString() != null &&
                    TapTest != true)
                {
                    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_DuctCurves, BuiltInParameter.RBS_DUCT_SYSTEM_TYPE_PARAM, BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM, BuiltInParameter.CURVE_ELEM_LENGTH,
                                BuiltInParameter.RBS_CURVE_SURFACE_AREA, BuiltInParameter.RBS_CURVE_DIAMETER_PARAM);
                }

                //Check for other rectangular fab ducts with the same parameters
                if (enumCategory.ToString() == "OST_FabricationDuctwork" &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_ANGLE)?.AsValueString() == null &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_DIAMETER_IN)?.AsValueString() == null &&
                    element.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM)?.AsValueString() != "Generic Square Bend" &&
                    TapTest != true)
                {
                    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_FabricationDuctwork, BuiltInParameter.ELEM_FAMILY_PARAM, BuiltInParameter.FABRICATION_PART_LENGTH, BuiltInParameter.FABRICATION_PART_DEPTH_IN,
                                BuiltInParameter.FABRICATION_PART_WIDTH_IN, BuiltInParameter.FABRICATION_SERVICE_PARAM);
                }


                //Check for other rectangular fab ducts fittings of angle 90 with the same parameters
                //if (enumCategory.ToString() == "OST_FabricationDuctwork"
                //    && element.get_Parameter(BuiltInParameter.FABRICATION_PART_ANGLE)?.AsValueString() == null
                //    && element.get_Parameter(BuiltInParameter.FABRICATION_PART_DIAMETER_IN)?.AsValueString() == null
                //    && element.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM)?.AsValueString() == "Generic Square Bend"
                //    )

                //{
                //    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_FabricationDuctwork, BuiltInParameter.ELEM_FAMILY_PARAM, BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM, BuiltInParameter.FABRICATION_PART_DEPTH_IN,
                //      BuiltInParameter.FABRICATION_PART_WIDTH_IN, BuiltInParameter.FABRICATION_SERVICE_PARAM);
                //}



                //Check for other rectangular fab ducts fittings of angle 90 with the same parameters
                if (enumCategory.ToString() == "OST_FabricationDuctwork" &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_ANGLE)?.AsValueString() == null &&
                    boolTest == true &&
                    TapTest != true
                    )
                {
                    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_FabricationDuctwork, BuiltInParameter.ELEM_FAMILY_PARAM, BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM, BuiltInParameter.FABRICATION_PART_DEPTH_IN,
                                BuiltInParameter.FABRICATION_PART_WIDTH_IN, BuiltInParameter.FABRICATION_SERVICE_PARAM);
                }


                //Check for other rectangular fab ducts fittings with the same parameters
                if (enumCategory.ToString() == "OST_FabricationDuctwork" &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_ANGLE)?.AsValueString() != null &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_DIAMETER_IN)?.AsValueString() == null
                    )
                {
                    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_FabricationDuctwork, BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM, BuiltInParameter.FABRICATION_PART_ANGLE, BuiltInParameter.FABRICATION_SERVICE_PARAM,
                                BuiltInParameter.FABRICATION_PART_DEPTH_IN, BuiltInParameter.FABRICATION_PART_WIDTH_IN);
                }

                //Check for other rectangular fab ducts fittings with the same parameters
                if (enumCategory.ToString() == "OST_FabricationDuctwork" &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_ANGLE)?.AsValueString() != null &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_DIAMETER_IN)?.AsValueString() != null
                    )
                {
                    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_FabricationDuctwork, BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM, BuiltInParameter.FABRICATION_PART_ANGLE, BuiltInParameter.FABRICATION_SERVICE_PARAM,
                                BuiltInParameter.FABRICATION_PART_DIAMETER_IN, BuiltInParameter.RBS_REFERENCE_OVERALLSIZE);
                }

                //Check for other round fab ducts with the same parameters
                if (enumCategory.ToString() == "OST_FabricationDuctwork" &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_ANGLE)?.AsValueString() == null &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_DIAMETER_IN)?.AsValueString() != null &&
                    TapTest != true
                    )
                {
                    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_FabricationDuctwork, BuiltInParameter.ELEM_FAMILY_PARAM, BuiltInParameter.FABRICATION_PART_LENGTH, BuiltInParameter.FABRICATION_PART_DIAMETER_IN,
                                BuiltInParameter.FABRICATION_PART_SHEETMETAL_AREA, BuiltInParameter.FABRICATION_SERVICE_PARAM);
                }


                //Check for other round fab ducts with the same parameters
                if (enumCategory.ToString() == "OST_FabricationDuctwork" &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_ANGLE)?.AsValueString() == null &&
                    element.get_Parameter(BuiltInParameter.FABRICATION_PART_DIAMETER_IN)?.AsValueString() != null &&
                    TapTest == true
                    )
                {
                    filterParam(element, Autodesk.Revit.DB.BuiltInCategory.OST_FabricationDuctwork, BuiltInParameter.ELEM_FAMILY_PARAM, BuiltInParameter.FABRICATION_PART_LENGTH, BuiltInParameter.FABRICATION_PART_DIAMETER_IN,
                                BuiltInParameter.RBS_REFERENCE_OVERALLSIZE, BuiltInParameter.FABRICATION_SERVICE_PARAM);
                }

                selectedElements.Add(element);

                //TODO: check if element is from the right category
                OverrideGraphicSettings overrideGraphicSettings = new OverrideGraphicSettings();
                Color colorSelect = MainForm.ColorSelected;

                //Split coloSelect in R,G,B to be transformed to a Revit color later
                byte r = colorSelect.R;
                byte b = colorSelect.B;
                byte g = colorSelect.G;

                //Set override properties to fill and line colors
                overrideGraphicSettings.SetProjectionFillColor(new Autodesk.Revit.DB.Color(r, g, b));
                overrideGraphicSettings.SetProjectionLineColor(new Autodesk.Revit.DB.Color(r, g, b));

                foreach (Element x in selectedElements)
                {
                    //Override color of element
                    doc.ActiveView.SetElementOverrides(x.Id, overrideGraphicSettings);
                }

                selectedElement = element;

                //Add element to the temporary list of selected elemenents
                ListOfElements.Add(element);
            }
        }
Esempio n. 17
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            Element selectedElement = null;

            foreach (ElementId id in uidoc.Selection.GetElementIds())
            {
                selectedElement = doc.GetElement(id);
                break;  // just get one selected element
            }
            // gittest 2 Delete 2
            // Get the category instance from the Category property
            Category category = selectedElement.Category;

            BuiltInCategory enumCategory = (BuiltInCategory)category.Id.IntegerValue;

            // Format the prompt string, which contains the category information
            String prompt = "The category information of the selected element is: ";

            prompt += "\n\tName:\t" + category.Name;         // Name information

            prompt += "\n\tId:\t" + enumCategory.ToString(); // Id information
            prompt += "\n\tParent:\t";
            if (null == category.Parent)
            {
                prompt += "No Parent Category";   // Parent information, it may be null
            }
            else
            {
                prompt += category.Parent.Name;
            }

            prompt += "\n\tSubCategories:"; // SubCategories information,
            CategoryNameMap subCategories = category.SubCategories;

            if (null == subCategories || 0 == subCategories.Size) // It may be null or has no item in it
            {
                prompt += "No SubCategories;";
            }
            else
            {
                foreach (Category ii in subCategories)
                {
                    prompt += "\n\t\t" + ii.Name;
                }
            }

            // Give the user some information
            TaskDialog.Show("Revit", prompt);

            Random rnd = new Random();

            OverrideGraphicSettings myOGS = new OverrideGraphicSettings();

            using (Transaction t = new Transaction(doc, "Change color"))
            {
                t.Start();
                if (null == subCategories || 0 == subCategories.Size) // It may be null or has no item in it
                {
                }
                else
                {
                    foreach (Category ii in subCategories)
                    {
                        ElementId elemID = ii.Id;
                        myOGS.SetProjectionLineColor(new Color(
                                                         (byte)rnd.Next(0, 256),
                                                         (byte)rnd.Next(0, 256),
                                                         (byte)rnd.Next(0, 256)
                                                         ));
                        doc.ActiveView.SetCategoryOverrides(elemID, myOGS);
                    }
                }
                t.Commit();
            }


            return(Result.Succeeded);
        }
Esempio n. 18
0
        private void test1(Document doc)
        {
            var category_colors = FileManager.ReadDefCsv(FileManager.data_location);

            DocPatterns patterns = new DocPatterns(doc);

            List <OverrideCat> rcs = new List <OverrideCat>();
            //foreach (var cs in category_colors)
            //{
            //    OverrideCat cst = new OverrideCat(patterns.Solidfill, cs);
            //    rcs.Add(cst);
            //}
            //FilteredElementCollector collec = new FilteredElementCollector(doc, doc.ActiveView.Id);

            //var collector
            //    =  collec.WheToElements()
            //        .Select(x => x.Category)
            //        .Distinct(new CategoryComparer())
            //        .ToList();

            var iter = doc.Settings.Categories;

            //doc.Settings.Categories.AsQueryable();
            // iter.MoveNext();
            foreach (Category cat in iter)
            {
                try
                {
                    // iter.C
                    BuiltInCategory curcat = (BuiltInCategory)cat.Id.IntegerValue;

                    //doc.Settings.Categories
                    string      ccat  = curcat.ToString();
                    var         found = category_colors.Where(x => x.First() == ccat);
                    OverrideCat cst;
                    if (found.Count() > 0)
                    {
                        cst = new OverrideCat(doc, patterns.Solidfill, found.First());
                    }
                    else
                    {
                        cst         = new OverrideCat(patterns.Dotline, curcat);
                        cst.visible = false;
                    }
                    rcs.Add(cst);
                    // iter.MoveNext();
                }
                catch (Exception) { }
            }

            var viewsCol
                = new FilteredElementCollector(doc)
                  .WhereElementIsNotElementType()
                  .OfCategory(BuiltInCategory.OST_Views)
                  .ToElements().Cast <View>().ToList();

            var watch = Stopwatch.StartNew();


            foreach (var vs in viewsCol)
            {
                string ext1             = "---base---";
                string ext2             = "---mask---";
                string view_export_loc1 = "C:\\data\\t1\\" + Helper.AndHash(vs.Name) + ext1 + vs.Name;
                string view_export_loc2 = "C:\\data\\t1\\" + Helper.AndHash(vs.Name) + ext2 + vs.Name;
                Applicator.ExportView(doc, vs, view_export_loc1, ext1);
                var rvs = Applicator.viewCatOverride(doc, vs, rcs);
                Applicator.ExportView(doc, rvs, view_export_loc2, ext2);
            }
            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            //uiapp.OpenAndActivateDocument(paths[1]);
            //doc.Close(false);


            //var watch2 = Stopwatch.StartNew();
            //foreach (var vs in viewsCol)
            //{
            //    string ext1 = "---base---";
            //    string ext2 = "---mask---";
            //    string view_export_loc1 = "C:\\data\\t2\\" + Helper.AndHash(vs.Name) + ext1 + vs.Name;
            //    string view_export_loc2 = "C:\\data\\t2\\" + Helper.AndHash(vs.Name) + ext2 + vs.Name;
            //    Applicator.ExportView(doc, vs, view_export_loc1, ext1);
            //    Applicator.AddOverride(doc, vs, patterns.Solidfill, category_colors);
            //    Applicator.ExportView(doc, vs, view_export_loc2, ext2);
            //}
            //watch2.Stop();
            //var elapsedMs2 = watch2.ElapsedMilliseconds;

            TaskDialog.Show("opt", "base " + elapsedMs.ToString());
        }
Esempio n. 19
0
        public DataTable getDataTableBySpecificCategory(Document doc, BuiltInCategory category)
        {
            //用篩選器取得模型當中的所有牆
            FilteredElementCollector collector   = new FilteredElementCollector(doc);
            ElementCategoryFilter    filter      = new ElementCategoryFilter(category);
            IList <Element>          elementList = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();

            DataTable dt = new DataTable("ElementParameters");

            dt.Columns.Add("ElementID", typeof(int));
            dt.Columns.Add("UniqueID", typeof(string));
            if (elementList.Count > 0)
            {
                //先從集合裡取一個元素來建立DataTable的樣板
                IEnumerator <Element> it = elementList.GetEnumerator();
                it.MoveNext(); //指到第一個元素
                Element templateElem = it.Current;

                List <XYZ> positions = this.getPosition(templateElem);
                if (positions.Count == 2)
                {
                    dt.Columns.Add("起點x座標", typeof(double));
                    dt.Columns.Add("起點y座標", typeof(double));
                    dt.Columns.Add("起點z座標", typeof(double));
                    dt.Columns.Add("終點x座標", typeof(double));
                    dt.Columns.Add("終點y座標", typeof(double));
                    dt.Columns.Add("終點z座標", typeof(double));
                }
                else if (positions.Count == 1)
                {
                    dt.Columns.Add("中心點x座標", typeof(double));
                    dt.Columns.Add("中心點y座標", typeof(double));
                    dt.Columns.Add("中心點z座標", typeof(double));
                }
                else
                {
                }

                foreach (Parameter para in templateElem.Parameters)
                {
                    Tuple <string, string, Type> currentItem = this.getParameterInfomation(para, doc);
                    //我意外從程式執行結果發現Parameters欄位還會發生重複的,原因不明,但只好這樣排除
                    if (dt.Columns.Contains(currentItem.Item1) == false)
                    {
                        dt.Columns.Add(currentItem.Item1, currentItem.Item3);
                    }
                }//end foreach

                //接下來正式上陣,填滿這個DataTable
                foreach (Element elem in elementList)
                {
                    int     eid   = elem.Id.IntegerValue;
                    string  uid   = elem.UniqueId;
                    DataRow dtRow = dt.NewRow();
                    //首先填寫辨識碼
                    dtRow["ElementID"] = eid;
                    dtRow["UniqueID"]  = uid;
                    //再來填寫幾何座標資訊
                    List <XYZ> positionsSpecific = this.getPosition(elem);
                    if (positionsSpecific.Count == 2)
                    {
                        dtRow["起點x座標"] = positionsSpecific[0].X; dtRow["起點y座標"] = positionsSpecific[0].Y;
                        dtRow["起點z座標"] = positionsSpecific[0].Z;  dtRow["終點x座標"] = positionsSpecific[1].X;
                        dtRow["終點y座標"] = positionsSpecific[1].Y;  dtRow["終點z座標"] = positionsSpecific[1].Z;
                    }
                    else if (positionsSpecific.Count == 1)
                    {
                        dtRow["中心點x座標"] = positionsSpecific[0].X;
                        dtRow["中心點y座標"] = positionsSpecific[0].Y;
                        dtRow["中心點z座標"] = positionsSpecific[0].Z;
                    }
                    else
                    {
                    }
                    //最後針對一個元件的所有參數進行擷取
                    foreach (Parameter para in elem.Parameters)
                    {
                        try
                        {
                            Tuple <string, string, Type> currentParameter = this.getParameterInfomation(para, doc);
                            //擷取參數的動作很麻煩,是官網提供的函式,做了一些改造並且用Tuple的結構傳回
                            dtRow[currentParameter.Item1] = currentParameter.Item2; //然後塞進DataTable的對應欄位中
                            //上述一行顯示出DataTable的強大,因為左值與右值理論上要變數型別相等,但現在右值一律是字串,
                            //而它只要「字串格式」能夠符合左值的要求(整數、布林或是浮點數)就會自動轉型置入
                        }
                        catch (Exception ex) { }
                    }
                    dt.Rows.Add(dtRow);//將新增資料列放入DataTable中
                }
                dt.WriteXml("D:\\revitAPI\\parameters_" + category.ToString() + ".xml", XmlWriteMode.WriteSchema);
                return(dt);
            }
            else
            {
                MessageBox.Show("這個篩選器沒有得到任何結果");
                return(dt);
            }
        }//end fun
        public Result Execute(ExternalCommandData commandData,
                              ref string message,
                              ElementSet elements)
        {
            UIApplication uiapp  = commandData.Application;
            UIDocument    _uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application _app = uiapp.Application;
            Autodesk.Revit.DB.Document _doc = _uidoc.Document;

            BuiltInCategory bicFamilyA = BuiltInCategory.OST_DuctTerminal;
            BuiltInCategory bicFamilyB = BuiltInCategory.OST_DataDevices;
            BuiltInCategory bicFamilyC = BuiltInCategory.OST_MechanicalEquipment;
            //BuiltInCategory bicFamilyC = BuiltInCategory.OST_Sprinklers;

            ICollection <BuiltInCategory> categories = new[] { bicFamilyA, bicFamilyB, bicFamilyC };
            ElementFilter    myPCatFilter            = new ElementMulticategoryFilter(categories);
            ISelectionFilter myPickFilter            = SelFilter.GetElementFilter(myPCatFilter);

            bool       keepOnTruckn = true;
            FormMsgWPF formMsg      = new FormMsgWPF();

            formMsg.Show();

            using (TransactionGroup pickGrp = new TransactionGroup(_doc)) {
                pickGrp.Start("CmdCycleType");
                bool firstTime = true;

                //string strCats= "";
                //foreach (BuiltInCategory iCat in categories) {
                //    strCats = strCats + iCat.ToString().Replace("OST_", "") + ", ";
                //}
                string strCats = FamilyUtils.BICListMsg(categories);

                formMsg.SetMsg("Pick the " + strCats + " to check its type.", "Type Cycle:");
                while (keepOnTruckn)
                {
                    try {
                        Reference pickedElemRef = _uidoc.Selection.PickObject(ObjectType.Element, myPickFilter, "Pick the " + bicFamilyA.ToString() + " to cycle its types. (Press ESC to cancel)");
                        Element   pickedElem    = _doc.GetElement(pickedElemRef.ElementId);

                        FamilyInstance fi = pickedElem as FamilyInstance;
                        FamilySymbol   fs = fi.Symbol;

                        var famTypesIds = fs.Family.GetFamilySymbolIds().OrderBy(e => _doc.GetElement(e).Name).ToList();
                        int thisIndx    = famTypesIds.FindIndex(e => e == fs.Id);
                        int nextIndx    = thisIndx;
                        if (!firstTime)
                        {
                            nextIndx = nextIndx + 1;
                            if (nextIndx >= famTypesIds.Count)
                            {
                                nextIndx = 0;
                            }
                        }
                        else
                        {
                            firstTime = false;
                        }

                        if (pickedElem != null)
                        {
                            using (Transaction tp = new Transaction(_doc, "PlunkOMatic:SetParam")) {
                                tp.Start();
                                if (pickedElem != null)
                                {
                                    fi.Symbol = _doc.GetElement(famTypesIds[nextIndx]) as FamilySymbol;
                                    formMsg.SetMsg("Currently:\n" + fi.Symbol.Name + "\n\nPick again to cycle its types.", "Type Cycling");
                                }
                                tp.Commit();
                            }
                        }
                        else
                        {
                            keepOnTruckn = false;
                        }
                    } catch (Exception) {
                        keepOnTruckn = false;
                        //throw;
                    }
                }
                pickGrp.Assimilate();
            }

            formMsg.Close();
            return(Result.Succeeded);
        }
        private void NumberPartButton_Click(object sender, RoutedEventArgs el)
        {
            Connector        CurrentConnector = null;
            List <Element>   RunElements      = new List <Element>();
            List <ElementId> RunElementsId    = new List <ElementId>();

            base.Hide();
            Element e;


            //Select the element only if it is a part number
            using (Transaction AssingPartNumberT = new Transaction(tools.uidoc.Document, "Assing Part Number"))
            {
                AssingPartNumberT.Start();
                e = tools.NewSelection();
                AssingPartNumberT.Commit();
            }

            //Make sure that the user selected a valid element
            if (e == null)
            {
                goto CloseApp;
            }


            ConnectorSet connectors   = this.getConnectorSetFromElement(e);
            int          connectCount = 0;


            //Get the numbers of connectors of the element
            foreach (Connector c in connectors)
            {
                //Conector must be connected, must be a End conector and should have another element connected to it.
                if (c.IsConnected && c.ConnectorType.ToString() != "Curve" && this.ConnectionCheck(c) != 0)
                {
                    connectCount    += 1;
                    CurrentConnector = c;
                }
            }

            //Check if the element is isolated
            if (connectCount == 0 || SnglElmtButton)
            {
                RunElements.Add(e);
                connectCount = 0;
            }

            //Check if the element has more than 2 connections
            if (connectCount >= 2)
            {
                //check if the element is a false positive
                this.CheckDoubleConn(ref connectCount, ref connectors, ref CurrentConnector);

                if (connectCount >= 2)
                {
                    System.Windows.MessageBox.Show("The elements is not an endpoint", "warning");
                    goto CloseApp;
                }
            }

            //Check if the element has 1 connection
            if (connectCount == 1)
            {
                int              tempValue          = 1;
                ConnectorSet     TempConnectors     = null;
                List <Connector> TempConnectorsList = new List <Connector>();
                Element          tempElem           = e;
                int              iterationsCount    = 0;
                TempConnectors = connectors;

                while (tempValue == 1)
                {
                    int countConnect = 0;

                    if (checkRoundDucts(RoundDuctsBool, tempElem))
                    {
                        RunElements.Add(tempElem);
                    }

                    RunElementsId.Add(tempElem.Id);

                    //Make sure that the elements are conected if connectors
                    //are geometrically aligned
                    foreach (Connector fcon in TempConnectors)
                    {
                        if (ConnectorsHelper.ConnStatus(fcon))
                        {
                            if (this.ConnectionCheck(fcon) != 0)
                            {
                                countConnect++;
                            }
                        }
                    }

                    //Check if the element is a tee
                    if (ConnectorsHelper.TeeDetect(TempConnectors))
                    {
                        tempValue = 2;
                        goto EndLoop;
                    }

                    if (countConnect == 1 && iterationsCount != 0)
                    {
                        tempValue = 2;
                        goto EndLoop;
                    }
                    else
                    {
                        ConnectorSet secondary = CurrentConnector.AllRefs;
                        foreach (Connector cone in secondary)
                        {
                            if (!RunElementsId.Contains(cone.Owner.Id))
                            {
                                //Check if the following element is connected from the side
                                tempElem = this._doc.GetElement(cone.Owner.Id);

                                Category        cat     = tempElem.Category;
                                BuiltInCategory enumCat = (BuiltInCategory)cat.Id.IntegerValue;

                                if (enumCat.ToString() != "OST_FabricationDuctwork")
                                {
                                    tempValue = 2;
                                    goto EndLoop;
                                }
                            }
                        }



                        TempConnectors = this.getConnectorSetFromElement(tempElem);

                        foreach (Connector connec in TempConnectors)
                        {
                            //Check that the previous element is not connecting from side
                            if (!ConnectorsHelper.ConnStatus(connec))
                            {
                                foreach (Connector con in connec.AllRefs)
                                {
                                    if (RunElementsId.Contains(con.Owner.Id))
                                    {
                                        tempValue = 2;
                                        goto EndLoop;
                                    }
                                }
                            }

                            //Get the next useful connector
                            if (ConnectorsHelper.ConnStatus(connec))
                            {
                                foreach (Connector con in connec.AllRefs)
                                {
                                    if (!RunElementsId.Contains(con.Owner.Id))
                                    {
                                        CurrentConnector = connec;
                                    }
                                }
                            }
                        }
                    }
EndLoop:
                    iterationsCount++;
                }
            }


            List <string> listToStringComplete = this.listToString(RunElements);

            if (RunElements.Count != 0)
            {
                foreach (Element elmnt in RunElements)
                {
                    using (Transaction AssingPartNumberT2 = new Transaction(tools.uidoc.Document, "Assing Part Number"))
                    {
                        tools.selectedElements.Clear();
                        AssingPartNumberT2.Start();


                        //Find all the elements that are the same in the RunElements list
                        tools.AddToSelection(elmnt, listToStringComplete, RunElements, checkBoxDuplicates);

                        //Generate the part number
                        string partNumber = tools.createNumbering(this.PrefixBox.Text, this.SeparatorBox.Text, tools.count, this.NumberBox.Text.Length);

                        //Assign the part number to each selected element
                        foreach (Element x in tools.selectedElements)
                        {
                            tools.AssingPartNumber(x, partNumber);
                        }


                        if (tools.selectedElements.Count != 0)
                        {
                            tools.count++;
                        }

                        int leadingZeros = (this.NumberBox.Text.Length > 1) ? (this.NumberBox.Text.Length - tools.count.ToString().Length) : 0;

                        if (leadingZeros >= 0)
                        {
                            this.NumberBox.Text = new string('0', leadingZeros) + tools.count.ToString();
                        }
                        else
                        {
                            this.NumberBox.Text = tools.count.ToString();
                        }

                        tools.writeConfig(this.PrefixBox.Text, this.SeparatorBox.Text, this.NumberBox.Text);
                        Options options = this.uiApp.Application.Create.NewGeometryOptions();
                        AssingPartNumberT2.Commit();
                    }
                }
            }



            CloseApp :;
            base.ShowDialog();
        }
Esempio n. 22
0
        /// <summary>
        /// Get The connector set of an element
        /// </summary>
        /// <param name="elem"></param>
        private int getElementConnected(ref Element elem)
        {
            List <string> categories          = new List <string>(new string[] { "OST_CableTrayFitting", "OST_CableTray", "OST_ConduitFitting", "OST_Conduit", "OST_DuctFitting", "OST_DuctCurves", "OST_DuctAccessory", "OST_FabricationParts", "OST_FabricationPipework", "OST_FabricationHangers", "OST_PipeAccessory", "OST_PipeFitting", "OST_PipeCurves", "OST_FabricationDuctwork" });
            ConnectorSet  connectors          = null;
            int           countElemToContinue = 0;
            //elemIds.Add(elem.Id);
            bool flag = elem is FamilyInstance;

            if (flag)
            {
                MEPModel i = ((FamilyInstance)elem).MEPModel;
                connectors = i.ConnectorManager.Connectors;
            }
            else
            {
                bool flag2 = elem is FabricationPart;
                if (flag2)
                {
                    connectors = ((FabricationPart)elem).ConnectorManager.Connectors;
                }
                else
                {
                    bool flag3 = elem is MEPCurve;
                    if (flag3)
                    {
                        connectors = ((MEPCurve)elem).ConnectorManager.Connectors;
                    }
                    else
                    {
                        Debug.Assert(elem.GetType().IsSubclassOf(typeof(MEPCurve)), "expected all candidate connector provider elements to be either family instances or derived from MEPCurve");
                    }
                }
            }
            //foreach (Connector cone in connectors)
            //{
            //    if (!elemIds.Contains(cone.Owner.Id))
            //        elemIds.Add(cone.Owner.Id);
            //}

            ConnectorSet tempConnectors = new ConnectorSet();

            foreach (Connector connec in connectors)
            {
                foreach (Connector con in connec.AllRefs)
                {
                    if (!elemIds.Contains(con.Owner.Id))
                    {
                        Element         tempElem = _doc.GetElement(con.Owner.Id);
                        Category        cat      = tempElem.Category;
                        BuiltInCategory enumCat  = (BuiltInCategory)cat.Id.IntegerValue;

                        if (categories.Contains(enumCat.ToString()))
                        {
                            if (con.Owner.Id != elem.Id && string.IsNullOrEmpty(tempElem.LookupParameter("Item Number").AsString()))
                            {
                                if (countElemToContinue == 0)
                                {
                                    elemIds.Add(con.Owner.Id);
                                }
                                else
                                if (countElemToContinue == 1)
                                {
                                    elemIds.RemoveAt(elemIds.Count() - 1);
                                }

                                countElemToContinue++;
                                tempConnectors.Insert(con);
                                elem = con.Owner;
                            }
                        }
                    }
                }
            }
            return(countElemToContinue);
        }
        Category GetCategory(
            Document doc,
            BuiltInCategory target)
        {
            Category cat = null;

              if( target.Equals( BuiltInCategory.OST_IOSModelGroups ) )
              {
            // determine model group category:

            FilteredElementCollector collector
              = Util.GetElementsOfType( doc, typeof( Group ), // GroupType works as well
            BuiltInCategory.OST_IOSModelGroups );

            IList<Element> modelGroups = collector.ToElements();

            if( 0 == modelGroups.Count )
            {
              Util.ErrorMsg( "Please insert a model group." );
              return cat;
            }
            else
            {
              cat = modelGroups[0].Category;
            }
              }
              else
              {
            try
            {
              cat = doc.Settings.Categories.get_Item( target );
            }
            catch( Exception ex )
            {
              Util.ErrorMsg( string.Format(
            "Error obtaining document {0} category: {1}",
            target.ToString(), ex.Message ) );
              return cat;
            }
              }
              if( null == cat )
              {
            Util.ErrorMsg( string.Format(
              "Unable to obtain the document {0} category.",
              target.ToString() ) );
              }
              return cat;
        }
        private void SetCutPatternSettings(View view, BuiltInCategory buildInCategory, Autodesk.Revit.DB.Color backgroundColor, FillPatternElement foregroundFillPattern)
        {
            ElementId categoryId = new ElementId(buildInCategory);

            OverrideGraphicSettings ogSettings = view.GetCategoryOverrides(categoryId);

            if ((ogSettings == null) || (!ogSettings.IsValidObject))
            {
                Utils.ShowWarningMessageBox(string.Format("Graphic overrides category '{0}' is not found or is not valid", buildInCategory.ToString()));
                return;
            }

            if (!(view.IsCategoryOverridable(categoryId)))
            {
                Utils.ShowWarningMessageBox(string.Format("Graphic overrides category '{0}' is not overridable", buildInCategory.ToString()));
                return;
            }

            ogSettings.SetCutBackgroundPatternColor(backgroundColor);
            ogSettings.SetCutForegroundPatternId(foregroundFillPattern.Id);
            view.SetCategoryOverrides(categoryId, ogSettings);
        }
Esempio n. 25
0
        public Result Execute(ExternalCommandData commandData,
                              ref string message,
                              ElementSet elements)
        {
            Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document;

            PlunkOClass plunkThis        = new PlunkOClass(commandData.Application);
            string      wsName           = "ELEC LIGHTING DIAGNOSTIC";
            string      FamilyName       = "OCC-SENSOR-DETECTION-CMR09";
            string      FamilySymbolName = "DET BLADES ALL";
            string      pNameOccHeight   = "HEIGHT_ABOVE_FLOOR";

            bool            oneShot   = true;
            BuiltInCategory bicFamily = BuiltInCategory.OST_LightingDevices;

            if (plunkThis.NotInThisView())
            {
                return(Result.Succeeded);
            }

            CheckThisFamilyPairing(doc, typeof(FamilySymbol), FamilyName, FamilySymbolName, bicFamily);

            Element elemPlunked = null;
            double  optOffset   = plunkThis.GetCeilingHeight("OCC Sensor Tool Plunk");
            Double  pOffSetX    = 0.0;
            Double  pOffSetY    = 0.0;
            Double  pOffSetZ    = 0.0 + optOffset;
            Units   unit        = commandData.Application.ActiveUIDocument.Document.GetUnits();
            string  optMSG      = " : will be at " + UnitFormatUtils.Format(unit, UnitType.UT_Length, optOffset, false, false);

            if (optOffset != 0.0)
            {
                plunkThis.PlunkThisFamilyType(FamilyName, FamilySymbolName, wsName, bicFamily, out elemPlunked, oneShot, pOffSetX, pOffSetY, pOffSetZ, optMSG);
            }

            /// At this point there may or may not have been an element placed.
            #region SetParametersSection
            if (elemPlunked != null)
            {
                using (Transaction tp = new Transaction(doc, "PlunkOMatic:SetParam")) {
                    tp.Start();
                    //TaskDialog.Show(_pName, _pName);
                    Parameter parToSet = null;
                    parToSet = elemPlunked.LookupParameter(pNameOccHeight);
                    string strVal = UnitFormatUtils.Format(unit, UnitType.UT_Length, optOffset, false, false);
                    if (null != parToSet)
                    {
                        parToSet.SetValueString(strVal); // this parameter is distance, therefore valuestring
                    }
                    else
                    {
                        FamilyUtils.SayMsg("Cannot Set Parameter Value: " + strVal, "... because parameter:\n" + pNameOccHeight
                                           + "\ndoes not exist in the family:\n" + FamilyName
                                           + "\nof Category:\n" + bicFamily.ToString().Replace("OST_", ""));
                    }
                    tp.Commit();
                }
            }
            #endregion
            return(Result.Succeeded);
        }