本文转自网络,未经测试,留存备用!

http://blog.sina.com.cn/s/blog_49a9ee1401016843.html

By Adam Nagy

I would like to serialize my .NET class into an AutoCAD drawing database, so it is saved into the drawing, and I can recreate my class again (deserialize it), when the drawing is reopened. How could I do it?

Solution

You could use the .NET serialization technique to serialize your class into a binary stream and then you can save it in the drawing as a bunch of binary chunks. You could save the ResultBuffer to an object's XData or into an Xrecord.Data of an entity or an item in the Named Objects Dictionary (NOD). DevNote TS2563 tells you what the difference is between using XData and Xrecord. If you are saving it into an XData, then the ResultBuffer needs to start with a registered application name. Here is a sample which shows this:

  1 using System;
  2
  3 using System.Runtime.Serialization;
  4
  5 using System.Runtime.Serialization.Formatters.Binary;
  6
  7 using System.IO;
  8
  9 using System.Security.Permissions;
 10
 11
 12
 13 using Autodesk.AutoCAD.Runtime;
 14
 15 using acApp = Autodesk.AutoCAD.ApplicationServices.Application;
 16
 17 using Autodesk.AutoCAD.DatabaseServices;
 18
 19 using Autodesk.AutoCAD.EditorInput;
 20
 21
 22
 23 [assembly: CommandClass(typeof(MyClassSerializer.Commands))]
 24
 25
 26
 27 namespace MyClassSerializer
 28
 29 {
 30
 31  // We need it to help with deserialization
 32
 33
 34
 35  public sealed class MyBinder : SerializationBinder
 36
 37  {
 38
 39    public override System.Type BindToType(
 40
 41      string assemblyName,
 42
 43      string typeName)
 44
 45    {
 46
 47      return Type.GetType(string.Format("{0}, {1}",
 48
 49        typeName, assemblyName));
 50
 51    }
 52
 53  }
 54
 55
 56
 57  // Helper class to write to and from ResultBuffer
 58
 59
 60
 61  public class MyUtil
 62
 63  {
 64
 65    const int kMaxChunkSize = 127;
 66
 67
 68
 69    public static ResultBuffer StreamToResBuf(
 70
 71      MemoryStream ms, string appName)
 72
 73    {
 74
 75      ResultBuffer resBuf =
 76
 77        new ResultBuffer(
 78
 79          new TypedValue(
 80
 81            (int)DxfCode.ExtendedDataRegAppName, appName));
 82
 83
 84
 85      for (int i = 0; i < ms.Length; i += kMaxChunkSize)
 86
 87      {
 88
 89        int length = (int)Math.Min(ms.Length - i, kMaxChunkSize);
 90
 91        byte[] datachunk = new byte[length];
 92
 93        ms.Read(datachunk, 0, length);
 94
 95        resBuf.Add(
 96
 97          new TypedValue(
 98
 99            (int)DxfCode.ExtendedDataBinaryChunk, datachunk));
100
101      }
102
103
104
105      return resBuf;
106
107    }
108
109
110
111    public static MemoryStream ResBufToStream(ResultBuffer resBuf)
112
113    {
114
115      MemoryStream ms = new MemoryStream();
116
117      TypedValue[] values = resBuf.AsArray();
118
119
120
121      // Start from 1 to skip application name
122
123
124
125      for (int i = 1; i < values.Length; i++)
126
127      {
128
129        byte[] datachunk = (byte[])values[i].Value;
130
131        ms.Write(datachunk, 0, datachunk.Length);
132
133      }
134
135      ms.Position = 0;
136
137
138
139      return ms;
140
141    }
142
143  }
144
145
146
147  [Serializable]
148
149  public abstract class MyBaseClass : ISerializable
150
151  {
152
153    public const string appName = "MyApp";
154
155
156
157    public MyBaseClass()
158
159    {
160
161    }
162
163
164
165    public static object NewFromResBuf(ResultBuffer resBuf)
166
167    {
168
169      BinaryFormatter bf = new BinaryFormatter();
170
171      bf.Binder = new MyBinder();
172
173
174
175      MemoryStream ms = MyUtil.ResBufToStream(resBuf);
176
177
178
179      MyBaseClass mbc = (MyBaseClass)bf.Deserialize(ms);
180
181
182
183      return mbc;
184
185    }
186
187
188
189    public static object NewFromEntity(Entity ent)
190
191    {
192
193      using (
194
195        ResultBuffer resBuf = ent.GetXDataForApplication(appName))
196
197      {
198
199        return NewFromResBuf(resBuf);
200
201      }
202
203    }
204
205
206
207    public ResultBuffer SaveToResBuf()
208
209    {
210
211      BinaryFormatter bf = new BinaryFormatter();
212
213      MemoryStream ms = new MemoryStream();
214
215      bf.Serialize(ms, this);
216
217      ms.Position = 0;
218
219
220
221      ResultBuffer resBuf = MyUtil.StreamToResBuf(ms, appName);
222
223
224
225      return resBuf;
226
227    }
228
229
230
231    public void SaveToEntity(Entity ent)
232
233    {
234
235      // Make sure application name is registered
236
237      // If we were to save the ResultBuffer to an Xrecord.Data,
238
239      // then we would not need to have a registered application name
240
241
242
243      Transaction tr =
244
245        ent.Database.TransactionManager.TopTransaction;
246
247
248
249      RegAppTable regTable =
250
251        (RegAppTable)tr.GetObject(
252
253          ent.Database.RegAppTableId, OpenMode.ForWrite);
254
255      if (!regTable.Has(MyClass.appName))
256
257      {
258
259        RegAppTableRecord app = new RegAppTableRecord();
260
261        app.Name = MyClass.appName;
262
263        regTable.Add(app);
264
265        tr.AddNewlyCreatedDBObject(app, true);
266
267      }
268
269
270
271      using (ResultBuffer resBuf = SaveToResBuf())
272
273      {
274
275        ent.XData = resBuf;
276
277      }
278
279    }
280
281
282
283    [SecurityPermission(SecurityAction.LinkDemand,
284
285      Flags = SecurityPermissionFlag.SerializationFormatter)]
286
287    public abstract void GetObjectData(
288
289      SerializationInfo info, StreamingContext context);
290
291  }
292
293
294
295  [Serializable]
296
297  public class MyClass : MyBaseClass
298
299  {
300
301    public string myString;
302
303    public double myDouble;
304
305
306
307    public MyClass()
308
309    {
310
311    }
312
313
314
315    protected MyClass(
316
317      SerializationInfo info, StreamingContext context)
318
319    {
320
321      if (info == null)
322
323        throw new System.ArgumentNullException("info");
324
325
326
327      myString = (string)info.GetValue("MyString", typeof(string));
328
329      myDouble = (double)info.GetValue("MyDouble", typeof(double));
330
331    }
332
333
334
335    [SecurityPermission(SecurityAction.LinkDemand,
336
337      Flags = SecurityPermissionFlag.SerializationFormatter)]
338
339    public override void GetObjectData(
340
341      SerializationInfo info, StreamingContext context)
342
343    {
344
345      info.AddValue("MyString", myString);
346
347      info.AddValue("MyDouble", myDouble);
348
349    }
350
351
352
353    // Just for testing purposes
354
355
356
357    public override string ToString()
358
359    {
360
361      return base.ToString() + "," +
362
363        myString + "," + myDouble.ToString();
364
365    }
366
367  }
368
369
370
371  public class Commands
372
373  {
374
375    [CommandMethod("SaveClassToEntityXData")]
376
377    static public void SaveClassToEntityXData()
378
379    {
380
381      Database db = acApp.DocumentManager.MdiActiveDocument.Database;
382
383      Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;
384
385
386
387      PromptEntityResult per =
388
389        ed.GetEntity("Select entity to save class to:\n");
390
391      if (per.Status != PromptStatus.OK)
392
393        return;
394
395
396
397      // Create an object
398
399
400
401      MyClass mc = new MyClass();
402
403      mc.myDouble = 1.2345;
404
405      mc.myString = "Some text";
406
407
408
409      // Save it to the document
410
411
412
413      using (
414
415        Transaction tr = db.TransactionManager.StartTransaction())
416
417      {
418
419        Entity ent =
420
421          (Entity)tr.GetObject(per.ObjectId, OpenMode.ForWrite);
422
423
424
425        mc.SaveToEntity(ent);
426
427
428
429        tr.Commit();
430
431      }
432
433
434
435      // Write some info about the results
436
437
438
439      ed.WriteMessage(
440
441        "Content of MyClass we serialized:\n {0} \n", mc.ToString());
442
443    }
444
445
446
447    [CommandMethod("GetClassFromEntityXData")]
448
449    static public void GetClassFromEntityXData()
450
451    {
452
453      Database db = acApp.DocumentManager.MdiActiveDocument.Database;
454
455      Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;
456
457
458
459      PromptEntityResult per =
460
461        ed.GetEntity("Select entity to get class from:\n");
462
463      if (per.Status != PromptStatus.OK)
464
465        return;
466
467
468
469      // Get back the class
470
471
472
473      using (
474
475        Transaction tr = db.TransactionManager.StartTransaction())
476
477      {
478
479        Entity ent =
480
481          (Entity)tr.GetObject(per.ObjectId, OpenMode.ForRead);
482
483
484
485        MyClass mc = (MyClass)MyClass.NewFromEntity(ent);
486
487
488
489        // Write some info about the results
490
491
492
493        ed.WriteMessage(
494
495          "Content of MyClass we deserialized:\n {0} \n",
496
497          mc.ToString());
498
499
500
501        tr.Commit();
502
503      }
504
505    }
506
507  }
508
509 }

