Пример #1
0
        public override bool WorldDraw(
            Autodesk.AutoCAD.GraphicsInterface.Drawable drawable,
            Autodesk.AutoCAD.GraphicsInterface.WorldDraw wd)
        {
            base.WorldDraw(drawable, wd);

            Polyline pline = (Polyline)drawable;

            double length = pline.Length;

            #region Size label
            double  dist = length / 2;
            Point3d pt   = pline.GetPointAtDist(dist);
            int     dn   = PropertySetManager.ReadNonDefinedPropertySetInt(pline, "DriGasDimOgMat", "Dimension");
            string  mat  = PropertySetManager.ReadNonDefinedPropertySetString(pline, "DriGasDimOgMat", "Material");

            if (mat.IsNoE() && dn == 0)
            {
                return(true);
            }
            if (!mat.IsNoE())
            {
                mat = " " + mat;
            }

            string label = $"{dn}{mat}";

            if (
                pline.Layer == "GAS-ude af drift" ||
                pline.Layer == "GAS-ude af drift-2D"
                )
            {
                label += " UAD";
            }

            Vector3d deriv = pline.GetFirstDerivative(pt);
            deriv = deriv.GetNormal();

            Vector3d perp = deriv.GetPerpendicularVector();

            wd.Geometry.Text(
                pt + perp * labelOffset, Vector3d.ZAxis, deriv, label, true, style);
            //pt + perp * labelOffset, Vector3d.ZAxis, deriv, labelHeight, 1.0, 0.0, label);

            //wd.Geometry.Text(
            //    pt + perp * labelOffset, Vector3d.ZAxis, deriv, labelHeight, 1.0, 0.0, label);
            #endregion


            return(true);
        }
Пример #2
0
        public static void labelpipe()
        {
            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;

            using (DocumentLock docLock = doc.LockDocument())
                using (Transaction tx = localDb.TransactionManager.StartTransaction())
                {
                    try
                    {
                        PromptEntityOptions promptEntityOptions1 = new PromptEntityOptions(
                            "\nSelect pipe (polyline) to label: ");
                        promptEntityOptions1.SetRejectMessage("\nNot a polyline!");
                        promptEntityOptions1.AddAllowedClass(typeof(Polyline), false);
                        PromptEntityResult entity1 = ed.GetEntity(promptEntityOptions1);
                        if (((PromptResult)entity1).Status != PromptStatus.OK)
                        {
                            tx.Abort(); return;
                        }
                        Oid    plineId = entity1.ObjectId;
                        Entity ent     = plineId.Go <Entity>(tx);

                        string labelText = PipeSchedule.GetLabel(ent);

                        PromptPointOptions pPtOpts       = new PromptPointOptions("\nChoose location of label: ");
                        PromptPointResult  pPtRes        = ed.GetPoint(pPtOpts);
                        Point3d            selectedPoint = pPtRes.Value;
                        if (pPtRes.Status != PromptStatus.OK)
                        {
                            tx.Abort(); return;
                        }

                        //Create new text
                        string     layerName = "FJV-DIM";
                        LayerTable lt        = tx.GetObject(localDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                        if (!lt.Has(layerName))
                        {
                            LayerTableRecord ltr = new LayerTableRecord();
                            ltr.Name  = layerName;
                            ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 6);

                            lt.CheckOrOpenForWrite();
                            lt.Add(ltr);
                            tx.AddNewlyCreatedDBObject(ltr, true);
                        }

                        DBText label = new DBText();
                        label.Layer          = layerName;
                        label.TextString     = labelText;
                        label.Height         = 1.2;
                        label.HorizontalMode = TextHorizontalMode.TextMid;
                        label.VerticalMode   = TextVerticalMode.TextVerticalMid;
                        label.Position       = new Point3d(selectedPoint.X, selectedPoint.Y, 0);
                        label.AlignmentPoint = selectedPoint;

                        //Find rotation
                        Polyline pline        = (Polyline)ent;
                        Point3d  closestPoint = pline.GetClosestPointTo(selectedPoint, true);
                        Vector3d derivative   = pline.GetFirstDerivative(closestPoint);
                        double   rotation     = Math.Atan2(derivative.Y, derivative.X);
                        label.Rotation = rotation;

                        BlockTable       bt         = tx.GetObject(localDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                        BlockTableRecord modelSpace =
                            tx.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                        Oid labelId = modelSpace.AppendEntity(label);
                        tx.AddNewlyCreatedDBObject(label, true);
                        label.Draw();

                        System.Windows.Forms.Application.DoEvents();

                        //Enable flipping of label
                        const string         kwd1 = "Yes";
                        const string         kwd2 = "No";
                        PromptKeywordOptions pkos = new PromptKeywordOptions("\nFlip label? ");
                        pkos.Keywords.Add(kwd1);
                        pkos.Keywords.Add(kwd2);
                        pkos.AllowNone        = true;
                        pkos.Keywords.Default = kwd2;
                        PromptResult pkwdres = ed.GetKeywords(pkos);
                        string       result  = pkwdres.StringResult;

                        if (result == kwd1)
                        {
                            label.Rotation += Math.PI;
                        }

                        #region Attach id data
                        PropertySetManager          psm = new PropertySetManager(localDb, PSetDefs.DefinedSets.DriSourceReference);
                        PSetDefs.DriSourceReference driSourceReference = new PSetDefs.DriSourceReference();

                        psm.GetOrAttachPropertySet(label);
                        string handle = ent.Handle.ToString();
                        psm.WritePropertyString(driSourceReference.SourceEntityHandle, handle);
                        #endregion
                    }
                    catch (System.Exception ex)
                    {
                        tx.Abort();
                        ed.WriteMessage("\n" + ex.ToString());
                        return;
                    }
                    tx.Commit();
                }
        }
        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
        }
