프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / APIDConverter / AutoModeling.cs @ dfb760ef

이력 | 보기 | 이력해설 | 다운로드 (41.6 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Collections;
4
using System.Configuration;
5
using System.Data;
6
using System.Data.Common;
7
using System.Data.SqlClient;
8
using System.IO;
9
using System.Runtime.CompilerServices;
10
using Microsoft.VisualBasic.CompilerServices;
11

    
12
using Autodesk.AutoCAD.ApplicationServices;
13
using Autodesk.AutoCAD.ApplicationServices.Core;
14
using Autodesk.AutoCAD.DatabaseServices;
15
using Autodesk.AutoCAD.EditorInput;
16
using Autodesk.AutoCAD.Geometry;
17
using Autodesk.AutoCAD.Interop;
18
using Autodesk.AutoCAD.Interop.Common;
19
using Autodesk.AutoCAD.Runtime;
20
using Autodesk.AutoCAD.Windows;
21

    
22
using AVEVA.PID.Components;
23
using AVEVA.PID.GUI;
24
using AVEVA.PID.Common;
25
using AVEVA.PID.DWGSelector;
26
using AVEVA.PID.Utilities;
27

    
28
using AVEVA.PID.CustomizationUtility.DB;
29
using AVEVA.PID.CustomizationUtility.Model;
30
using AVEVA.PID.CustomizationUtility.Properties;
31

    
32
using DevExpress.XtraSplashScreen;
33

    
34
namespace AVEVA.PID.CustomizationUtility
35
{
36
    public class AutoModeling
37
    {
38
        public static AutoModeling Running { get; set; }
39
        Model.Document document;
40
        AvevaInfo avevaInfo;
41

    
42
        private void SetConvertRule()
43
        {
44
            #region OPC Setting
45
            document.OPCs.Sort(SortOPC);
46
            int SortOPC(OPC a, OPC b)
47
            {
48
                if (a.FlowType == FlowType.In)
49
                    return 1;
50
                else
51
                    return 0;
52
            }
53
            #endregion
54
        }
55

    
56
        public AutoModeling(Model.Document document)
57
        {
58
            this.document = document;
59
            avevaInfo = AvevaInfo.GetInstance();
60
        }
61

    
62
        public void CreateDrawing()
63
        {
64
            string outPath = Project_DB.GetDirectiveValue("DRGPTH");
65
            string tempPath = Path.GetTempPath();
66
            string selectedFullPath = Path.Combine(tempPath, document.AvevaTemplateName + ".DWT");
67

    
68
            DWTSelector.strDrawingNumber = document.AvevaDrawingNumber;
69
            DWTSelector.strSheetNumber = document.AvevaSheetNumber;
70
            DWTSelector.strCadFileName = document.AvevaDrawingNumber + document.AvevaSheetNumber;
71
            DWTSelector.strCadFilePath = outPath;
72

    
73
            try
74
            {
75
                string text = ReadWriteDrawingData.ReadTemplateData(document.AvevaTemplateName, document.AvevaTemplateID, selectedFullPath, false);
76
                Autodesk.AutoCAD.Interop.AcadApplication acadApplication = Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication as Autodesk.AutoCAD.Interop.AcadApplication;
77
                Autodesk.AutoCAD.Interop.AcadDocument acadDocument = acadApplication.Documents.Add(text);
78

    
79
                Commands.addLatestPidvesrionToDictionary();
80
                AVVPropCmd.ActivateAcad();
81

    
82
                if (acadDocument != null)
83
                {
84
                    Running = this;
85
                    acadApplication.ActiveDocument = acadDocument;
86
                    acadDocument.SendCommand("QSAVE ");
87
                    acadDocument.SendCommand("APPIDRun ");
88
                    acadDocument.SendCommand("QSAVE ");
89
                    Running = null;
90
                }
91
            }
92
            catch (System.Exception ex)
93
            {
94
                
95
            }
96

    
97
            GC.Collect();
98
        }
99
        public void Run()
100
        {
101
            try
102
            {
103
                SplashScreenManager.ShowForm(typeof(APIDSplashScreen), true, true);
104
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllStepCount, 8);
105
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetDocumentName, document.AvevaDrawingNumber + document.AvevaSheetNumber);
106
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetParent, Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.Handle);
107

    
108
                SetConvertRule();
109

    
110
                RunLineModeling();
111
                RunOPCModeling();
112
                RunSymbolModeling();
113
                RunTextModeling();
114
                RunNoteModeling();
115
                RunInputLineAttribute();
116
                RunInputLineNumberAttribute();
117
                RunInputSymbolAttribute();
118
            }
119
            catch (System.Exception ex)
120
            {
121
                System.Windows.Forms.MessageBox.Show(ex.Message + @"\n" + ex.StackTrace);
122
            }
123
            finally
124
            {
125
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.ClearParent, null);
126
                SplashScreenManager.CloseForm(false);
127
            }