转载于:https://www.cnblogs.com/swtool/p/SWTOOL_00010.html

autocad.net将代码保存到图纸中,打开图纸后可以直接运行?相关推荐

  1. winform打开cad图纸_CAD打开图纸的方法汇总

    打开文件属于最基本的操作,大家都会,但每个人的习惯不一样,采用的方法也不完全相同,这里简单地将打开文件的各种方法汇总一下. 一.打开(OPEN)命令 这是最基本也是最常用的方法,但调用方法有很多种,可 ...

  2. idea整合jboos_在 idea 中 启动 jboss 后, 没有运行部署(通过idea部署)的ssm项目,打开后项目404...

    在 idea 中 启动 jboss 后, 没有运行部署(通过idea部署)的ssm项目,打开后项目404, 暂时的解决办法 每次启动 jboss 都需要是手动登录到 9999 管理端,添加部署 Cre ...

  3. centos桌面进入服务器,解决如何在centos7桌面中打开终端_网站服务器运行维护

    如何解决在Centos中NAT无法上网_网站服务器运行维护 在Centos中NAT无法上网的解决方法:首先将网络设置为"DHCP"自动获取IP:然后查看主机的相关服务是否开启:最后 ...

  4. Linux中打开谷歌浏览器后一直在转圈

    Linux可视化界面通过商店下载谷歌浏览器后,打开的时候在左上角一直转圈,打不开,过一会就没了 打开终端 [bb@aa ~]$ cd /opt/google/chrome/ #进入到google目录下 ...

  5. winform打开cad图纸_CAD打开文件后发现图纸显示不全怎么办?

    关注不迷路   1.每天持续更新CAD使用技巧和知识点! 2.想一起交流学习CAD的朋友们,可以加入 QQ群:421246724 3.学习资料和视频看群资料 最近有很多同学都有找我问这么一个问题,就是 ...

  6. Mac中安装git后,终端运行git出错,提示安装Xcode

    mac用户不使用Xcode安装git之后,默认安装路径是: /usr/local/git 但是在终端运行 git 命令时候的路径是: /usr/bin/git 当我们输入 git 命令时出现如下错误, ...

  7. xshell中打开vim后的颜色与colorscheme配置颜色不符合

    设置vim 256色彩显示 同时设置 xshell 256色彩显示 参考连接 http://blog.csdn.net/wide288/article/details/25072441 设置xshel ...

  8. 怎么使用CAD编辑器来打开图纸中的所有图层

    在CAD绘图中,建筑设计师们不仅要对CAD图纸进行编辑,还要对CAD图纸进行查看,一张图纸中是有许多图层的,那在查看的过程中有的时候把其他的图层进行隐藏了,那如果想要把隐藏的CAD图层进行打开要怎么操 ...

  9. 为什么在CAD图纸中插入外部参照后会出现多余图形?

    在使用浩辰CAD软件绘图的过程中,有些时候在CAD图纸中插入外部参照后图纸中就显示了一些不需要的图形:但是打开外部参照原图没有这些图形,插入到图纸后却显示出来了:这是什么原因呢?接下来以浩辰CAD软件 ...

  10. 浩辰CAD看图王中如何一键替换CAD图纸中大量相同的文字?

    在使用浩辰CAD制图软件绘制完成图纸后,在使用手机CAD快速看图软件浩辰CAD看图王中查看图纸的过程中,发现需要对CAD图纸中相同的文字进行修改,有什么办法可以批量修改呢? 此时就需要用到CAD快速看 ...

