public void ShowSample() { Database db = GetDatabase(); Editor ed = GetEditor(); ed.WriteMessage("Adding a new property set definition contains a formula property to calculate wall volume.\n"); // we need to add all the automatic properties prior to the formula property PropertySetDefinition psd = CreateWallPropertySetDefinition(); // then we add the property set definition to the dictionary to make formula property work properly DictionaryPropertySetDefinitions dict = new DictionaryPropertySetDefinitions(db); using (Transaction trans = db.TransactionManager.StartTransaction()) { dict.AddNewRecord("SampleWallPropertySetDefinition", psd); trans.AddNewlyCreatedDBObject(psd, true); // now we can create the formula property PropertyDefinitionFormula formula = new PropertyDefinitionFormula(); formula.SetToStandard(db); formula.SubSetDatabaseDefaults(db); formula.Name = "Wall Volume"; formula.UseFormulaForDescription = true; // before setting formula string to the formula property, we need to make sure // that the property definition is added to the property set definition (which has an object id) psd.Definitions.Add(formula); // so we can set the formula string now formula.SetFormulaString("[Length]*[Height]*[Width]"); // and here we change the sample values of the referenced properties formula.DataItems[0].Sample = 1; formula.DataItems[1].Sample = 2; formula.DataItems[2].Sample = 3; trans.Commit(); } ed.WriteMessage("A new property set definition \"SampleWallPropertySetDefinition\" is created.\n"); ed.WriteMessage("It contains a formula definition named \"Wall Volume\".\n"); }
// another way to find the index of a property definition //private static int FindPropertyDefinitionIndex(PropertySetDefinition psd, string propertyName) //{ // PropertyDefinition propDef = new PropertyDefinition(); // propDef.Name = propertyName; // return psd.Definitions.IndexOf(propDef); //} private static ScheduleTableStyle CreateStyle(UiData uiData, PropertySetDefinition psd, Transaction trans) { Database db = ScheduleSample.GetDatabase(); ScheduleTableStyle style = new ScheduleTableStyle(); style.SetToStandard(db); style.SubSetDatabaseDefaults(db); // sets the object type to which the schedule table style applies StringCollection filter = new StringCollection(); foreach (RXClass rc in uiData.classPropertiesMap.Keys) { filter.Add(rc.Name); } style.AppliesToFilter = filter; CreateChildNodes(uiData.headerColumnDesignData, style.Tree, psd, style); //add it into database DictionaryScheduleTableStyle scheduleTableStyleDict = new DictionaryScheduleTableStyle(db); style.Title = uiData.scheduleTableStyleName; scheduleTableStyleDict.AddNewRecord(uiData.scheduleTableStyleName, style); trans.AddNewlyCreatedDBObject(style, true); return(style); }
/// <summary> /// Creates the whole property sets, schedule table style and schedule table in database. /// </summary> /// <param name="uiData">The data saved from the wizard.</param> /// <returns>Returns the object id of the property set definition, schedule table style and schedule table.</returns> public static ScheduleTableCreateResult CreateScheduleTable(UiData uiData) { ScheduleTableCreateResult result = new ScheduleTableCreateResult(); Database db = ScheduleSample.GetDatabase(); DBTransactionManager tm = db.TransactionManager; using (Transaction trans = tm.StartTransaction()) { try { PropertySetDefinition psd = CreatePropertySetDefinition(uiData, trans); result.PropertySetDefinitionId = psd.Id; if (result.PropertySetDefinitionId == ObjectId.Null) { throw (new System.Exception("Failed to create property set definition.")); } ScheduleTableStyle style = CreateStyle(uiData, psd, trans); result.StyleId = style.Id; if (result.StyleId == ObjectId.Null) { throw (new System.Exception("Failed to create property style.")); } AddPropertySetToObjects(uiData, result.PropertySetDefinitionId, trans); ScheduleTable table = CreateScheduleTable(uiData, result.PropertySetDefinitionId, result.StyleId, trans); result.ScheduleTableId = table.Id; if (result.ScheduleTableId == ObjectId.Null) { throw (new System.Exception("Failed to create Schedule Table.")); } Editor editor = ScheduleSample.GetEditor(); PromptPointResult editorResult = editor.GetPoint("Please pick a point to insert the schedule table:"); if (editorResult.Status == PromptStatus.OK) { table.Location = editorResult.Value; table.Scale = 10; trans.Commit(); } else { trans.Abort(); } } catch (System.Exception) { trans.Abort(); return(null); } finally { trans.Dispose(); } } return(result); }
public static BaseStairObject GetPropertySetDefinitionStairStandardValues() { PropertySetDefinition psd = new PropertySetDefinition(); // ObjectId psdId = ObjectId.Null; Database db = Application.DocumentManager.MdiActiveDocument.Database; Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; BaseStairObject retBso = new BaseStairObject(); using (Transaction tr = tm.StartTransaction()) { try { DictionaryPropertySetDefinitions psdDict = new DictionaryPropertySetDefinitions(db); if (psdDict.Has(MyPlugin.psdName, tr)) { // Get the ObjectID of the property set definition by name // psdId = psdDict.GetAt(MyPlugin.psdName); psd = (PropertySetDefinition)tr.GetObject(psdDict.GetAt(MyPlugin.psdName), OpenMode.ForRead); // Get the standard value from the properties in the property set defenition BaseStairObject bso = new BaseStairObject { Id = ObjectId.Null, Name = Convert.ToString(psd.Definitions[psd.Definitions.IndexOf("name")].DefaultData), Steps = Convert.ToInt32(psd.Definitions[psd.Definitions.IndexOf("_steps")].DefaultData), Tread = Convert.ToDouble(psd.Definitions[psd.Definitions.IndexOf("_tread")].DefaultData), Riser = Convert.ToDouble(psd.Definitions[psd.Definitions.IndexOf("_riser")].DefaultData), Landing = Convert.ToDouble(psd.Definitions[psd.Definitions.IndexOf("_landing")].DefaultData), Width = Convert.ToDouble(psd.Definitions[psd.Definitions.IndexOf("_width")].DefaultData), Slope = Convert.ToDouble(psd.Definitions[psd.Definitions.IndexOf("_slope")].DefaultData) }; retBso = bso; } else { ed.WriteMessage("\n PropertySetDefinition {0} does not exist ", MyPlugin.psdName); } } catch { ed.WriteMessage("\n GetPropertySetDefinitionIdByName failed"); } tr.Commit(); } return(retBso); }
private static PropertySetDefinition CreatePropertySetDefinition(UiData uiData, Transaction trans) { Database db = ScheduleSample.GetDatabase(); string psdName = uiData.propertySetDefinitionName; StringCollection appliesTo = new StringCollection(); foreach (RXClass rc in uiData.classPropertiesMap.Keys) { appliesTo.Add(rc.Name); } // create the property set definition PropertySetDefinition psd = new PropertySetDefinition(); psd.SetToStandard(db); psd.SubSetDatabaseDefaults(db); psd.AlternateName = psdName; psd.IsLocked = false; psd.IsVisible = true; psd.IsWriteable = true; psd.SetAppliesToFilter(appliesTo, false); Dictionary <string, List <RXClass> > propertyClassesMap = uiData.classPropertiesMap.GroupClassesByProperty(); foreach (string propertyName in propertyClassesMap.Keys) { PropertyDefinition propDef = new PropertyDefinition(); propDef.SetToStandard(db); propDef.SubSetDatabaseDefaults(db); propDef.Name = propertyName; propDef.Automatic = true; propDef.Description = propertyName; propDef.IsVisible = true; propDef.IsReadOnly = true; foreach (RXClass objectType in propertyClassesMap[propertyName]) { propDef.SetAutomaticData(objectType.Name, propertyName); } psd.Definitions.Add(propDef); } DictionaryPropertySetDefinitions propDefs = new DictionaryPropertySetDefinitions(db); propDefs.AddNewRecord(uiData.propertySetDefinitionName, psd); trans.AddNewlyCreatedDBObject(psd, true); return(psd); }
public static PropertySetDefinition CreateWallPropertySetDefinition() { Database db = GetDatabase(); PropertySetDefinition def = new PropertySetDefinition(); // we want the property set to apply to walls StringCollection appliesTo = new StringCollection(); string wallClassName = RXObject.GetClass(typeof(Wall)).Name; appliesTo.Add(wallClassName); def.SetToStandard(db); def.SubSetDatabaseDefaults(db); def.AlternateName = "SampleWallPropertySet"; def.IsLocked = false; def.IsVisible = true; def.IsWriteable = true; StringCollection properties = new StringCollection(); properties.Add("Width"); properties.Add("Length"); properties.Add("Height"); foreach (string propName in properties) { PropertyDefinition propDef = new PropertyDefinition(); propDef.SetToStandard(db); propDef.SubSetDatabaseDefaults(db); propDef.Automatic = true; propDef.Name = propName; propDef.Description = propName; propDef.IsVisible = true; propDef.IsReadOnly = true; propDef.SetAutomaticData(wallClassName, propName); def.Definitions.Add(propDef); } return(def); }
public void AddPropertySet() { Database db = HostApplicationServices.WorkingDatabase; ObjectId layoutId = SymbolUtilityServices.GetBlockModelSpaceId(db); using (var tr = db.TransactionManager.StartTransaction()) { var bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; var btr = tr.GetObject(layoutId, OpenMode.ForRead) as BlockTableRecord; btr.Name = "bimcad"; Line line = new Line(Point3d.Origin, new Point3d(10, 15, 0)); PropertySetDefinition psDef = new PropertySetDefinition(); PropertyDefinition propertyDef = new PropertyDefinition(); propertyDef.DataType = Autodesk.Aec.PropertyData.DataType.Text; propertyDef.Id = 1; psDef.Definitions.Add(propertyDef); PropertySet ps = new PropertySet(); ps.PropertySetDefinition = psDef.Id; ps.SetAt(propertyDef.Id, "hello World"); PropertyDataServices.AddPropertySet(line, ps.Id); Circle circle = new Circle(Point3d.Origin, Vector3d.ZAxis, 10); btr.AppendEntity(line); btr.AppendEntity(circle); ObjectId id = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); tr.Commit(); } }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Sets properties according to the provided definition. </summary> /// /// <param name="propertySetDefinition"> The property set definition. </param> /// <param name="onSetProperty"> The set property callback. </param> /// <param name="onGetProperty"> The get property callback. </param> /// /// <returns> true if it succeeds, false if it fails. </returns> public bool SetProperties(PropertySetDefinition propertySetDefinition, Action <string, string> onSetProperty, Func <string, string> onGetProperty) { // Set the properties foreach (var property in propertySetDefinition.Properties) { var splitValues = property.Value.Split(new char[] { ';' }); // Expand properties as needed for (int i = 0; i < splitValues.Length; ++i) { if (splitValues[i].StartsWith("[") && splitValues[i].EndsWith("]")) { var propertyValue = onGetProperty(splitValues[i].Trim('[', ']')); if (propertyValue == null) { return(false); } splitValues[i] = propertyValue; } } // Set the property switch (property.Type) { case PropertyType.String: onSetProperty(property.Name, property.Value); break; case PropertyType.Path: { var pathResult = ""; foreach (var path in splitValues) { pathResult = Path.Combine(pathResult, path); } onSetProperty(property.Name, pathResult); } break; case PropertyType.FileExists: { var expandedPath = Environment.ExpandEnvironmentVariables(splitValues[0]); var exists = File.Exists(expandedPath); onSetProperty(property.Name, exists.ToString()); } break; case PropertyType.DirectoryExists: { var expandedPath = Environment.ExpandEnvironmentVariables(splitValues[0]); var exists = Directory.Exists(expandedPath); onSetProperty(property.Name, exists.ToString()); } break; } } return(true); }
public static ObjectId CreateStairPropertySetDefinition(string psdName) { ObjectId psdId; Database db = Application.DocumentManager.MdiActiveDocument.Database; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager; DictionaryPropertySetDefinitions dict = new DictionaryPropertySetDefinitions(db); // Check for existing propert set definition ... If so just return its ObjectId. psdId = GetPropertySetDefinitionIdByName(psdName); if (psdId != ObjectId.Null) { ed.WriteMessage("\n Property set definition {0} exist", psdName); return(psdId); // check version and correctness not implemented } else { // Create the new property set definition; PropertySetDefinition psd = new PropertySetDefinition(); psd.SetToStandard(db); psd.SubSetDatabaseDefaults(db); psd.AlternateName = psdName; psd.IsLocked = true; psd.IsVisible = false; psd.IsWriteable = true; // Setup an array of objects that this property set definition will apply to System.Collections.Specialized.StringCollection appliesto = new System.Collections.Specialized.StringCollection { "AcDb3dSolid" }; psd.SetAppliesToFilter(appliesto, false); // Add the property set definition to the dictionary to make formula property work correctly using (Transaction tr = tm.StartTransaction()) { dict.AddNewRecord(psdName, psd); tr.AddNewlyCreatedDBObject(psd, true); // Invisible Properties (managed by app) PropertyDefinition def; def = new PropertyDefinition(); def.SetToStandard(db); def.SubSetDatabaseDefaults(db); def.Name = "_tread"; def.DataType = Autodesk.Aec.PropertyData.DataType.Real; def.DefaultData = 0.32; def.IsVisible = false; psd.Definitions.Add(def); def = new PropertyDefinition(); def.SetToStandard(db); def.SubSetDatabaseDefaults(db); def.Name = "_riser"; def.DataType = Autodesk.Aec.PropertyData.DataType.Real; def.DefaultData = 0.15; def.IsVisible = false; psd.Definitions.Add(def); def = new PropertyDefinition(); def.SetToStandard(db); def.SubSetDatabaseDefaults(db); def.Name = "_landing"; def.DataType = Autodesk.Aec.PropertyData.DataType.Real; def.DefaultData = 1.1; def.IsVisible = false; psd.Definitions.Add(def); def = new PropertyDefinition(); def.SetToStandard(db); def.SubSetDatabaseDefaults(db); def.Name = "_width"; def.DataType = Autodesk.Aec.PropertyData.DataType.Real; def.DefaultData = 2.00; def.IsVisible = false; psd.Definitions.Add(def); def = new PropertyDefinition(); def.SetToStandard(db); def.SubSetDatabaseDefaults(db); def.Name = "_slope"; def.DataType = Autodesk.Aec.PropertyData.DataType.Real; def.DefaultData = 0.02; def.IsVisible = false; psd.Definitions.Add(def); def = new PropertyDefinition(); def.SetToStandard(db); def.SubSetDatabaseDefaults(db); def.Name = "_steps"; def.DataType = Autodesk.Aec.PropertyData.DataType.Integer; def.DefaultData = 5; def.IsVisible = false; psd.Definitions.Add(def); // Visable properties (exposed to user) def = new PropertyDefinition(); def.SetToStandard(db); def.SubSetDatabaseDefaults(db); def.Name = "name"; def.DataType = Autodesk.Aec.PropertyData.DataType.Text; def.DefaultData = "Stair - "; def.IsVisible = true; psd.Definitions.Add(def); // Visable read only properties (exposed to user) PropertyDefinitionFormula formula; // Property definition need to be added to the property set definition before setting formula string to the formula property // steps formula = new PropertyDefinitionFormula(); formula.SetToStandard(db); formula.SubSetDatabaseDefaults(db); formula.Name = "steps"; psd.Definitions.Add(formula); formula.SetFormulaString("[_steps]"); // riser formula = new PropertyDefinitionFormula(); formula.SetToStandard(db); formula.SubSetDatabaseDefaults(db); formula.Name = "riser"; psd.Definitions.Add(formula); formula.SetFormulaString("[_riser]"); // tread formula = new PropertyDefinitionFormula(); formula.SetToStandard(db); formula.SubSetDatabaseDefaults(db); formula.Name = "tread"; psd.Definitions.Add(formula); formula.SetFormulaString("[_tread]"); // landing formula = new PropertyDefinitionFormula(); formula.SetToStandard(db); formula.SubSetDatabaseDefaults(db); formula.Name = "landing"; psd.Definitions.Add(formula); formula.SetFormulaString("[_landing]"); // width formula = new PropertyDefinitionFormula(); formula.SetToStandard(db); formula.SubSetDatabaseDefaults(db); formula.Name = "width"; psd.Definitions.Add(formula); formula.SetFormulaString("[_width]"); // slope formula = new PropertyDefinitionFormula(); formula.SetToStandard(db); formula.SubSetDatabaseDefaults(db); formula.Name = "slope"; psd.Definitions.Add(formula); formula.SetFormulaString("[_slope]"); tr.Commit(); psdId = psd.ObjectId; return(psdId); } } }
private static ScheduleTableStyleColumn CreateColumn(PropertyClassData nodeData, PropertySetDefinition psd, ScheduleTableStyle style) { Database db = ScheduleSample.GetDatabase(); ScheduleTableStyleColumn column = new ScheduleTableStyleColumn(); column.SetToStandard(db); column.SubSetDatabaseDefaults(db); column.PropertySetDefinitionId = psd.Id; column.ColumnType = ScheduleTableStyleColumnType.Normal; column.Heading = nodeData.DisplayName; column.PropertyId = psd.Definitions.IndexOf(nodeData.PropertyName); return(column); }
private static List <ScheduleTableStyleHeaderNode> CreateChildNodes(List <ColumnHeaderNode> childNodes, ScheduleTableStyleHeaderTree tree, PropertySetDefinition psd, ScheduleTableStyle style) { Database db = ScheduleSample.GetDatabase(); List <ScheduleTableStyleHeaderNode> nodesCreated = new List <ScheduleTableStyleHeaderNode>(); foreach (ColumnHeaderNode childNode in childNodes) { if (childNode.IsColumn) { PropertyClassData data = childNode.ColumnData; ScheduleTableStyleColumn column = CreateColumn(data, psd, style); style.Columns.Add(column); nodesCreated.Add(column); } else if (childNode.IsHeader) { string headerName = childNode.NodeData as string; List <ScheduleTableStyleHeaderNode> myChildren = CreateChildNodes(childNode.Children, tree, psd, style); ScheduleTableStyleHeaderNode header = tree.InsertNode(headerName, tree.Root.Children.Count, tree.Root, myChildren.ToArray()); nodesCreated.Add(header); } else { throw new ArgumentException("Cannot resolve node type properly when creating schedule table style."); } } return(nodesCreated); }
public static void CreateLerData(Database db, FeatureCollection fc) { string pathLag = "X:\\AutoCAD DRI - 01 Civil 3D\\Lag-Ler2.0.csv"; System.Data.DataTable dtLag = CsvReader.ReadCsvToDataTable(pathLag, "Lag"); if (dtLag == null) { throw new System.Exception("Lag file could not be read!"); } HashSet <UtilityOwner> ownersRegister = new HashSet <UtilityOwner>(); HashSet <LedningType> ledninger = new HashSet <LedningType>(); HashSet <LedningstraceType> ledningstrace = new HashSet <LedningstraceType>(); HashSet <LedningskomponentType> ledningskomponenter = new HashSet <LedningskomponentType>(); #region Redirect objects to collections //Redirect objects to collections //int i = 0; foreach (FeatureMember fm in fc.featureCollection) { //i++; prdDbg($"Switching item {i}."); System.Windows.Forms.Application.DoEvents(); switch (fm.item) { case UtilityOwner uo: ownersRegister.Add(uo); break; case Graveforesp gvfsp: break; case UtilityPackageInfo upi: break; case Kontaktprofil kp: break; case Informationsressource ir: break; case LedningType lt: ledninger.Add(lt); //prdDbg(lt.gmlid); break; case LedningstraceType ltr: ledningstrace.Add(ltr); //prdDbg(ltr.gmlid); break; case LedningskomponentType lk: ledningskomponenter.Add(lk); //prdDbg(lk.gmlid); break; default: prdDbg(fm.item.GMLTypeID); throw new System.Exception($"Unexpected type encountered {fm.item.GetType().Name}!"); } } #endregion #region Populate Company Name //Populate Company Name foreach (LedningType ledning in ledninger) { var owner = ownersRegister.FirstOrDefault(x => x.ledningsejer == ledning.ledningsejer); //if (owner == default) throw new System.Exception($"Ledning {ledning.id} kan ikke finde ejer!"); if (owner == default) { prdDbg($"Ledning {ledning.id} kan ikke finde ejer!"); } else { ledning.LedningsEjersNavn = owner.companyName; } } foreach (LedningstraceType trace in ledningstrace) { var owner = ownersRegister.FirstOrDefault(x => x.ledningsejer == trace.ledningsejer); //if (owner == default) throw new System.Exception($"Ledning {trace.id} kan ikke finde ejer!"); if (owner == default) { prdDbg($"Ledning {trace.id} kan ikke finde ejer!"); } else { trace.LedningsEjersNavn = owner.companyName; } } foreach (LedningskomponentType komp in ledningskomponenter) { var owner = ownersRegister.FirstOrDefault(x => x.ledningsejer == komp.ledningsejer); //if (owner == default) throw new System.Exception($"Ledning {komp.id} kan ikke finde ejer!"); if (owner == default) { prdDbg($"Ledning {komp.id} kan ikke finde ejer!"); } else { komp.LedningsEjersNavn = owner.companyName; } } #endregion #region Create property sets //Dictionary to translate between type name and psName Dictionary <string, string> psDict = new Dictionary <string, string>(); //Create property sets HashSet <Type> allUniqueTypes = ledninger.Select(x => x.GetType()).Distinct().ToHashSet(); allUniqueTypes.UnionWith(ledningstrace.Select(x => x.GetType()).Distinct().ToHashSet()); allUniqueTypes.UnionWith(ledningskomponenter.Select(x => x.GetType()).Distinct().ToHashSet()); foreach (Type type in allUniqueTypes) { string psName = type.Name.Replace("Type", ""); //Store the ps name in dictionary referenced by the type name //PS name is not goood! It becomes Elledning which is not unique //But it is unique!! //Data with different files will still follow the class definition in code //Which assures that all pssets are the same psDict.Add(type.Name, psName); PropertySetDefinition propSetDef = new PropertySetDefinition(); propSetDef.SetToStandard(db); propSetDef.SubSetDatabaseDefaults(db); propSetDef.Description = type.FullName; bool isStyle = false; var appliedTo = new StringCollection() { RXClass.GetClass(typeof(Polyline)).Name, RXClass.GetClass(typeof(Polyline3d)).Name, RXClass.GetClass(typeof(DBPoint)).Name, RXClass.GetClass(typeof(Hatch)).Name, }; propSetDef.SetAppliesToFilter(appliedTo, isStyle); var properties = type.GetProperties(); foreach (PropertyInfo prop in properties) { bool include = prop.CustomAttributes.Any(x => x.AttributeType == typeof(Schema.PsInclude)); if (include) { var propDefManual = new PropertyDefinition(); propDefManual.SetToStandard(db); propDefManual.SubSetDatabaseDefaults(db); propDefManual.Name = prop.Name; propDefManual.Description = prop.Name; switch (prop.PropertyType.Name) { case nameof(String): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Text; propDefManual.DefaultData = ""; break; case nameof(System.Boolean): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.TrueFalse; propDefManual.DefaultData = false; break; case nameof(Double): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Real; propDefManual.DefaultData = 0.0; break; case nameof(Int32): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Integer; propDefManual.DefaultData = 0; break; default: propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Text; propDefManual.DefaultData = ""; break; } propSetDef.Definitions.Add(propDefManual); } } using (Transaction tx = db.TransactionManager.StartTransaction()) { //check if prop set already exists DictionaryPropertySetDefinitions dictPropSetDef = new DictionaryPropertySetDefinitions(db); if (dictPropSetDef.Has(psName, tx)) { tx.Abort(); continue; } dictPropSetDef.AddNewRecord(psName, propSetDef); tx.AddNewlyCreatedDBObject(propSetDef, true); tx.Commit(); } } #endregion #region Create elements //List of all (new) layers of new entities HashSet <string> layerNames = new HashSet <string>(); foreach (LedningType ledning in ledninger) { string psName = psDict[ledning.GetType().Name]; ILerLedning iLedning = ledning as ILerLedning; if (iLedning == null) { throw new System.Exception($"Ledning {ledning.id} har ikke implementeret ILerLedning!"); } ObjectId entityId = iLedning.DrawEntity2D(db); Entity ent = entityId.Go <Entity>(db.TransactionManager.TopTransaction, OpenMode.ForWrite); layerNames.Add(ent.Layer); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(db, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(ledning); PropertySetManager.PopulateNonDefinedPropertySet(db, ent, psName, psData); } foreach (LedningstraceType trace in ledningstrace) { string psName = psDict[trace.GetType().Name]; ILerLedning ledning = trace as ILerLedning; if (ledning == null) { throw new System.Exception($"Trace {trace.id} har ikke implementeret ILerLedning!"); } ObjectId entityId = ledning.DrawEntity2D(db); Entity ent = entityId.Go <Entity>(db.TransactionManager.TopTransaction, OpenMode.ForWrite); layerNames.Add(ent.Layer); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(db, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(trace); PropertySetManager.PopulateNonDefinedPropertySet(db, ent, psName, psData); } foreach (LedningskomponentType komponent in ledningskomponenter) { string psName = psDict[komponent.GetType().Name]; ILerKomponent creator = komponent as ILerKomponent; if (creator == null) { throw new System.Exception($"Komponent {komponent.id} har ikke implementeret ILerKomponent!"); } Oid entityId = creator.DrawComponent(db); Entity ent = entityId.Go <Entity>(db.TransactionManager.TopTransaction, OpenMode.ForWrite); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(db, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(komponent); PropertySetManager.PopulateNonDefinedPropertySet(db, ent, psName, psData); } #endregion #region Read and assign layer's color //Cache layer table LayerTable ltable = db.LayerTableId.Go <LayerTable>(db.TransactionManager.TopTransaction); //Set up all LER layers foreach (string layerName in layerNames) { string colorString = ReadStringParameterFromDataTable(layerName, dtLag, "Farve", 0); Color color; if (colorString.IsNoE()) { Log.log($"Ledning with layer name {layerName} could not get a color!"); color = Color.FromColorIndex(ColorMethod.ByAci, 0); } else { color = ParseColorString(colorString); if (color == null) { Log.log($"Ledning layer name {layerName} could not parse colorString {colorString}!"); color = Color.FromColorIndex(ColorMethod.ByAci, 0); } } LayerTableRecord ltr = ltable[layerName] .Go <LayerTableRecord>(db.TransactionManager.TopTransaction, OpenMode.ForWrite); ltr.Color = color; } #endregion #region Read and assign layer's linetype LinetypeTable ltt = (LinetypeTable)db.TransactionManager.TopTransaction .GetObject(db.LinetypeTableId, OpenMode.ForWrite); //Check if all line types are present HashSet <string> missingLineTypes = new HashSet <string>(); foreach (string layerName in layerNames) { string lineTypeName = ReadStringParameterFromDataTable(layerName, dtLag, "LineType", 0); if (lineTypeName.IsNoE()) { continue; } else if (!ltt.Has(lineTypeName)) { missingLineTypes.Add(lineTypeName); } } if (missingLineTypes.Count > 0) { Database ltDb = new Database(false, true); ltDb.ReadDwgFile("X:\\AutoCAD DRI - 01 Civil 3D\\Projection_styles.dwg", FileOpenMode.OpenForReadAndAllShare, false, null); Transaction ltTx = ltDb.TransactionManager.StartTransaction(); Oid destDbMsId = SymbolUtilityServices.GetBlockModelSpaceId(db); LinetypeTable sourceLtt = (LinetypeTable)ltDb.TransactionManager.TopTransaction .GetObject(ltDb.LinetypeTableId, OpenMode.ForRead); ObjectIdCollection idsToClone = new ObjectIdCollection(); foreach (string missingName in missingLineTypes) { idsToClone.Add(sourceLtt[missingName]); } IdMapping mapping = new IdMapping(); ltDb.WblockCloneObjects(idsToClone, destDbMsId, mapping, DuplicateRecordCloning.Replace, false); ltTx.Commit(); ltTx.Dispose(); ltDb.Dispose(); } Oid lineTypeId; foreach (string layerName in layerNames) { string lineTypeName = ReadStringParameterFromDataTable(layerName, dtLag, "LineType", 0); if (lineTypeName.IsNoE()) { Log.log($"WARNING! Layer name {layerName} does not have a line type specified!."); //If linetype string is NoE -> CONTINUOUS linetype must be used lineTypeId = ltt["Continuous"]; } else { //the presence of the linetype is assured in previous foreach. lineTypeId = ltt[lineTypeName]; } LayerTableRecord ltr = ltable[layerName] .Go <LayerTableRecord>(db.TransactionManager.TopTransaction, OpenMode.ForWrite); ltr.LinetypeObjectId = lineTypeId; } #endregion }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Sets properties according to the provided definition. </summary> /// /// <param name="propertySetDefinition"> The property set definition. </param> /// <param name="onSetProperty"> The set property callback. </param> /// <param name="onGetProperty"> The get property callback. </param> /// /// <returns> true if it succeeds, false if it fails. </returns> public bool SetProperties(PropertySetDefinition propertySetDefinition, Action<string, string> onSetProperty, Func<string, string> onGetProperty) { // Set the properties foreach (var property in propertySetDefinition.Properties) { var splitValues = property.Value.Split(new char[] { ';' }); // Expand properties as needed for (int i = 0; i < splitValues.Length; ++i) { if (splitValues[i].StartsWith("[") && splitValues[i].EndsWith("]")) { var propertyValue = onGetProperty(splitValues[i].Trim('[', ']')); if(propertyValue == null) { return false; } splitValues[i] = propertyValue; } } // Set the property switch(property.Type) { case PropertyType.String: onSetProperty(property.Name, property.Value); break; case PropertyType.Path: { var pathResult = ""; foreach (var path in splitValues) { pathResult = Path.Combine(pathResult, path); } onSetProperty(property.Name, pathResult); } break; case PropertyType.FileExists: { var expandedPath = Environment.ExpandEnvironmentVariables(splitValues[0]); var exists = File.Exists(expandedPath); onSetProperty(property.Name, exists.ToString()); } break; case PropertyType.DirectoryExists: { var expandedPath = Environment.ExpandEnvironmentVariables(splitValues[0]); var exists = Directory.Exists(expandedPath); onSetProperty(property.Name, exists.ToString()); } break; } } return true; }
public void CreateLerData() { #region Catch no pipelines switch (this.type) { case GraveforespoergselssvartypeType.ingenledningerigraveområde: throw new System.Exception("INGEN ledninger i graveområde!"); case GraveforespoergselssvartypeType.ledningsoplysningerudleveresikke: throw new System.Exception("Leningsoplysninger udleveres ikke!"); case GraveforespoergselssvartypeType.ledningsoplysningerudleveret: break; case GraveforespoergselssvartypeType.udtagettilmanuelbehandling: break; case GraveforespoergselssvartypeType.udtagettilpåvisningledningsoplysningerudleveresikke: break; case GraveforespoergselssvartypeType.udtagettilpåvisningledningsoplysningerudleveret: break; default: break; } #endregion if (this.ledningMember == null) { this.ledningMember = new GraveforespoergselssvarTypeLedningMember[0]; } if (this.ledningstraceMember == null) { this.ledningstraceMember = new GraveforespoergselssvarTypeLedningstraceMember[0]; } if (this.ledningskomponentMember == null) { this.ledningskomponentMember = new GraveforespoergselssvarTypeLedningskomponentMember[0]; } Log.log($"Number of ledningMember -> {this.ledningMember?.Length.ToString()}"); Log.log($"Number of ledningstraceMember -> {this.ledningstraceMember?.Length.ToString()}"); Log.log($"Number of ledningskomponentMember -> {this.ledningskomponentMember?.Length.ToString()}"); #region Create property sets //Dictionary to translate between type name and psName Dictionary <string, string> psDict = new Dictionary <string, string>(); //Create property sets HashSet <Type> allUniqueTypes = ledningMember.Select(x => x.Item.GetType()).Distinct().ToHashSet(); allUniqueTypes.UnionWith(ledningstraceMember.Select(x => x.Ledningstrace.GetType()).Distinct().ToHashSet()); allUniqueTypes.UnionWith(ledningskomponentMember.Select(x => x.Item.GetType()).Distinct().ToHashSet()); foreach (Type type in allUniqueTypes) { string psName = type.Name.Replace("Type", ""); //Store the ps name in dictionary referenced by the type name //PS name is not goood! It becomes Elledning which is not unique //But it is unique!! //Data with different files will still follow the class definition in code //Which assures that all pssets are the same psDict.Add(type.Name, psName); PropertySetDefinition propSetDef = new PropertySetDefinition(); propSetDef.SetToStandard(WorkingDatabase); propSetDef.SubSetDatabaseDefaults(WorkingDatabase); propSetDef.Description = type.FullName; bool isStyle = false; var appliedTo = new StringCollection() { RXClass.GetClass(typeof(Polyline)).Name, RXClass.GetClass(typeof(Polyline3d)).Name, RXClass.GetClass(typeof(DBPoint)).Name, RXClass.GetClass(typeof(Hatch)).Name, }; propSetDef.SetAppliesToFilter(appliedTo, isStyle); var properties = type.GetProperties(); foreach (PropertyInfo prop in properties) { bool include = prop.CustomAttributes.Any(x => x.AttributeType == typeof(Schema.PsInclude)); if (include) { var propDefManual = new PropertyDefinition(); propDefManual.SetToStandard(WorkingDatabase); propDefManual.SubSetDatabaseDefaults(WorkingDatabase); propDefManual.Name = prop.Name; propDefManual.Description = prop.Name; switch (prop.PropertyType.Name) { case nameof(String): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Text; propDefManual.DefaultData = ""; break; case nameof(Boolean): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.TrueFalse; propDefManual.DefaultData = false; break; case nameof(Double): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Real; propDefManual.DefaultData = 0.0; break; case nameof(Int32): propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Integer; propDefManual.DefaultData = 0; break; default: propDefManual.DataType = Autodesk.Aec.PropertyData.DataType.Text; propDefManual.DefaultData = ""; break; } propSetDef.Definitions.Add(propDefManual); } } using (Transaction tx = WorkingDatabase.TransactionManager.StartTransaction()) { //check if prop set already exists DictionaryPropertySetDefinitions dictPropSetDef = new DictionaryPropertySetDefinitions(WorkingDatabase); if (dictPropSetDef.Has(psName, tx)) { tx.Abort(); continue; } dictPropSetDef.AddNewRecord(psName, propSetDef); tx.AddNewlyCreatedDBObject(propSetDef, true); tx.Commit(); } } #endregion //Debug list of all types in collections HashSet <string> names = new HashSet <string>(); //List of all (new) layers of new entities HashSet <string> layerNames = new HashSet <string>(); foreach (GraveforespoergselssvarTypeLedningMember member in ledningMember) { if (member.Item == null) { Log.log($"ledningMember is null! Some enity has not been deserialized correct!"); continue; } string psName = psDict[member.Item.GetType().Name]; ILerLedning ledning = member.Item as ILerLedning; Oid entityId = ledning.DrawEntity2D(WorkingDatabase); Entity ent = entityId.Go <Entity>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); layerNames.Add(ent.Layer); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(WorkingDatabase, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(member.Item); PropertySetManager.PopulateNonDefinedPropertySet(WorkingDatabase, ent, psName, psData); //names.Add(member.Item.ToString()); } foreach (GraveforespoergselssvarTypeLedningstraceMember member in ledningstraceMember) { if (member.Ledningstrace == null) { Log.log($"ledningstraceMember is null! Some enity has not been deserialized correct!"); continue; } string psName = psDict[member.Ledningstrace.GetType().Name]; ILerLedning ledning = member.Ledningstrace as ILerLedning; Oid entityId = ledning.DrawEntity2D(WorkingDatabase); Entity ent = entityId.Go <Entity>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); layerNames.Add(ent.Layer); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(WorkingDatabase, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(member.Ledningstrace); PropertySetManager.PopulateNonDefinedPropertySet(WorkingDatabase, ent, psName, psData); //names.Add(item.Ledningstrace.ToString()); //prdDbg(ObjectDumper.Dump(item.Ledningstrace)); } foreach (GraveforespoergselssvarTypeLedningskomponentMember member in ledningskomponentMember) { if (member.Item == null) { Log.log($"ledningskomponentMember is null! Some enity has not been deserialized correct!"); continue; } string psName = psDict[member.Item.GetType().Name]; ILerKomponent creator = member.Item as ILerKomponent; Oid entityId = creator.DrawComponent(WorkingDatabase); Entity ent = entityId.Go <Entity>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); //Layer names are not analyzed for components currently //layerNames.Add(ent.Layer); //Attach the property set PropertySetManager.AttachNonDefinedPropertySet(WorkingDatabase, ent, psName); //Populate the property set var psData = GmlToPropertySet.TranslateGmlToPs(member.Item); PropertySetManager.PopulateNonDefinedPropertySet(WorkingDatabase, ent, psName, psData); //names.Add(member.Item.ToString()); } foreach (string name in names) { prdDbg(name); } #region Read and assign layer's color //Regex to parse the color information Regex colorRegex = new Regex(@"^(?<R>\d+)\*(?<G>\d+)\*(?<B>\d+)"); //Cache layer table LayerTable lt = WorkingDatabase.LayerTableId.Go <LayerTable>(WorkingDatabase.TransactionManager.TopTransaction); //Set up all LER layers foreach (string layerName in layerNames) { string colorString = ReadStringParameterFromDataTable(layerName, DtKrydsninger, "Farve", 0); Color color; if (colorString.IsNoE()) { Log.log($"Ledning with layer name {layerName} could not get a color!"); color = Color.FromColorIndex(ColorMethod.ByAci, 0); } else if (colorRegex.IsMatch(colorString)) { Match match = colorRegex.Match(colorString); byte R = Convert.ToByte(int.Parse(match.Groups["R"].Value)); byte G = Convert.ToByte(int.Parse(match.Groups["G"].Value)); byte B = Convert.ToByte(int.Parse(match.Groups["B"].Value)); //prdDbg($"Set layer {name} to color: R: {R.ToString()}, G: {G.ToString()}, B: {B.ToString()}"); color = Color.FromRgb(R, G, B); } else { Log.log($"Ledning layer name {layerName} could not parse colorString {colorString}!"); color = Color.FromColorIndex(ColorMethod.ByAci, 0); } LayerTableRecord ltr = lt[layerName] .Go <LayerTableRecord>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); ltr.Color = color; } #endregion #region Read and assign layer's linetype LinetypeTable ltt = (LinetypeTable)WorkingDatabase.TransactionManager.TopTransaction .GetObject(WorkingDatabase.LinetypeTableId, OpenMode.ForWrite); //Check if all line types are present HashSet <string> missingLineTypes = new HashSet <string>(); foreach (string layerName in layerNames) { string lineTypeName = ReadStringParameterFromDataTable(layerName, DtKrydsninger, "LineType", 0); if (lineTypeName.IsNoE()) { continue; } else if (!ltt.Has(lineTypeName)) { missingLineTypes.Add(lineTypeName); } } if (missingLineTypes.Count > 0) { Database ltDb = new Database(false, true); ltDb.ReadDwgFile("X:\\AutoCAD DRI - 01 Civil 3D\\Projection_styles.dwg", FileOpenMode.OpenForReadAndAllShare, false, null); Transaction ltTx = ltDb.TransactionManager.StartTransaction(); Oid destDbMsId = SymbolUtilityServices.GetBlockModelSpaceId(WorkingDatabase); LinetypeTable sourceLtt = (LinetypeTable)ltDb.TransactionManager.TopTransaction .GetObject(ltDb.LinetypeTableId, OpenMode.ForRead); ObjectIdCollection idsToClone = new ObjectIdCollection(); foreach (string missingName in missingLineTypes) { idsToClone.Add(sourceLtt[missingName]); } IdMapping mapping = new IdMapping(); ltDb.WblockCloneObjects(idsToClone, destDbMsId, mapping, DuplicateRecordCloning.Replace, false); ltTx.Commit(); ltTx.Dispose(); ltDb.Dispose(); } Oid lineTypeId; foreach (string layerName in layerNames) { string lineTypeName = ReadStringParameterFromDataTable(layerName, DtKrydsninger, "LineType", 0); if (lineTypeName.IsNoE()) { Log.log($"WARNING! Layer name {layerName} does not have a line type specified!."); //If linetype string is NoE -> CONTINUOUS linetype must be used lineTypeId = ltt["Continuous"]; } else { //the presence of the linetype is assured in previous foreach. lineTypeId = ltt[lineTypeName]; } LayerTableRecord ltr = lt[layerName] .Go <LayerTableRecord>(WorkingDatabase.TransactionManager.TopTransaction, OpenMode.ForWrite); ltr.LinetypeObjectId = lineTypeId; } #endregion }
//Loops through all ODTables in document and creates corresponding PropertySetDefinitions public static void oddatacreatepropertysetsdefs() { DocumentCollection docCol = Application.DocumentManager; Database localDb = docCol.MdiActiveDocument.Database; Editor ed = docCol.MdiActiveDocument.Editor; Document doc = docCol.MdiActiveDocument; CivilDocument civilDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument; //Reference ODTables Tables tables = HostMapApplicationServices.Application.ActiveProject.ODTables; StringCollection tableNames = tables.GetTableNames(); foreach (string name in tableNames) { Table curTable = tables[name]; try { // (1) create prop set def PropertySetDefinition propSetDef = new PropertySetDefinition(); propSetDef.SetToStandard(localDb); propSetDef.SubSetDatabaseDefaults(localDb); // alternatively, you can use dictionary's NewEntry // Dim dictPropSetDef = New DictionaryPropertySetDefinitions(db) // Dim propSetDef As PropertySetDefinition = // dictPropSetDef.NewEntry() // General tab propSetDef.Description = name; // Applies To tab // apply to objects or styles. True if style, False if objects bool isStyle = false; var appliedTo = new StringCollection(); appliedTo.Add("AcDbLine"); appliedTo.Add("AcDbSpline"); appliedTo.Add("AcDbPolyline"); appliedTo.Add("AcDb3dPolyline"); appliedTo.Add(RXClass.GetClass(typeof(BlockReference)).Name); appliedTo.Add(RXClass.GetClass(typeof(DBPoint)).Name); propSetDef.SetAppliesToFilter(appliedTo, isStyle); FieldDefinitions defs = curTable.FieldDefinitions; int defsCount = defs.Count; for (int i = 0; i < defsCount; i++) { FieldDefinition curFd = defs[i]; string fieldDefName = curFd.Name; string fieldDefDescription = curFd.Description; DataType fieldType = curFd.Type; // Definition tab // (2) we can add a set of property definitions. // We first make a container to hold them. // This is the main part. A property set definition can contain // a set of property definition. // (2.1) let's first add manual property. // Here we use text type var propDefManual = new PropertyDefinition(); propDefManual.SetToStandard(localDb); propDefManual.SubSetDatabaseDefaults(localDb); propDefManual.Name = fieldDefName; propDefManual.Description = fieldDefDescription; propDefManual.DataType = GetCorrespondingPropertyDataType(fieldType); propDefManual.DefaultData = ConvertDefaultValue(curFd); // add to the prop set def propSetDef.Definitions.Add(propDefManual); } using (Transaction tx = localDb.TransactionManager.StartTransaction()) { //check if prop set already exists var dictPropSetDef = new DictionaryPropertySetDefinitions(localDb); if (dictPropSetDef.Has(name, tx)) { ed.WriteMessage("\nError - the property set defintion already exists: " + name); tx.Abort(); continue; } dictPropSetDef.AddNewRecord(name, propSetDef); tx.AddNewlyCreatedDBObject(propSetDef, true); tx.Commit(); } } catch (System.Exception ex) { ed.WriteMessage("\nError while creating Property Set definitions: " + ex.ToString()); return; } } ed.WriteMessage("\nFinished!"); }