128
        }
129

    
130
        #region Run Method
131
        private void RunLineModeling()
132
        {
133
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
134
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling");
135
            foreach (var item in document.LINES)
136
            {
137
                if (item.Aveva.Handle == 0)
138
                    LineModeling(item);
139

    
140
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
141
            }
142
        }
143
        private void RunOPCModeling()
144
        {
145
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.OPCs.Count);
146
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "OPC Modeling");
147
            foreach (var item in document.OPCs)
148
            {
149
                if (item.Aveva.Handle == 0)
150
                    SymbolModeling(item);
151
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
152
            }
153
        }
154
        private void RunSymbolModeling()
155
        {
156
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
157
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
158
            foreach (var item in document.SYMBOLS)
159
            {
160
                if (item.Aveva.Handle == 0)
161
                    SymbolModeling(item);
162
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
163
            }
164
        }
165
        private void RunTextModeling()
166
        {
167
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Texts.Count);
168
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Text Modeling");
169
            foreach (var item in document.Texts)
170
            {
171
                TextModeling(item);
172
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
173
            }
174
        }
175
        private void RunNoteModeling()
176
        {
177
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Notes.Count);
178
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Note Modeling");
179
            foreach (var item in document.Notes)
180
            {
181
                NoteModeling(item);
182
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
183
            }
184
        }
185
        private void RunInputLineAttribute()
186
        {
187
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
188
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Input Line Attribute");
189
            foreach (var item in document.LINES)
190
            {
191
                SetLineAttribute(item);
192
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
193
            }
194
        }
195
        private void RunInputSymbolAttribute()
196
        {
197
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
198
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Input Symbol Attribute");
199
            foreach (var item in document.SYMBOLS)
200
            {
201
                SetSymbolAttribute(item);
202
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
203
            }
204
        }
205
        private void RunInputLineNumberAttribute()
206
        {
207
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
208
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Input LineNumber Attribute");
209
            foreach (var item in document.LINENUMBERS)
210
            {
211
                SetLineNumberAttribute(item);
212
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
213
            }
214
        }
215
        #endregion
216

    
217
        #region Modeling Method
218
        private void LineModeling(Model.Line line)
219
        {
220
            List<Model.Line> groupLine = new List<Model.Line>();
221
            List<string> points = new List<string>();
222
            GetConnectedGroupLine(line, groupLine, false);
223
            GetGroupLinePoints(groupLine, points);
224

    
225
            LineNumber lineNumber = null;
226
            if (line.Aveva.Type == Model.Type.Pipe)
227
            {
228
                foreach (var item in groupLine)
229
                {
230
                    lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == item.UID);
231
                    if (lineNumber != null)
232
                    {
233
                        GUIUtils.SetAutoLabelCheck(true);
234
                        break;
235
                    }
236
                }
237
            }
238

    
239

    
240
            long handle = 0;
241
            if (line.Aveva.Type == Model.Type.Pipe)
242
                handle = DrawPipe(line.Aveva.Name, points, lineNumber);
243
            else if (line.Aveva.Type == Model.Type.Signal)
244
                handle = DrawSignal(line.Aveva.Name, points);
245

    
246
            if (lineNumber != null)
247
                GUIUtils.SetAutoLabelCheck(false);
248

    
249
            foreach (var item in groupLine)
250
                item.Aveva.Handle = handle;
251
        }
252
        private void SymbolModeling(Symbol symbol)
253
        {
254
            DataRow[] allRows = avevaInfo.AvevaSymbolTable.Select(string.Format("Symbol_Name = '{0}'", symbol.Aveva.Name));
255
            if (allRows.Length == 1)
256
            {
257
                DataRow symbolRow = allRows[0];
258
                bool bAngle = CheckAngle(symbolRow);
259
                bool bBalloon = CheckBalloon(symbol);
260

    
261
                long handle = InsertSymbol(symbol, symbolRow, bAngle, bBalloon);
262
                if (handle != 0)
263
                {
264
                    symbol.Aveva.Handle = handle;
265

    
266
                    if (!bAngle)
267
                    {
268
                        ObjectId objectId = GetObjectIdByHandle(handle);
269
                        if (objectId != ObjectId.Null)
270
                        {
271
                            SetBlockReferenceRotation(objectId, symbol.ANGLE);
272
                        }
273
                    }
274
                }
275
            }
276
        }
277
        private void TextModeling(Text text)