最新文章

  1. 60 Permutation Sequence
  2. 第四范式冲刺IPO:4年亏13亿收入逐年翻番,研发工资人均2万
  3. java AES加密
  4. Libra教程之:Libra testnet使用指南
  5. 一个基于 SpringBoot 开源的小说和漫画在线阅读网站,简洁大方 !强烈推荐 !
  6. deepin安装bochs2.6.2_深度Deepin系统中wine4.0.1源编辑安装
  7. Android:如何从堆栈中还原ProGuard混淆后的代码
  8. Python中对字符串进行Url加解密操作
  9. Color Table
  10. make_heap,pop_heap,push_heap
  11. 电脑文件同步备份软件哪个好用?
  12. python猜数字游戏实验报告_猜数字游戏实验报告
  13. 【Ubuntu】Ubuntu20.04安装GPU显卡驱动
  14. 【转】O'Reilly Java系列书籍建议阅读顺序(转自蔡学庸)
  15. 网络下载的图始终与北京坐标有偏移,坐标对不准,用arcgis自带的WGS84与beijing54坐标转换2解决
  16. 分享105个PHP源码,总有一款适合您
  17. oracle序列无缓存,oracle 序列跳号现象
  18. android 黑白棋源码,黑白棋源代码
  19. 简易集成的MVP模块化App框架(1/3)
  20. PDF格式转WORD要钱?Python几秒就能完成。

热门文章

  1. 程序员写代码时反复思考的问题
  2. apple pencil性价比高吗?适用ipad的电容笔推荐
  3. 这位阿里程序媛有点拼,爬8米高的锅炉,竟是为了这个!
  4. anaconda如何更新python_如何更新anaconda发行版和python包?
  5. [技术杂谈]几款常用的安装包制作工具
  6. hint: (e.g., ‘git pull ...‘) before pushing again. hint: See the ‘Note about fast-forwards‘ in ‘git
  7. Windwos密码导出的几种姿势
  8. java中日期比较方法,java中如何进行日期时间比较4种方法介绍
  9. Mate 10保时捷设计溢价再创新高超3倍价格秒杀iPhone X
  10. UWB定位系统在工业领域的重要作用