Пример #4
0
        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
        }
        public void exportareas()
        {
            DocumentCollection docCol  = Application.DocumentManager;
            Database           localDb = docCol.MdiActiveDocument.Database;
            Document           doc     = docCol.MdiActiveDocument;

            using (Transaction tx = localDb.TransactionManager.StartTransaction())
            {
                string logFileName = @"X:\AutoCAD DRI - QGIS\EGIS\Export\export.log";
                Log.LogFileName = logFileName;

                PropertySetManager  psm        = new PropertySetManager(localDb, PSetDefs.DefinedSets.DriOmråder);
                PSetDefs.DriOmråder driOmråder = new PSetDefs.DriOmråder();

                try
                {
                    string fileName = localDb.OriginalFileName;

                    string baseDir   = @"X:\037-1178 - Gladsaxe udbygning - Dokumenter\01 Intern\04 Projektering\05 Optælling til TBL\";
                    string shapeName = "Områder";

                    Log.log($"Exporting to {baseDir}.");

                    #region Exporting (p)lines
                    HashSet <Polyline> pls = localDb.HashSetOfType <Polyline>(tx);

                    pls = pls.Where(pl => pl.Layer == "0-OMRÅDER-OK").ToHashSet();

                    Log.log($"{pls.Count} object(s) found for export.");

                    DbfFieldDesc[] dbfFields = new DbfFieldDesc[4];

                    dbfFields[0].FieldName   = "Vejnavn";
                    dbfFields[0].FieldType   = DbfFieldType.General;
                    dbfFields[0].FieldLength = 100;

                    dbfFields[1].FieldName   = "Vejklasse";
                    dbfFields[1].FieldType   = DbfFieldType.Number;
                    dbfFields[1].FieldLength = 10;

                    dbfFields[2].FieldName   = "Belaegning";
                    dbfFields[2].FieldType   = DbfFieldType.General;
                    dbfFields[2].FieldLength = 100;

                    dbfFields[3].FieldName   = "Nummer";
                    dbfFields[3].FieldType   = DbfFieldType.General;
                    dbfFields[3].FieldLength = 100;



                    using (ShapeFileWriter writer = ShapeFileWriter.CreateWriter(
                               baseDir, shapeName,
                               ShapeType.PolyLine, dbfFields,
                               EGIS.Projections.CoordinateReferenceSystemFactory.Default.GetCRSById(25832)
                               .GetWKT(EGIS.Projections.PJ_WKT_TYPE.PJ_WKT1_GDAL, false)))
                    {
                        foreach (Polyline pline in pls)
                        {
                            List <Point2d> points    = new List <Point2d>();
                            int            numOfVert = pline.NumberOfVertices - 1;
                            if (pline.Closed)
                            {
                                numOfVert++;
                            }
                            for (int i = 0; i < numOfVert; i++)
                            {
                                switch (pline.GetSegmentType(i))
                                {
                                case SegmentType.Line:
                                    LineSegment2d ls = pline.GetLineSegment2dAt(i);
                                    if (i == 0)
                                    {    //First iteration
                                        points.Add(ls.StartPoint);
                                    }
                                    points.Add(ls.EndPoint);
                                    break;

                                case SegmentType.Arc:
                                    CircularArc2d arc         = pline.GetArcSegment2dAt(i);
                                    double        sPar        = arc.GetParameterOf(arc.StartPoint);
                                    double        ePar        = arc.GetParameterOf(arc.EndPoint);
                                    double        length      = arc.GetLength(sPar, ePar);
                                    double        radians     = length / arc.Radius;
                                    int           nrOfSamples = (int)(radians / 0.04);
                                    if (nrOfSamples < 3)
                                    {
                                        if (i == 0)
                                        {
                                            points.Add(arc.StartPoint);
                                        }
                                        points.Add(arc.EndPoint);
                                    }
                                    else
                                    {
                                        Point2d[] samples = arc.GetSamplePoints(nrOfSamples);
                                        if (i != 0)
                                        {
                                            samples = samples.Skip(1).ToArray();
                                        }
                                        foreach (Point2d p2d in samples)
                                        {
                                            points.Add(p2d);
                                        }
                                    }
                                    break;

                                case SegmentType.Coincident:
                                case SegmentType.Point:
                                case SegmentType.Empty:
                                default:
                                    continue;
                                }
                            }

                            PointD[] shapePoints = points.Select(p => new PointD(p.X, p.Y)).ToArray();

                            string[] attributes = new string[4];

                            psm.GetOrAttachPropertySet(pline);

                            attributes[0] = psm.ReadPropertyString(driOmråder.Vejnavn);
                            attributes[1] = psm.ReadPropertyString(driOmråder.Vejklasse);
                            attributes[2] = psm.ReadPropertyString(driOmråder.Belægning);
                            attributes[3] = psm.ReadPropertyString(driOmråder.Nummer);

                            writer.AddRecord(shapePoints, shapePoints.Length, attributes);
                        }
                    }

                    #endregion
                }
                catch (System.Exception ex)
                {
                    tx.Abort();
                    Log.log($"EXCEPTION!!!: {ex.ToString()}. Aborting export of current file!");
                    //editor.WriteMessage("\n" + ex.Message);
                    return;
                }
                tx.Abort();
            }
        }