public CategoriesView(CategoryNameMap map) { Text = "Snoop Categories"; TvObjs.BeginUpdate(); AddObjectsToTree(map, TvObjs.Nodes); TvObjs.EndUpdate(); }
/// <summary> /// Report Rows /// </summary> public List <clsData> Report(List <Category> cats) { try { if (_report.Count < 1) { foreach (Category c in cats) { _report.Add(new clsData(c, false)); CategoryNameMap map = c.SubCategories; if (map != null && map.Size > 0) { IOrderedEnumerable <Category> orderedMap = from Category cm in map orderby cm.Name ascending select cm; foreach (Category subCat in orderedMap) { _report.Add(new clsData(subCat, true)); } } } } } catch (Exception exception) { Debug.WriteLine(exception.Message); } return(_report); }
Categories(CategoryNameMap map) { this.Text = "Snoop Categories"; m_tvObjs.BeginUpdate(); AddObjectsToTree(map, m_tvObjs.Nodes); m_tvObjs.EndUpdate(); }
Categories(CategoryNameMap map) { Text = "Snoop Categories"; MTvObjs.BeginUpdate(); AddObjectsToTree(map, MTvObjs.Nodes); MTvObjs.EndUpdate(); }
/// <summary> /// prepare data for the dialog /// </summary> public void PrepareData() { //Create seven Load Natures first if (!CreateLoadNatures()) { return; } //get all the categories of load cases UIApplication uiapplication = new UIApplication(m_revit); Categories categories = uiapplication.ActiveUIDocument.Document.Settings.Categories; Category category = categories.get_Item(BuiltInCategory.OST_LoadCases); CategoryNameMap categoryNameMap = category.SubCategories; System.Collections.IEnumerator iter = categoryNameMap.GetEnumerator(); iter.Reset(); while (iter.MoveNext()) { Category temp = iter.Current as Category; if (null == temp) { continue; } m_dataBuffer.LoadCasesCategory.Add(temp); } //get all the loadnatures name IList <Element> elements = new FilteredElementCollector(uiapplication.ActiveUIDocument.Document).OfClass(typeof(LoadNature)).ToElements(); foreach (Element e in elements) { LoadNature nature = e as LoadNature; if (null != nature) { m_dataBuffer.LoadNatures.Add(nature); LoadNaturesMap newLoadNaturesMap = new LoadNaturesMap(nature); m_dataBuffer.LoadNaturesMap.Add(newLoadNaturesMap); } } elements = new FilteredElementCollector(uiapplication.ActiveUIDocument.Document).OfClass(typeof(LoadCase)).ToElements(); foreach (Element e in elements) { //get all the loadcases LoadCase loadCase = e as LoadCase; if (null != loadCase) { m_dataBuffer.LoadCases.Add(loadCase); LoadCasesMap newLoadCaseMap = new LoadCasesMap(loadCase); m_dataBuffer.LoadCasesMap.Add(newLoadCaseMap); } } }
private static ElementId CategorySetup(Document doc) { string name = "View Outline"; var parent = Category.GetCategory(doc, BuiltInCategory.OST_CLines); CategoryNameMap map = parent.SubCategories; var subcat = !map.Contains(name) ? doc.Settings.Categories.NewSubcategory(parent, name) : map.get_Item(name); subcat.SetLineWeight(1, GraphicsStyleType.Projection); subcat.LineColor = new Color(255, 128, 0); subcat.SetLinePatternId(doc.GetDash(), GraphicsStyleType.Projection); return(subcat.Id); }
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); }
//判断线样式是否存在 private bool IsExistLineStyle(Document doc, string Name) { Category IsCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); CategoryNameMap map = IsCategory.SubCategories; foreach (Category g in map) { if (g.Name == Name) { return(true); } } return(false); }
// Detailed line methods public static void GetListOfLinestyles(Document doc) { Category c = doc.Settings.Categories.get_Item( BuiltInCategory.OST_Lines); CategoryNameMap subcats = c.SubCategories; foreach (Category lineStyle in subcats) { Debug.Print("Line style", string.Format( "Linestyle {0} id {1}", lineStyle.Name, lineStyle.Id.ToString())); } }
/// <summary> /// Get a list of line styles loaded in the document as Revit Category objects. These can be iterated over and/or passed to the LineStyleRAW class. /// </summary> /// <returns>A list of Revit Category objects which represent line styles as document settings.</returns> public List <Category> GetDocumentLineStyles() { List <Category> documentLineStyles = new List <Category>(); Category lineStylesCategory = Doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); CategoryNameMap lineStyleSubTypes = lineStylesCategory.SubCategories; foreach (Category subCatLineStyle in lineStyleSubTypes) { documentLineStyles.Add(subCatLineStyle); } return(documentLineStyles); }
//搜索目标线样式 private Category BackLineStyle(Document doc) { Category lineCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); CategoryNameMap map = lineCategory.SubCategories; foreach (Category g in map) { if (g.Name == "房间边界线") { return(g); } } return(null); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { IList <Reference> linesToDelete = uidoc.Selection.PickObjects(ObjectType.Element, "Select linestyles to delete"); Category c = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); CategoryNameMap subcats = c.SubCategories; using (Transaction t = new Transaction(doc, "Place text")) { t.Start(); foreach (Reference line in linesToDelete) { CurveElement curveEle = doc.GetElement(line) as CurveElement; foreach (Category cat in subcats) { if (cat.Name == curveEle.LineStyle.Name) { doc.Delete(cat.Id); break; } } //Category cat = subcats.Where( x => x.Name == curveEle.LineStyle.Name).First(); doc.Delete(curveEle.LineStyle.Id); doc.Delete(line.ElementId); } t.Commit(); } return(Result.Succeeded); } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); return(Result.Failed); } }
/// <summary> /// 获取所有线型类别 方法二:通过document setting /// </summary> /// <param name="doc"></param> /// <returns></returns> public static List <GraphicsStyle> getAllLineGraphicses(Document doc) { List <GraphicsStyle> lineStyles = new List <GraphicsStyle>(); Settings documentSettings = doc.Settings; Categories ParentCategoyry = doc.Settings.Categories; Category ParentLineCategoyry = ParentCategoyry.get_Item(BuiltInCategory.OST_Lines); CategoryNameMap _CategoryNameMap = ParentLineCategoyry.SubCategories; foreach (Category lineStyle in _CategoryNameMap) { GraphicsStyle _GraphicsStyle = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection); lineStyles.Add(_GraphicsStyle); } return(lineStyles); }
/// <summary> /// 获取所有线型类别 方法二:通过document setting /// </summary> /// <param name="doc"></param> /// <returns></returns> public static ICollection <ElementId> GetAllLineStyleIdsFromSetting(Document doc) { ICollection <ElementId> styles = new List <ElementId>(); Settings documentSettings = doc.Settings; Categories ParentCategoyry = doc.Settings.Categories; Category ParentLineCategoyry = ParentCategoyry.get_Item(BuiltInCategory.OST_Lines); CategoryNameMap _CategoryNameMap = ParentLineCategoyry.SubCategories; foreach (Category lineStyle in _CategoryNameMap) { GraphicsStyle _GraphicsStyle = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection); styles.Add(_GraphicsStyle.Id); } return(styles); }
private static string GetCategoryName(IEnumerable <ModelProperty> propertySet) { if (propertySet == null) { return(null); } // Note: ExtensibilityAccessor uses CategoryAttribute to look up the category name. // CategoryAttribute logic tries to look up the localized names for standard category names // by default already. CategoryNameMap.GetLocalizedCategoryName() takes care of the few, // special WPF categories that are not found by the existing mechanism. foreach (ModelProperty property in propertySet) { return(CategoryNameMap.GetLocalizedCategoryName(ExtensibilityAccessor.GetCategoryName(property))); } return(null); }
/// <summary> /// Hide the LightingFixtures category /// Hosts subcategory in the given view, cf. /// http://forums.autodesk.com/t5/revit-api/how-to-get-image-of-a-family-model-without-showing-host-element/td-p/5526085 /// http://forums.autodesk.com/t5/revit-api/how-to-change-visibility-setting/td-p/5526076 /// http://forums.autodesk.com/t5/revit-api/how-to-get-family-model-image/td-p/5494839 /// </summary> void HideLightingFixtureHosts(View view) { Document doc = view.Document; Categories categories = doc.Settings.Categories; Category catLightingFixtures = categories.get_Item( BuiltInCategory.OST_LightingFixtures); CategoryNameMap subcats = catLightingFixtures.SubCategories; Category catHosts = subcats.get_Item("Hosts"); view.SetVisibility(catHosts, false); }
AddObjectsToTree(CategoryNameMap map, TreeNodeCollection curNodes) { m_tvObjs.Sorted = true; if (map.IsEmpty) return; // nothing to add // iterate over the map and add items to the tree CategoryNameMapIterator iter = map.ForwardIterator(); while (iter.MoveNext()) { TreeNode tmpNode = new TreeNode(iter.Key); tmpNode.Tag = iter.Current; curNodes.Add(tmpNode); // recursively add sub-nodes (if any) Category curCat = (Category)iter.Current; AddObjectsToTree(curCat.SubCategories, tmpNode.Nodes); } }
AddObjectsToTree(CategoryNameMap map, TreeNodeCollection curNodes) { m_tvObjs.Sorted = true; if (map.IsEmpty) { return; // nothing to add } // iterate over the map and add items to the tree CategoryNameMapIterator iter = map.ForwardIterator(); while (iter.MoveNext()) { TreeNode tmpNode = new TreeNode(iter.Key); tmpNode.Tag = iter.Current; curNodes.Add(tmpNode); // recursively add sub-nodes (if any) Category curCat = (Category)iter.Current; AddObjectsToTree(curCat.SubCategories, tmpNode.Nodes); } }
private void AddObjectsToTree(CategoryNameMap map, TreeNodeCollection curNodes) { TvObjs.Sorted = true; if (map.IsEmpty) { return; } // iterate over the map and add items to the tree var iterator = map.ForwardIterator(); while (iterator.MoveNext()) { var tmpNode = new TreeNode(iterator.Key) { Tag = iterator.Current }; curNodes.Add(tmpNode); // recursively add sub-nodes (if any) var curCat = (Category)iterator.Current; AddObjectsToTree(curCat !.SubCategories, tmpNode.Nodes); } }
private void CategorySetup(CC_Category cat) { if (cat.BuiltInCategory > 0) { Category bic = GetBuiltInCategory(currentDoc, cat.BuiltInCategory); setCategoryStyles(bic, cat); } else { CC_Category parentcat = CategoryCalls.getCategory(cat.Name); Category parent = GetBuiltInCategory(currentDoc, parentcat.BuiltInCategory); CategoryNameMap map = parent.SubCategories; if (!map.Contains(cat.Name)) { Category subcat = currentDoc.Settings.Categories.NewSubcategory(parent, cat.Name); setCategoryStyles(subcat, cat); } else { Category subcat = map.get_Item(cat.Name); setCategoryStyles(subcat, cat); } } }
/// <summary> /// The method is used to collect template information, specifying the New Window Parameters /// </summary> private void CollectTemplateInfo() { List <Wall> walls = Utility.GetElements <Wall>(m_application, m_document); m_wallThickness = walls[0].Width; ParameterMap paraMap = walls[0].ParametersMap; Parameter wallheightPara = walls[0].get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);//paraMap.get_Item("Unconnected Height"); if (wallheightPara != null) { m_wallHeight = wallheightPara.AsDouble(); } LocationCurve location = walls[0].Location as LocationCurve; m_wallWidth = location.Curve.Length; m_windowInset = m_wallThickness / 10; FamilyType type = m_familyManager.CurrentType; FamilyParameter heightPara = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT); FamilyParameter widthPara = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH); FamilyParameter sillHeightPara = m_familyManager.get_Parameter("Default Sill Height"); if (type.HasValue(heightPara)) { switch (heightPara.StorageType) { case StorageType.Double: m_height = type.AsDouble(heightPara).Value; break; case StorageType.Integer: m_height = type.AsInteger(heightPara).Value; break; } } if (type.HasValue(widthPara)) { switch (widthPara.StorageType) { case StorageType.Double: m_width = type.AsDouble(widthPara).Value; break; case StorageType.Integer: m_width = type.AsDouble(widthPara).Value; break; } } if (type.HasValue(sillHeightPara)) { switch (sillHeightPara.StorageType) { case StorageType.Double: m_sillHeight = type.AsDouble(sillHeightPara).Value; break; case StorageType.Integer: m_sillHeight = type.AsDouble(sillHeightPara).Value; break; } } //set the height,width and sillheight parameter of the opening m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT), m_height); m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH), m_width); m_familyManager.Set(m_familyManager.get_Parameter("Default Sill Height"), m_sillHeight); //get materials FilteredElementCollector elementCollector = new FilteredElementCollector(m_document); elementCollector.WherePasses(new ElementClassFilter(typeof(Material))); IList <Element> materials = elementCollector.ToElements(); foreach (Element materialElement in materials) { Material material = materialElement as Material; m_para.GlassMaterials.Add(material.Name); m_para.FrameMaterials.Add(material.Name); } //get categories Categories categories = m_document.Settings.Categories; Category category = categories.get_Item(BuiltInCategory.OST_Windows); CategoryNameMap cnm = category.SubCategories; m_frameCat = categories.get_Item(BuiltInCategory.OST_WindowsFrameMullionProjection); m_glassCat = categories.get_Item(BuiltInCategory.OST_WindowsGlassProjection); //get referenceplanes List <ReferencePlane> planes = Utility.GetElements <ReferencePlane>(m_application, m_document); foreach (ReferencePlane p in planes) { if (p.Name.Equals("Sash")) { m_sashPlane = p; } if (p.Name.Equals("Exterior")) { m_exteriorPlane = p; } if (p.Name.Equals("Center (Front/Back)")) { m_centerPlane = p; } if (p.Name.Equals("Top") || p.Name.Equals("Head")) { m_topPlane = p; } if (p.Name.Equals("Sill") || p.Name.Equals("Bottom")) { m_sillPlane = p; } } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { XYZ origin = uidoc.Selection.PickPoint("Select insertion point"); double width = 0.2; //feet Category c = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); CategoryNameMap subcats = c.SubCategories; double offset = 0; TextNoteOptions options = new TextNoteOptions(); options.HorizontalAlignment = HorizontalTextAlignment.Left; options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType); var dict = new SortedDictionary <string, GraphicsStyle>(); foreach (Category lineStyle in subcats) { GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection); dict.Add(gs.Name, gs); } var output = dict.OrderBy(e => e.Key).Select(e => new { graphicStyle = e.Value, linestyleName = e.Key }).ToList(); using (Transaction t = new Transaction(doc, "Place Lines")) { t.Start(); //foreach( Line item in ordered) { foreach (var item in output) { // GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection); XYZ newOrigin = new XYZ(origin.X, origin.Y + offset, 0); XYZ offsetPoint = new XYZ(origin.X + width, origin.Y + offset, 0); Line L1 = Line.CreateBound(newOrigin, offsetPoint); try { TextNote note = TextNote.Create(doc, doc.ActiveView.Id, new XYZ(origin.X - 0.2, origin.Y + offset + 0.01, 0), 0.2, item.linestyleName, options); DetailCurve e = doc.Create.NewDetailCurve(doc.ActiveView, L1); Parameter p = e.LookupParameter("Line Style"); p.Set(item.graphicStyle.Id); } catch { } offset -= 0.03; } t.Commit(); } return(Result.Succeeded); } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); return(Result.Failed); } }
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); }
/// <summary> /// /// </summary> /// <param name="filePath"></param> /// <param name="sched"></param> /// <param name="doc"></param> /// <param name="pt"></param> /// <param name="contentOnly"></param> public void AddScheduleData(string filePath, ViewSchedule sched, Document doc, PathType pt, bool contentOnly) { string docPath; if (doc.IsWorkshared) { docPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath()); } else { docPath = doc.PathName; } string fullPath; if (pt == PathType.Absolute) { fullPath = filePath; } else { fullPath = PathExchange.GetFullPath(filePath, docPath); } // Get the file path excelFilePath = fullPath; if (!File.Exists(excelFilePath)) { return; } // read the Excel file and create the schedule Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Open(excelFilePath); Excel.Sheets worksheets = workbook.Worksheets; worksheet = null; foreach (Excel.Worksheet ws in worksheets) { if (ws.Name.Trim() == sched.Name.Trim()) { worksheet = ws; } } if (worksheet == null) { return; } //TaskDialog.Show("Test", "Worksheet found"); // Find the ThinLine linestyle CategoryNameMap lineSubCats = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines).SubCategories; ElementId thinLineStyle = new ElementId(-1); ElementId hairlineStyle = new ElementId(-1); ElementId thinStyle = new ElementId(-1); ElementId mediumStyle = new ElementId(-1); ElementId thickStyle = new ElementId(-1); foreach (Category style in lineSubCats) { if (style.Name == "Thin Lines") { thinLineStyle = style.Id; } if (style.GetGraphicsStyle(GraphicsStyleType.Projection).Id.IntegerValue == Properties.Settings.Default.hairlineInt) { hairlineStyle = style.Id; } else if (style.GetGraphicsStyle(GraphicsStyleType.Projection).Id.IntegerValue == Properties.Settings.Default.thinInt) { thinStyle = style.Id; } else if (style.GetGraphicsStyle(GraphicsStyleType.Projection).Id.IntegerValue == Properties.Settings.Default.mediumInt) { mediumStyle = style.Id; } else if (style.GetGraphicsStyle(GraphicsStyleType.Projection).Id.IntegerValue == Properties.Settings.Default.thickInt) { thickStyle = style.Id; } } if (hairlineStyle.IntegerValue == -1) { hairlineStyle = thinLineStyle; } if (thinStyle.IntegerValue == -1) { thinStyle = thinLineStyle; } if (mediumStyle.IntegerValue == -1) { mediumStyle = thinLineStyle; } if (thickStyle.IntegerValue == -1) { thickStyle = thinLineStyle; } // Find out how many rows and columns we need in the schedule Excel.Range rng = ActualUsedRange(worksheet); Excel.Range range = rng; int rowCount = range.Rows.Count; int columnCount = range.Columns.Count; // Get the schedule body to set the overall width TableSectionData bodyData = sched.GetTableData().GetSectionData(SectionType.Body); if (!contentOnly) { double schedWidth = range.Columns.Width; try { bodyData.SetColumnWidth(0, (schedWidth * pointWidthInches) / 12); } catch { } } // Get the header body to create the necessary rows and columns TableSectionData headerData = sched.GetTableData().GetSectionData(SectionType.Header); if (!contentOnly) { //TaskDialog.Show("Test: ", "Row Count: " + rowCount.ToString() + "\nColumn Count: " + columnCount.ToString()); for (int i = 0; i < columnCount - 1; i++) { headerData.InsertColumn(1); } for (int i = 0; i < rowCount - 1; i++) { headerData.InsertRow(1); } for (int i = 1; i <= headerData.NumberOfColumns; i++) { try { Excel.Range cell = worksheet.Cells[1, i]; headerData.SetColumnWidth(i - 1, (cell.Width * pointWidthInches) / 12); } catch { } } for (int i = 1; i <= headerData.NumberOfRows; i++) { try { Excel.Range cell = worksheet.Cells[i, 1]; headerData.SetRowHeight(i - 1, (cell.Height * pointWidthInches) / 12); } catch { } } } List <TableMergedCell> mergedCells = new List <TableMergedCell>(); int errorCount = 0; for (int i = 1; i <= headerData.NumberOfRows; i++) // Iterate through rows of worksheet data { for (int j = 1; j <= headerData.NumberOfColumns; j++) // Iterate through columns of worksheet data { // Get the current cell in the worksheet grid Excel.Range cell = worksheet.Cells[i, j]; // If adjusting the formatting or adding content is not necessary, // just update the text content. This is via a UI switch. if (contentOnly) { try { headerData.SetCellText(i - 1, j - 1, cell.Text); continue; } catch { errorCount++; continue; } } Excel.Font font = cell.Font; Excel.DisplayFormat dispFormat = cell.DisplayFormat; TableCellStyle cellStyle = new TableCellStyle(); TableCellStyleOverrideOptions styleOverride = cellStyle.GetCellStyleOverrideOptions(); Excel.Border topEdge = cell.Borders.Item[Excel.XlBordersIndex.xlEdgeTop]; Excel.Border bottomEdge = cell.Borders.Item[Excel.XlBordersIndex.xlEdgeBottom]; Excel.Border leftEdge = cell.Borders.Item[Excel.XlBordersIndex.xlEdgeLeft]; Excel.Border rightEdge = cell.Borders.Item[Excel.XlBordersIndex.xlEdgeRight]; // Determine Bottom Edge Line Style if (bottomEdge.LineStyle == (int)Excel.XlLineStyle.xlLineStyleNone) { cellStyle.BorderBottomLineStyle = new ElementId(-1); } else { switch (bottomEdge.Weight) { case (int)Excel.XlBorderWeight.xlHairline: cellStyle.BorderBottomLineStyle = hairlineStyle; break; case (int)Excel.XlBorderWeight.xlThin: cellStyle.BorderBottomLineStyle = thinStyle; break; case (int)Excel.XlBorderWeight.xlMedium: cellStyle.BorderBottomLineStyle = mediumStyle; break; case (int)Excel.XlBorderWeight.xlThick: cellStyle.BorderBottomLineStyle = thickStyle; break; } } // Determine Top Edge Line Style if (topEdge.LineStyle == (int)Excel.XlLineStyle.xlLineStyleNone) { cellStyle.BorderTopLineStyle = new ElementId(-1); } else { switch (topEdge.Weight) { case (int)Excel.XlBorderWeight.xlHairline: cellStyle.BorderTopLineStyle = hairlineStyle; break; case (int)Excel.XlBorderWeight.xlThin: cellStyle.BorderTopLineStyle = thinStyle; break; case (int)Excel.XlBorderWeight.xlMedium: cellStyle.BorderTopLineStyle = mediumStyle; break; case (int)Excel.XlBorderWeight.xlThick: cellStyle.BorderTopLineStyle = thickStyle; break; } } // Determine Left Edge Line Style if (leftEdge.LineStyle == (int)Excel.XlLineStyle.xlLineStyleNone) { cellStyle.BorderLeftLineStyle = new ElementId(-1); } else { switch (leftEdge.Weight) { case (int)Excel.XlBorderWeight.xlHairline: cellStyle.BorderLeftLineStyle = hairlineStyle; break; case (int)Excel.XlBorderWeight.xlThin: cellStyle.BorderLeftLineStyle = thinStyle; break; case (int)Excel.XlBorderWeight.xlMedium: cellStyle.BorderLeftLineStyle = mediumStyle; break; case (int)Excel.XlBorderWeight.xlThick: cellStyle.BorderLeftLineStyle = thickStyle; break; } } // Determine Right Edge Line Style if (rightEdge.LineStyle == (int)Excel.XlLineStyle.xlLineStyleNone) { cellStyle.BorderRightLineStyle = new ElementId(-1); } else { switch (rightEdge.Weight) { case (int)Excel.XlBorderWeight.xlHairline: cellStyle.BorderRightLineStyle = hairlineStyle; break; case (int)Excel.XlBorderWeight.xlThin: cellStyle.BorderRightLineStyle = thinStyle; break; case (int)Excel.XlBorderWeight.xlMedium: cellStyle.BorderRightLineStyle = mediumStyle; break; case (int)Excel.XlBorderWeight.xlThick: cellStyle.BorderRightLineStyle = thickStyle; break; } } // Border Styles are always overridden styleOverride.BorderBottomLineStyle = true; styleOverride.BorderTopLineStyle = true; styleOverride.BorderLeftLineStyle = true; styleOverride.BorderRightLineStyle = true; if (styleOverride.BorderBottomLineStyle || styleOverride.BorderTopLineStyle || styleOverride.BorderLeftLineStyle || styleOverride.BorderRightLineStyle) { styleOverride.BorderLineStyle = true; } // Get Background color and font name System.Drawing.Color backGroundColor = System.Drawing.ColorTranslator.FromOle((int)cell.Interior.Color); cellStyle.BackgroundColor = new Color(backGroundColor.R, backGroundColor.G, backGroundColor.B); styleOverride.BackgroundColor = true; cellStyle.FontName = cell.Font.Name; styleOverride.Font = true; // Determine Horizontal Alignment // If its not set to left, right or center, do not modify switch (dispFormat.HorizontalAlignment) { case (int)Excel.XlHAlign.xlHAlignLeft: cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Left; styleOverride.HorizontalAlignment = true; break; case (int)Excel.XlHAlign.xlHAlignRight: cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Right; styleOverride.HorizontalAlignment = true; break; case (int)Excel.XlHAlign.xlHAlignGeneral: // No specific style assigned // Check if it's a number which is typically right aligned if (double.TryParse(cell.Text, out double alignTest)) { cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Right; styleOverride.HorizontalAlignment = true; } else // Assume text and left align it { cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Left; styleOverride.HorizontalAlignment = true; } break; case (int)Excel.XlHAlign.xlHAlignCenter: cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Center; styleOverride.HorizontalAlignment = true; break; } // Get the vertical alignment of the cell switch (dispFormat.VerticalAlignment) { case (int)Excel.XlVAlign.xlVAlignBottom: cellStyle.FontVerticalAlignment = VerticalAlignmentStyle.Bottom; styleOverride.VerticalAlignment = true; break; case (int)Excel.XlVAlign.xlVAlignTop: cellStyle.FontVerticalAlignment = VerticalAlignmentStyle.Top; styleOverride.VerticalAlignment = true; break; default: cellStyle.FontVerticalAlignment = VerticalAlignmentStyle.Middle; styleOverride.VerticalAlignment = true; break; } switch (dispFormat.Orientation) { case (int)Excel.XlOrientation.xlUpward: cellStyle.TextOrientation = 9; styleOverride.TextOrientation = true; break; case (int)Excel.XlOrientation.xlDownward: cellStyle.TextOrientation = -9; styleOverride.TextOrientation = true; break; case (int)Excel.XlOrientation.xlVertical: cellStyle.TextOrientation = 9; styleOverride.TextOrientation = true; break; default: int rotation = (int)cell.Orientation; if (rotation != (int)Excel.XlOrientation.xlHorizontal) { cellStyle.TextOrientation = rotation; styleOverride.TextOrientation = true; } break; } // Determine Text Size double textSize = Convert.ToDouble(font.Size); //double newTextSize = (textSize / 72) / 12; cellStyle.TextSize = textSize; styleOverride.FontSize = true; // Determine Font Color System.Drawing.Color fontColor = System.Drawing.ColorTranslator.FromOle((int)font.Color); cellStyle.TextColor = new Color(fontColor.R, fontColor.G, fontColor.B); styleOverride.FontColor = true; // NOTES: Bold is a bool // Italic is a bool // Underline is an int cellStyle.IsFontBold = (bool)font.Bold; cellStyle.IsFontItalic = (bool)font.Italic; cellStyle.IsFontUnderline = (int)font.Underline == 2; styleOverride.Bold = true; styleOverride.Italics = true; styleOverride.Underline = true; cellStyle.SetCellStyleOverrideOptions(styleOverride); if (cell.MergeCells == true) { TableMergedCell tmc = new TableMergedCell() { Left = j - 1, Right = cell.MergeArea.Columns.Count - 1, Top = i - 1, Bottom = (i - 1) + cell.MergeArea.Rows.Count - 1 }; // Check to see if the cell is already merged... bool alreadyMerged = false; foreach (TableMergedCell mergedCell in mergedCells) { bool left = false; bool right = false; bool top = false; bool bottom = false; if (i - 1 >= mergedCell.Top) { top = true; } if (i - 1 <= mergedCell.Bottom) { bottom = true; } if (j - 1 >= mergedCell.Left) { left = true; } if (j - 1 <= mergedCell.Right) { right = true; } //TaskDialog.Show("MergedCell", string.Format("Top: {0}\nBottom: {1}\nLeft: {2}\nRight: {3}\ni-1: {4}\nj-1: {5}", mergedCell.Top, mergedCell.Bottom, mergedCell.Left, mergedCell.Right, i - 1, j - 1)); if (top && bottom && left && right) { alreadyMerged = true; break; } } if (!alreadyMerged) { try { headerData.MergeCells(tmc); headerData.SetCellText(i - 1, j - 1, cell.Text); headerData.SetCellStyle(i - 1, j - 1, cellStyle); j += cell.MergeArea.Columns.Count - 1; mergedCells.Add(tmc); // TaskDialog.Show("Test", string.Format("This cell [{0},{1}] is merged.\nMerged Area: [{2},{3}]", cell.Row - 1, cell.Column - 1, cell.MergeArea.Rows.Count.ToString(), cell.MergeArea.Columns.Count.ToString())); } catch { } } } else { //TaskDialog.Show("Non Merged", string.Format("This cell is not merged with any others [{0}, {1}]", i - 1, j - 1)); try { headerData.SetCellText(i - 1, j - 1, cell.Text); headerData.SetCellStyle(i - 1, j - 1, cellStyle); } catch { } } } } if (errorCount > 0) { TaskDialog.Show("Warning", "Error reloading content for " + errorCount.ToString() + " cells.\n\nConsider unchecking the \"Content Only\" checkbox and reloading the schedule to force it to rebuild."); } // Write the Schema to the project Schema schema = null; try { schema = Schema.Lookup(schemaGUID); } catch { } ModifySchemaData(schema, sched.Id); workbook.Close(false); Marshal.ReleaseComObject(worksheets); Marshal.ReleaseComObject(worksheet); Marshal.ReleaseComObject(workbook); excelApp.Quit(); Marshal.ReleaseComObject(excelApp); }
public CategoryNameMapData(string label, CategoryNameMap val) : base(label) { _value = val; }
private static bool InitFromFile() { string fileName = IFCImportFile.TheFile.Document.Application.ImportIFCCategoryTable; StreamReader inFile = null; if (!string.IsNullOrWhiteSpace(fileName)) { try { inFile = new StreamReader(fileName); } catch { return(false); } } if (inFile == null) { return(false); } IDictionary <string, Category> createdSubcategories = Importer.TheCache.CreatedSubcategories; while (true) { string nextLine = inFile.ReadLine(); if (nextLine == null) { break; } // Skip empty line. if (string.IsNullOrWhiteSpace(nextLine)) { continue; } // Skip comment. if (nextLine.First() == '#') { continue; } string[] fields = nextLine.Split('\t'); int numFields = fields.Count(); // Too few fields, ignore. if (numFields < 3) { continue; } string ifcClassName = fields[0]; if (string.IsNullOrWhiteSpace(ifcClassName)) { continue; } IFCEntityType ifcClassType; if (!Enum.TryParse <IFCEntityType>(ifcClassName, true, out ifcClassType)) { IFCImportFile.TheLog.LogWarning(-1, "Unknown class name in IFC entity to category mapping file: " + ifcClassName, true); continue; } bool hasTypeName = (numFields == 4); string ifcTypeName = null; if (hasTypeName) { ifcTypeName = fields[1]; } // Skip entries we have already seen bool alreadyPresent = false; if (string.IsNullOrWhiteSpace(ifcTypeName)) { alreadyPresent = m_EntityTypeToCategory.ContainsKey(ifcClassType); } else { alreadyPresent = m_EntityShapeTypeToCategory.ContainsKey(new KeyValuePair <IFCEntityType, string>(ifcClassType, ifcTypeName)); } if (alreadyPresent) { continue; } int categoryField = hasTypeName ? 2 : 1; int subCategoryField = hasTypeName ? 3 : 2; // If set to "Don't Import", or some variant, ignore this entity. string categoryName = fields[categoryField]; if (IsEqualIgnoringCaseSpacesApostrophe(categoryName, "DontImport")) { if (string.IsNullOrWhiteSpace(ifcTypeName)) { m_EntityDontImport.Add(ifcClassType); } else { m_EntityDontImportShapeType.Add(new KeyValuePair <IFCEntityType, string>(ifcClassType, ifcTypeName)); } continue; } // TODO: Use enum name, not category name, in file. ElementId categoryId = ElementId.InvalidElementId; Category category = null; try { category = Importer.TheCache.DocumentCategories.get_Item(categoryName); categoryId = category.Id; } catch { IFCImportFile.TheLog.LogWarning(-1, "Unknown top-level category in IFC entity to category mapping file: " + categoryName, true); continue; } string subCategoryName = null; if (numFields > 2) { subCategoryName = fields[subCategoryField]; if (!string.IsNullOrWhiteSpace(subCategoryName)) { CategoryNameMap subCategories = category.SubCategories; try { Category subcategory = subCategories.get_Item(subCategoryName); categoryId = subcategory.Id; } catch { if (category.CanAddSubcategory) { Category subcategory = null; if (!createdSubcategories.TryGetValue(subCategoryName, out subcategory)) { subcategory = Importer.TheCache.DocumentCategories.NewSubcategory(category, subCategoryName); createdSubcategories[subCategoryName] = subcategory; } categoryId = subcategory.Id; } else { IFCImportFile.TheLog.LogWarning(-1, "Can't add sub-category " + subCategoryName + " to top-level category " + categoryName + " in IFC entity to category mapping file.", true); } } } } if (string.IsNullOrWhiteSpace(ifcTypeName)) { m_EntityTypeToCategory[ifcClassType] = (BuiltInCategory)category.Id.IntegerValue; } else { m_EntityShapeTypeToCategory[new KeyValuePair <IFCEntityType, string>(ifcClassType, ifcTypeName)] = (BuiltInCategory)category.Id.IntegerValue; } } return(true); }
/// <summary> /// Get the top-level Built-in category id for an IFC entity. /// </summary> /// <param name="doc">The doument.</param> /// <param name="entity">The entity.</param> /// <param name="gstyleId">The graphics style, if the returned category is not top level. This allows shapes to have their visibility controlled by the sub-category.</param> /// <returns>The element id for the built-in category.</returns> public static ElementId GetCategoryIdForEntity(Document doc, IFCObjectDefinition entity, out ElementId gstyleId) { gstyleId = ElementId.InvalidElementId; IFCEntityType entityType = entity.EntityType; IFCEntityType?typeEntityType = null; string typeShapeType = null; GetAssociatedTypeEntityInfo(entity, out typeEntityType, out typeShapeType); // Use the IfcTypeObject shape type if the IfcElement shape type is either null, empty, white space, or not defined. string shapeType = entity.ShapeType; if ((string.IsNullOrWhiteSpace(shapeType) || (string.Compare(shapeType, "NOTDEFINED", true) == 0)) && !string.IsNullOrWhiteSpace(typeShapeType)) { shapeType = typeShapeType; } // Set "special" shape types switch (entityType) { case IFCEntityType.IfcColumn: case IFCEntityType.IfcColumnType: if (IsColumnLoadBearing(entity)) { shapeType = "[LoadBearing]"; } break; } ElementId catElemId = GetCategoryElementId(entityType, shapeType); // If we didn't find a category, or if we found the generic model category, try again with the IfcTypeObject, if there is one. if (catElemId == ElementId.InvalidElementId || catElemId.IntegerValue == (int)BuiltInCategory.OST_GenericModel) { if (typeEntityType.HasValue) { catElemId = GetCategoryElementId(typeEntityType.Value, shapeType); } } Category subCategory = null; if (catElemId.IntegerValue == (int)BuiltInCategory.OST_GenericModel) { string subCategoryName = GetCustomCategoryName(entity); if (!string.IsNullOrWhiteSpace(subCategoryName)) { IDictionary <string, Category> createdSubcategories = Importer.TheCache.CreatedSubcategories; if (!createdSubcategories.TryGetValue(subCategoryName, out subCategory)) { // Category may have been created by a previous action (probably a previous import). Look first. try { CategoryNameMap subCategories = Importer.TheCache.GenericModelsCategory.SubCategories; subCategory = subCategories.get_Item(subCategoryName); } catch { subCategory = null; } if (subCategory == null) { subCategory = Importer.TheCache.DocumentCategories.NewSubcategory(Importer.TheCache.GenericModelsCategory, subCategoryName); SetMaterialForSpacesAndOpenings(doc, entity.Id, subCategory, subCategoryName); } createdSubcategories[subCategoryName] = subCategory; } GraphicsStyle graphicsStyle = subCategory.GetGraphicsStyle(GraphicsStyleType.Projection); if (graphicsStyle != null) { gstyleId = graphicsStyle.Id; } } } else if (catElemId == ElementId.InvalidElementId) { catElemId = new ElementId(BuiltInCategory.OST_GenericModel); // Top level entities that are OK to be here. if (entityType != IFCEntityType.IfcProject && entityType != IFCEntityType.IfcBuilding && entityType != IFCEntityType.IfcBuildingStorey && entityType != IFCEntityType.IfcElementAssembly) { string msg = "Setting IFC entity "; if (string.IsNullOrWhiteSpace(shapeType)) { msg = entityType.ToString(); } else { msg = entityType.ToString() + "." + shapeType; } if (typeEntityType.HasValue) { msg += " (" + typeEntityType.Value.ToString() + ")"; } msg += " to Generic Models."; IFCImportFile.TheLog.LogWarning(entity.Id, msg, true); } } Category categoryToCheck = null; if (catElemId.IntegerValue < 0) { categoryToCheck = Importer.TheCache.DocumentCategories.get_Item((BuiltInCategory)catElemId.IntegerValue); } else { categoryToCheck = subCategory; } if (categoryToCheck != null) { // We'll assume that a negative value means a built-in category. It may still be a sub-category, in which case we need to get the parent category and assign the gstyle. // We could optimize this, but this is safer. Category parentCategory = categoryToCheck.Parent; if (parentCategory != null) { catElemId = parentCategory.Id; } // Not already set by subcategory. if (gstyleId == ElementId.InvalidElementId) { GraphicsStyle graphicsStyle = categoryToCheck.GetGraphicsStyle(GraphicsStyleType.Projection); if (graphicsStyle != null) { gstyleId = graphicsStyle.Id; } } } return(catElemId); }
/// <summary> /// Duplicate a new load case /// </summary> /// <param name="index"></param> /// <returns></returns> public bool DuplicateLoadCase(int index) { LoadCasesMap myLoadCase = null; bool isUnique = false; string caseName = null; //try to get the load case from the map try { myLoadCase = m_dataBuffer.LoadCasesMap[index]; } catch (Exception e) { m_dataBuffer.ErrorInformation += e.ToString(); return(false); } //get nothing if (null == myLoadCase) { m_dataBuffer.ErrorInformation += "Can not find the load case"; return(false); } //check the name caseName = myLoadCase.LoadCasesName; while (!isUnique) { caseName += "(1)"; isUnique = IsCaseNameUnique(caseName); } //get the selected case's nature Category caseCategory = null; LoadNature caseNature = null; Autodesk.Revit.DB.ElementId categoryId = myLoadCase.LoadCasesCategoryId; Autodesk.Revit.DB.ElementId natureId = myLoadCase.LoadCasesNatureId; UIApplication uiapplication = new UIApplication(m_revit); caseNature = uiapplication.ActiveUIDocument.Document.get_Element(natureId) as LoadNature; //get the selected case's category Categories categories = uiapplication.ActiveUIDocument.Document.Settings.Categories; Category category = categories.get_Item(BuiltInCategory.OST_LoadCases); CategoryNameMap categoryNameMap = category.SubCategories; System.Collections.IEnumerator iter = categoryNameMap.GetEnumerator(); iter.Reset(); while (iter.MoveNext()) { Category tempC = iter.Current as Category; if (null != tempC && (categoryId.IntegerValue == tempC.Id.IntegerValue)) { caseCategory = tempC; break; } } //check if lack of the information if (null == caseNature || null == caseCategory || null == caseName) { m_dataBuffer.ErrorInformation += "Can't find the load case"; return(false); } //try to create a load case try { LoadCase newLoadCase = uiapplication.ActiveUIDocument.Document.Create.NewLoadCase(caseName, caseNature, caseCategory); if (null == newLoadCase) { m_dataBuffer.ErrorInformation += "Create Load Case Failed"; return(false); } //add the new case into list and map m_dataBuffer.LoadCases.Add(newLoadCase); LoadCasesMap newLoadCaseMap = new LoadCasesMap(newLoadCase); m_dataBuffer.LoadCasesMap.Add(newLoadCaseMap); } catch (Exception e) { m_dataBuffer.ErrorInformation += e.ToString(); return(false); } return(true); }