278
        {
279
            if (text.TextAngle == TextAngle.None)
280
                return;
281

    
282
            if (text.Aveva.LabelType == LabelType.SingleText)
283
                DrawText(text.Aveva.X, text.Aveva.Y, text.Aveva.Height, text.VALUE, text.Aveva.Angle);
284
            else if (text.Aveva.LabelType == LabelType.MultiText)
285
            {
286
                string[] valueArray = text.VALUE.Split(new string[] { "\n" }, StringSplitOptions.None);
287
                List<string> values = new List<string>();
288
                for (int i = 0; i < valueArray.Length; i++)
289
                    values.Insert(0, valueArray[i]);
290

    
291
                for (int i = 0; i < values.Count; i++)
292
                {
293
                    double x = text.Aveva.X;
294
                    double y = text.Aveva.Y;
295
                    int heightIndex = i;
296

    
297
                    if (text.TextAngle == TextAngle.Degree0 || text.TextAngle == TextAngle.Degree180)
298
                        y = y + text.Aveva.Height * i;
299
                    else if (text.TextAngle == TextAngle.Degree90 || text.TextAngle == TextAngle.Degree270)
300
                        x = x + text.Aveva.Height * i;
301

    
302
                    DrawText(x, y, text.Aveva.Height, values[i], text.Aveva.Angle);
303
                }
304
            }
305
                
306

    
307
        }
308
        private void NoteModeling(Model.Note note)
309
        {
310
            if (note.TextAngle == TextAngle.None)
311
                return;
312

    
313
            if (note.Aveva.LabelType == LabelType.SingleNote)
314
                DrawText(note.Aveva.X, note.Aveva.Y, note.Aveva.Height, note.VALUE, note.Aveva.Angle);
315
            else if (note.Aveva.LabelType == LabelType.MultiNote)
316
            {
317
                string[] valueArray = note.VALUE.Split(new string[] { "\n" }, StringSplitOptions.None);
318
                List<string> values = new List<string>();
319
                for (int i = 0; i < valueArray.Length; i++)
320
                    values.Insert(0, valueArray[i]);
321

    
322
                for (int i = 0; i < values.Count; i++)
323
                {
324
                    double x = note.Aveva.X;
325
                    double y = note.Aveva.Y;
326
                    int heightIndex = i;
327

    
328
                    if (note.TextAngle == TextAngle.Degree0 || note.TextAngle == TextAngle.Degree180)
329
                        y = y + note.Aveva.Height * i;
330
                    else if (note.TextAngle == TextAngle.Degree90 || note.TextAngle == TextAngle.Degree270)
331
                        x = x + note.Aveva.Height * i;
332

    
333
                    DrawText(x, y, note.Aveva.Height, values[i], note.Aveva.Angle);
334
                }
335
            }
336
        }
337
        private void SetLineAttribute(Model.Line line)
338
        {
339

    
340
        }
341
        private void SetLineNumberAttribute(Model.LineNumber lineNumber)
342
        {
343

    
344
        }
345
        private void SetSymbolAttribute(Model.Symbol symbol)
346
        {
347

    
348
        }
349
        #endregion
350

    
351
        #region Drawing Method
352
        private long DrawPipe(string style, List<string> coordinates, LineNumber lineNumber = null)
353
        {
354
            List<long> prevHandles = GetAllGroupHandles();
355

    
356
            GUIUtils.SetPipeStyle(style);
357
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
358
            Editor editor = acDoc.Editor;
359
            List<object> commandParam = new List<object>();
360
            //command name
361
            commandParam.Add("DRPIPE");
362
            //coordinate
363
            foreach (var item in coordinates)
364
                commandParam.Add(item);
365

    
366
            //enter Parent(null)
367
            commandParam.Add(null);
368

    
369
            if (lineNumber != null)
370
            {
371
                Point3d point = new Point3d(lineNumber.Aveva.X, lineNumber.Aveva.Y, 0);
372
                commandParam.Add(point);
373
                commandParam.Add(lineNumber.Aveva.Angle);
374

    
375
                commandParam.Add(null);
376
            }
377
            else
378
                commandParam.Add(null);
379

    
380
            editor.Command(commandParam.ToArray());
381

    
382
            List<long> newHandles = GetAllGroupHandles();
383
            List<long> otherHandles = new List<long>();
384
            foreach (var item in newHandles)
385
                if (!prevHandles.Contains(item))
386
                    otherHandles.Add(item);
387

    
388
            if (otherHandles.Count == 1)
389
                return otherHandles[0];
390
            else
391
                return 0;
392
        }
393
        private long DrawPipe(string style, List<string> coordinates, ObjectId objectId)
394
        {
395
            List<long> prevHandles = GetAllGroupHandles();
396
            GUIUtils.SetPipeStyle(style);
397

    
398
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
399
            Editor editor = acDoc.Editor;
400
            List<object> commandParam = new List<object>();
401
            //command name
402
            commandParam.Add("DRPIPE");
403
            //coordinate
404
            foreach (var item in coordinates)
405
                commandParam.Add(item);
406
            //enter
407
            commandParam.Add(null);
408

    
409
            //Input Object ID
410
            commandParam.Add(objectId);
411

    
412
            //enter
413
            commandParam.Add(null);
414

    
415
            editor.Command(commandParam.ToArray());
416

    
417
            List<long> newHandles = GetAllGroupHandles();
418
            List<long> otherHandles = new List<long>();
419
            foreach (var item in newHandles)
420
                if (!prevHandles.Contains(item))
421
                    otherHandles.Add(item);
422

    
423
            if (otherHandles.Count == 1)
424
                return otherHandles[0];
425
            else
426
                return 0;
427
        }
