Dxf Attribute definitions coping twice on adding it a target dwg from an external dwg

Sandeep Bhat
5/6/2022 12:47 PM

My requirement is to copy specific block along with its attributes from an external drawing to an existing drawing.

I have the below code. When I open the manage attributes in AutoCad I see all the definitions in red and being duplicated. I tried two ways, First is directly fetching the attributes from the DxfInsert. Second is to create a attribute definition and adding the attribute. Both have the same result. I constructed this code following many examples on this forum. Not sure where I have gone wrong here. Any help is appreciated!

C# Code:
                private void InsertSourceBlockInTargetModel(DxfModel sourceModel, DxfModel targetModel)

                    double positionX = 525;
                    double positionY = 375;
                    double positionZ = 0;

                    var cloneContext = new CloneContext(sourceModel, targetModel, ReferenceResolutionType.CloneMissing);

                    foreach (var sourceBlock in sourceModel.Blocks)
                        var clonedBlock = (DxfBlock)sourceBlock.Clone(cloneContext);

                        foreach (var blockEntity in sourceBlock.Entities)
                            var clonedEntity = (DxfEntity)blockEntity.Clone(cloneContext);


                        var sourceDxfInsert = (DxfInsert)FindBlockInsertions(this.sourceModel, sourceBlock);

                        var targetDxfInsert = new DxfInsert(clonedBlock, new Point3D(positionX, positionY, positionZ));

                        foreach (var attribute in sourceDxfInsert.Attributes)
                            //var attrDef = sourceBlock.GetAttributeDefinition(attribute.TagString);
                            //var attr = new DxfAttribute(attrDef);
                            var clonedAttribute = (DxfAttribute)attribute.Clone(cloneContext);




                    static DxfEntity FindBlockInsertions(DxfModel sourceModel, DxfBlock sourceBlock)
                        => ScanEntityCollectionForBlockInsertions(sourceModel.Entities, sourceBlock);

                    static DxfEntity ScanEntityCollectionForBlockInsertions(IEnumerable<DxfEntity> collection,
                                                                            DxfBlock block)
                        => collection.First(entity => entity is DxfInsert insert && insert.Block == block);

5/6/2022 2:22 PM


When you clone the block, its entities are already cloned. But then you clone the block's entities yourself, so this is problably the problem.

Also cloneContext.ResolveReferences() needs to be outside the foreach loop.

- Wout

Sandeep Bhat
5/10/2022 6:33 AM

Thanks for the hint. That worked!