428
        private long DrawSignal(string style, List<string> coordinates)
429
        {
430
            List<long> prevHandles = GetAllGroupHandles();
431

    
432
            GUIUtils.SetPipeStyle(style);
433
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
434
            Editor editor = acDoc.Editor;
435
            List<object> commandParam = new List<object>();
436
            //command name
437
            commandParam.Add("VPESIGNAL");
438
            //coordinate
439
            foreach (var item in coordinates)
440
                commandParam.Add(item);
441
            //enter
442
            commandParam.Add(null);
443

    
444
            editor.Command(commandParam.ToArray());
445

    
446
            List<long> newHandles = GetAllGroupHandles();
447
            List<long> otherHandles = new List<long>();
448
            foreach (var item in newHandles)
449
                if (!prevHandles.Contains(item))
450
                    otherHandles.Add(item);
451

    
452
            if (otherHandles.Count == 1)
453
                return otherHandles[0];
454
            else
455
                return 0;
456
        }
457
        private long InsertSymbol(Symbol symbol, DataRow symbolRow, bool needAngle, bool needBalloon)
458
        {
459
            long handle = 0;
460
            try
461
            {
462
                string insertSymbolName = symbol.Aveva.Name;
463
                double x = symbol.Aveva.X;
464
                double y = symbol.Aveva.Y;
465

    
466
                List<long> prevHandles = GetAllBlockHandlesByName(insertSymbolName);
467

    
468
                AVEVA.PID.Utilities.DrawingData drawingData = new AVEVA.PID.Utilities.DrawingData();
469
                drawingData.InsertSymbolName = insertSymbolName;
470
                Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
471
                Editor editor = acDoc.Editor;
472
                List<object> commandParam = new List<object>();
473
                commandParam.Add("INSSYM");
474

    
475
                // Insert Point
476
                Point3d point = new Point3d(x, y, 0);
477
                commandParam.Add(point);
478

    
479
                // Check Insert Point
480
                if (needAngle)
481
                    commandParam.Add(symbol.ANGLE);
482

    
483
                // Check Balloon
484
                if (needBalloon)
485
                {
486
                    point = new Point3d(x + 20, y + 20, 0);
487
                    commandParam.Add(point);
488
                    
489
                    // Check LeaderLine
490
                    if (GraphicalUtility.IsLeaderReqOnSymbolBalloons())
491
                        commandParam.Add(x + "," + y);
492
                }
493

    
494
                for (int i = 0; i < 8; i++)
495
                    commandParam.Add(null);
496

    
497
                editor.Command(commandParam.ToArray());
498

    
499
                List<long> newHandles = GetAllBlockHandlesByName(insertSymbolName);
500
                List<long> otherHandles = new List<long>();
501
                foreach (var item in newHandles)
502
                    if (!prevHandles.Contains(item))
503
                        otherHandles.Add(item);
504

    
505
                if (otherHandles.Count == 1)
506
                    return otherHandles[0];
507
                else
508
                    return 0;
509
            }
510
            catch (System.Exception ex)
511
            {
512

    
513
            }
514

    
515
            return handle;
516
        }
517
        private void DrawText(double x, double y, double height, string text, double rotation)
518
        {
519
            // Get the current document and database
520
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
521
            Database acCurDb = acDoc.Database;
522

    
523
            // Start a transaction
524
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
525
            {
526
                // Open the Block table for read
527
                BlockTable acBlkTbl;
528
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
529
                                                OpenMode.ForRead) as BlockTable;
530

    
531
                // Open the Block table record Model space for write
532
                BlockTableRecord acBlkTblRec;
533
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
534
                                                OpenMode.ForWrite) as BlockTableRecord;
535

    
536
                // Create a single-line text object
537
                using (DBText acText = new DBText())
538
                {
539
                    acText.Position = new Point3d(x, y, 0);
540
                    acText.Height = height;
541
                    acText.TextString = text;
542
                    acText.Rotation = rotation;
543

    
544
                    acBlkTblRec.AppendEntity(acText);
545
                    acTrans.AddNewlyCreatedDBObject(acText, true);
546
                }
547

    
548
                // Save the changes and dispose of the transaction
549
                acTrans.Commit();
550
            }
551
        }
552
        #endregion
553

    
554
        #region Autocad Utils
555
        private List<long> GetAllBlockHandlesByName(string name)
556
        {
557
            List<long> handles = new List<long>();
558

    
559
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
560
            Database acCurDb = acDoc.Database;
561
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
562
            {
563
                BlockTable gd = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
564
                foreach (var entry in gd)
565
                {
566
                    BlockTableRecord blockTableRecord = acTrans.GetObject(entry, OpenMode.ForRead, true) as BlockTableRecord;
567
                    if (blockTableRecord != null)
568
                    {
569
                        IEnumerable<BlockReference> records = AcDbLinqExtensionMethods.GetBlockReferences(blockTableRecord);
570
                        foreach (var item in records)
571
                        {
572
                            if (item.Name == name)
573
                                handles.Add(item.Handle.Value);
574
                        }
575
                    }
576
                }
577
                    
578
                acTrans.Commit();
579
            }
580
            return handles;
581
        }
582
        private List<long> GetAllGroupHandles()
583
        {
584
            List<long> handles = new List<long>();
585

    
586
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
587
            Database acCurDb = acDoc.Database;
588
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
589
            {
590
                DBDictionary gd = (DBDictionary)acTrans.GetObject(acCurDb.GroupDictionaryId, OpenMode.ForRead);
591
                foreach (var entry in gd)
592
                    handles.Add(entry.Value.Handle.Value);
593
                acTrans.Commit();
594
            }
595
            return handles;
596
        }
597
        private ObjectId GetFirstPolyLine(long groupHandle)
598
        {
599
            ObjectId result = ObjectId.Null;
600

    
601
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
602
            Database acCurDb = acDoc.Database;
603
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
604
            {
605
                DBDictionary gd = (DBDictionary)acTrans.GetObject(acCurDb.GroupDictionaryId, OpenMode.ForRead);
606
                foreach (var entry in gd)
607
                {
608
                    if (entry.Value.Handle.Value == groupHandle)
609
                    {
610
                        Autodesk.AutoCAD.DatabaseServices.Group group = acTrans.GetObject(entry.Value, OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.Group;
611
                        foreach (var item in group.GetAllEntityIds())
612
                        {
613
                            if (acTrans.GetObject(item, OpenMode.ForRead).GetType() == typeof(Autodesk.AutoCAD.DatabaseServices.Polyline))
614
                            {
615
                                result = item;
616
                                break;
617
                            }
618
                        }
619
                        break;
620
                    }
621
                }
622
                acTrans.Commit();
623
            }
624

    
625
            return result;
626
        }
627
        private ObjectId GetObjectIdByHandle(long lHandle)
628
        {
629
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
630
            Database acCurDb = acDoc.Database;
631
            Handle handle = new Handle(lHandle);
632

    
633
            return acCurDb.GetObjectId(false, handle, 0);
634
        }
635
        private void SetBlockReferenceRotation(ObjectId objectId, double rotation)
636
        {
637
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
638
            Database acCurDb = acDoc.Database;
639
            Editor acDocEd = acDoc.Editor;
640

    
641
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
642
            {
643
                DBObject objDB = acTrans.GetObject(objectId, OpenMode.ForWrite);
644
                if (objDB != null)
645
                {
646
                    if (objDB.GetType() == typeof(BlockReference))
647
                    {
648
                        BlockReference block = objDB as BlockReference;
649
                        block.Rotation = rotation;
650
                    }
651
                }
652
                acTrans.Commit();
653
            }
654
        }
655
        private void SetSymbolUDAAttribute(ObjectId objectId, List<Tuple<string, string>> datas)
656
        {
657
            AcadApplication acadApplication = Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication as Autodesk.AutoCAD.Interop.AcadApplication;
658
            AcadBlockReference acadBlockReference = acadApplication.ActiveDocument.ObjectIdToObject((long)objectId.OldIdPtr);
659
            if (acadBlockReference.HasAttributes)
660
            {
661
                object objectValue = RuntimeHelpers.GetObjectValue(acadBlockReference.GetAttributes());
662
                int arg_5B_0 = Microsoft.VisualBasic.Information.LBound((Array)objectValue, 1);
663
                int num = Microsoft.VisualBasic.Information.UBound((Array)objectValue, 1);
664
                for (int i = arg_5B_0; i <= num; i++)
665
                {
666
                    string text = string.Empty;
667
                    text = Conversions.ToString(NewLateBinding.LateGet(NewLateBinding.LateIndexGet(objectValue, new object[]
668
                    {
669
                                i
670
                    }, null), null, "tagString", new object[0], null, null, null));
671

    
672
                    Tuple<string, string> attribute = datas.Find(x => x.Item1 == text);
673
                    if (attribute != null)
674
                    {
675
                        NewLateBinding.LateSetComplex(NewLateBinding.LateIndexGet(objectValue, new object[]
676
                                {
677
                                    i
678
                                }, null), null, "textString", new object[]
679
                                {
680
                                    attribute.Item2.Split("|".ToCharArray())[0]
681
                                }, null, null, false, true);
682
                    }
683
                }
684
            }
685
        }
686
        #endregion
687

    
688
        #region Modeling Utils
689
        private void GetConnectedGroupLine(Model.Line line, List<Model.Line> group, bool isInsert)
690
        {
691
            if (!group.Contains(line))
692
            {
693
                if (isInsert)
694
                    group.Insert(0, line);
695
                else
696
                    group.Add(line);
697

    
698
                if (line.CONNECTORS[0].ConnectedObject != null && !IsExistEndBreak(line, line.CONNECTORS[0].ConnectedObject))
699
                {
700
                    object connObj = line.CONNECTORS[0].ConnectedObject;
701
                    if (connObj.GetType() == typeof(Model.Line) &&
702
                        APIDUtils.IsConnectedLine(connObj as Model.Line, line))
703
                        GetConnectedGroupLine(connObj as Model.Line, group, true);
704
                    else if (connObj.GetType() == typeof(Model.Symbol))
705
                    {
706
                        Model.Line connLine = FindOtherLineByRun(line, connObj as Symbol);
707
                        if (connLine != null)
708
                            GetConnectedGroupLine(connLine as Model.Line, group, true);
709
                    }
710
                }
711
                if (line.CONNECTORS[1].ConnectedObject != null && !IsExistEndBreak(line, line.CONNECTORS[1].ConnectedObject))
712
                {
713
                    object connObj = line.CONNECTORS[1].ConnectedObject;
714
                    if (connObj.GetType() == typeof(Model.Line) &&
715
                        APIDUtils.IsConnectedLine(connObj as Model.Line, line))
716
                        GetConnectedGroupLine(connObj as Model.Line, group, false);
717
                    else if (connObj.GetType() == typeof(Model.Symbol))
718
                    {
719
                        Model.Line connLine = FindOtherLineByRun(line, connObj as Symbol);
720
                        if (connLine != null)
721
                            GetConnectedGroupLine(connLine as Model.Line, group, false);
722
                    }
723
                }
724
            }
725
        }
726
        private void GetGroupLinePoints(List<Model.Line> groupLine, List<string> points)
727
        {
728
            for (int i = 0; i < groupLine.Count; i++)
729
            {
730
                Model.Line line = groupLine[i];
731
                if (i == 0)
732
                {
733
                    object connObj = line.CONNECTORS[0].ConnectedObject;
734
                    if (connObj != null)
735
                    {
736
                        string point = GetPointByConnectedItem(connObj, line, true);
737
                        if (string.IsNullOrEmpty(point))
738
                            points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
739
                        else
740
                            points.Add(point);
741
                    }
742
                    else
743
                        points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
744
                }
745
                else
746
                {
747
                    Model.Line prevLine = groupLine[i - 1];
748
                    if (line.SlopeType == SlopeType.HORIZONTAL &&
749
                        prevLine.SlopeType == SlopeType.VERTICAL)
750
                        points.Add(prevLine.Aveva.End_X + "," + line.Aveva.Start_Y);
751
                    else if (line.SlopeType == SlopeType.VERTICAL &&
752
                        prevLine.SlopeType == SlopeType.HORIZONTAL)
753
                        points.Add(line.Aveva.Start_X + "," + prevLine.Aveva.End_Y);
754
                    else
755
                        points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
756
                }
757

    
758
                if (i == groupLine.Count - 1)
759
                {
760
                    object connObj = line.CONNECTORS[1].ConnectedObject;
761
                    if (connObj != null && connObj.GetType() == typeof(Symbol))
762
                    {
763
                        string point = GetPointByConnectedItem(connObj, line, false);
764
                        if (string.IsNullOrEmpty(point))
765
                            points.Add(line.Aveva.End_X + "," + line.Aveva.End_Y);
766
                        else
767
                            points.Add(point);
768
                    }
769
                    else
770
                        points.Add(line.Aveva.End_X + "," + line.Aveva.End_Y);
771
                }
772
            }
773
        }
774
        private string GetPointByConnectedItem(object connObj, Model.Line line, bool isStart)
775
        {
776
            string result = string.Empty;
777
            double x;
778
            double y;
779
            if (isStart)
780
            {
781
                x = line.Aveva.Start_X;
782
                y = line.Aveva.Start_Y;
783
            }
784
            else
785
            {
786
                x = line.Aveva.End_X;
787
                y = line.Aveva.End_Y;
788
            }
789

    
790
            if (connObj.GetType() == typeof(Symbol))
791
            {
792
                Symbol connSymbol = connObj as Symbol;
793
                Connector connector = connSymbol.CONNECTORS.Find(loop => loop.ConnectedObject == line);
794

    
795
                SlopeType slopeType = APIDUtils.CalcSlope(connSymbol.X, connSymbol.Y, connector.X, connector.Y);
796
                if (slopeType == SlopeType.HORIZONTAL)
797
                    result = connSymbol.Aveva.X + "," + y;
798
                else if (slopeType == SlopeType.VERTICAL)
799
                    result = x + "," + connSymbol.Aveva.Y;
800
                else
801
                    result = x + "," + y;
802
            }
803
            else if (connObj.GetType() == typeof(OPC))
804
            {
805
                OPC connOPC = connObj as OPC;
806
                Connector connector = connOPC.CONNECTORS.Find(loop => loop.ConnectedObject == line);
807

    
808
                double locX = 0, locY = 0, sizeWidth = 0, sizeHeight = 0, aX = 0, aY = 0;
809
                APIDUtils.ConvertPointBystring(connOPC.LOCATION, ref locX, ref locY);
810
                APIDUtils.ConvertPointBystring(connOPC.SIZE, ref sizeWidth, ref sizeHeight);
811
                locX = locX + sizeWidth / 2;
812
                locY = locY + sizeHeight / 2;
813
                aX = locX;
814
                aY = locY;
815
                document.ConvertAvevaPoint(ref aX, ref aY);
816

    
817
                SlopeType slopeType = APIDUtils.CalcSlope(locX, locY, connector.X, connector.Y);
818
                if (slopeType == SlopeType.HORIZONTAL)
819
                    result = aX + "," + y;
820
                else if (slopeType == SlopeType.VERTICAL)
821
                    result = x + "," + aY;
822
                else
823
                    result = x + "," + y;
824
            }
825
            
826
            return result;
827
        }
828
        private bool IsExistEndBreak(object item1, object item2)
829
        {
830
            bool result = false;
831
            if (item1 != null && item2 != null)
832
            {
833
                EndBreak endBreak = document.EndBreaks.Find(x =>
834
            (APIDUtils.FindObjectByUID(document, x.OWNER) == item1 &&
835
            APIDUtils.FindObjectByUID(document, x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE) == item2) ||
836
            (APIDUtils.FindObjectByUID(document, x.OWNER) == item2 &&
837
            APIDUtils.FindObjectByUID(document, x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE) == item1));
838

    
839
                if (endBreak != null)
840
                    result = true;
841
            }
842

    
843
            return result;
844
        }
845
        private LineRun FindLineRun(Model.Line line)
846
        {
847
            List<LineRun> allLineRun = new List<LineRun>();
848
            foreach (var item in document.LINENUMBERS)
849
                allLineRun.AddRange(item.RUNS);
850
            foreach (var item in document.TRIMLINES)
851
                allLineRun.AddRange(item.RUNS);
852

    
853
            return allLineRun.Find(x => x.RUNITEMS.Contains(line));
854
        }
855
        private Model.Line FindOtherLineByRun(Model.Line line, Symbol symbol)
856
        {
857
            Model.Line result = null;
858
            LineRun run = FindLineRun(line);
859
            Connector connector = symbol.CONNECTORS.Find(x =>
860
            x.ConnectedObject != null &&
861
            x.ConnectedObject != line &&
862
            run.RUNITEMS.Contains(x.ConnectedObject) &&
863
            x.ConnectedObject.GetType() == typeof(Model.Line));
864

    
865
            if (connector != null)
866
                result = connector.ConnectedObject as Model.Line;
867
            
868
            return result;
869
        }
870
        private bool CheckAngle(DataRow symbolRow)
871
        {
872
            return int.Parse(symbolRow["Insert_Points"].ToString()).Equals(2);
873
        }
874
        private bool CheckBalloon(Symbol symbol)
875
        {
876
            bool result = false;
877

    
878
            string text = string.Empty;
879
            Hashtable symbolDefinitions = GraphicsUtility.GetSymbolDefinitions(symbol.Aveva.Name);
880
            if (symbolDefinitions.Count != 0)
881
            {
882
                text = symbolDefinitions[SymbolDefinition.symAflowType].ToString().ToUpper();
883

    
884
                if (text.Equals("VLP"))
885
                    text = "VPO";
886
                else if (text.Equals("IVP"))
887
                    text = "IPO";
888

    
889
                if (SymbolCategory.astrLabelBalloonBlockNames.Contains(text))
890
                    result = true;//dumbDwgUpgrade.addLabelBalloon(symbolForInsertion, objectId);
891
            }
892

    
893
            return result;
894
        }
895
        #endregion
896

    
897
        #region Test Source
898
        public void test()
899
        {
900
            //InitGUI();
901
            //DrawSignal("SONIC", new List<string>() { "2,100", "100,100" });
902

    
903
            DrawPipe("Main Pipe", new List<string>() { "2,100", "100,100" }, null);
904
            return;
905
            Symbol symbol = new Symbol();
906
            symbol.Aveva = new AvevaSymbolInfo();
907
            symbol.Aveva.Name = "INVB";
908
            symbol.Aveva.X = 50;
909
            symbol.Aveva.Y = 100;
910

    
911
            DataRow[] allRows = avevaInfo.AvevaSymbolTable.Select(string.Format("Symbol_Name = '{0}'", symbol.Aveva.Name));
912
            if (allRows.Length == 1)
913
            {
914
                DataRow symbolRow = allRows[0];
915
                bool bAngle = CheckAngle(symbolRow);
916
                bool bBalloon = CheckBalloon(symbol);
917
                bBalloon = false;
918
                long handle = InsertSymbol(symbol, symbolRow, bAngle, bBalloon);
919
            }
920

    
921
            Hashtable symbolDefinitions = GraphicsUtility.GetSymbolDefinitions(symbol.Aveva.Name);
922
            string text = symbolDefinitions[SymbolDefinition.symAflowType].ToString().ToUpper();
923
            if (int.Parse(symbolDefinitions[SymbolDefinition.symNoOfInsertPoints].ToString()).Equals(2))
924
            {
925
                bool bIsPromptRotate = true;
926
            }
927
            int num = int.Parse(symbolDefinitions[SymbolDefinition.symFixedOrUserDefined].ToString());
928

    
929
            AssociateSymbolType eAssosiateSym = AssociateSymbolType.None;
930
            bool bIsSymbolHasAssociation = GraphicalUtility.FindSymbolHasAssociation(text, ref eAssosiateSym);
931
            bool bPlaceSimpleBlocks = SymbolCategory.astrSimplePlacedBlocks.Contains(text);
932

    
933
            //DrawPipe("Main Pipe", new List<string>() { "2,200", "100,200" });
934

    
935
            //DrawPipe("Sub Pipe", new List<string>() { "50,100", "50,200" });
936
        }
937
        public static void TESTStatic(ObjectId objectId)
938
        {
939
            // Get the current document and database, and start a transaction
940
            //Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
941
            //Database acCurDb = acDoc.Database;
942
            //Editor acDocEd = acDoc.Editor;
943

    
944
            //using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
945
            //{
946
            //    Entity objDb = (Entity)acTrans.GetObject(objectId, OpenMode.ForWrite);
947
            //    Entity startNodeEntityForPipe = Pipe.GetStartNodeEntityForPipe(objDb);
948

    
949
            //    //ArrayList arrayList = new ArrayList();
950
            //    //ArrayList arrayList2 = new ArrayList();
951
            //    //PIDUtils.VBUtils.GetUserDefineAttributes(startNodeEntityForPipe.ObjectId, ref arrayList, ref arrayList2);
952
            //    //PIDUtils.VBUtils.GetUserDefineAttributes(objDb.ObjectId, ref arrayList, ref arrayList2);
953
            //    //NamedXDataBlock namedXDataBlock = XDataUtilities.GetNamedBlock(objDb, "ReferenceObject");
954

    
955
            //    XData xData = XDataUtilities.GetXData<Entity>(objDb);
956
            //    XData xData2 = XDataUtilities.GetXData<Entity>(startNodeEntityForPipe);
957
            //    acTrans.Commit();
958
            //}
959

    
960
            //PLABFO
961
        }
962
        #endregion
963
    }
964

    
965

    
966
    public static class AcDbLinqExtensionMethods
967
    {
968
        /// <summary>
969
        /// Get all references to the given BlockTableRecord, including 
970
        /// references to anonymous dynamic BlockTableRecords.
971
        /// </summary>
972

    
973
        public static IEnumerable<BlockReference> GetBlockReferences(
974
           this BlockTableRecord btr,
975
           OpenMode mode = OpenMode.ForRead,
976
           bool directOnly = true)
977
        {
978
            if (btr == null)
979
                throw new ArgumentNullException("btr");
980
            var tr = btr.Database.TransactionManager.TopTransaction;
981
            if (tr == null)
982
                throw new InvalidOperationException("No transaction");
983
            var ids = btr.GetBlockReferenceIds(directOnly, true);
984
            int cnt = ids.Count;
985
            for (int i = 0; i < cnt; i++)
986
            {
987
                yield return (BlockReference)
988
                   tr.GetObject(ids[i], mode, false, false);
989
            }
990
            if (btr.IsDynamicBlock)
991
            {
992
                BlockTableRecord btr2 = null;
993
                var blockIds = btr.GetAnonymousBlockIds();
994
                cnt = blockIds.Count;
995
                for (int i = 0; i < cnt; i++)
996
                {
997
                    btr2 = (BlockTableRecord)tr.GetObject(blockIds[i],
998
                       OpenMode.ForRead, false, false);
999
                    ids = btr2.GetBlockReferenceIds(directOnly, true);
1000
                    int cnt2 = ids.Count;
1001
                    for (int j = 0; j < cnt2; j++)
1002
                    {
1003
                        yield return (BlockReference)
1004
                           tr.GetObject(ids[j], mode, false, false);
1005
                    }
1006
                }
1007
            }
1008
        }
1009
    }
1010
}
클립보드 이미지 추가 (최대 크기: 500 MB)