프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / APIDConverter / AutoModeling.cs @ c8b025e0

이력 | 보기 | 이력해설 | 다운로드 (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
using System.Runtime.InteropServices;
12
using System.Threading;
13

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

    
24
using AVEVA.PID.Components;
25
using AVEVA.PID.GUI;
26
using AVEVA.PID.Common;
27
using AVEVA.PID.DWGSelector;
28
using AVEVA.PID.Utilities;
29

    
30
using AVEVA.PID.CustomizationUtility.DB;
31
using AVEVA.PID.CustomizationUtility.Model;
32
using AVEVA.PID.CustomizationUtility.Properties;
33

    
34
using DevExpress.XtraSplashScreen;
35

    
36
namespace AVEVA.PID.CustomizationUtility
37
{
38
    public class AutoModeling
39
    {
40
        [DllImport("user32")]
41
        public static extern int FindWindow(string lpClassName, string lpWindowName);
42

    
43
        public static AutoModeling Running { get; set; }
44
        Model.Document document;
45
        AvevaInfo avevaInfo;
46

    
47
        private void SetConvertRule()
48
        {
49
            #region OPC Setting
50
            document.OPCs.Sort(SortOPC);
51
            int SortOPC(OPC a, OPC b)
52
            {
53
                if (a.FlowType == FlowType.In)
54
                    return 1;
55
                else
56
                    return 0;
57
            }
58
            #endregion
59
        }
60

    
61
        public AutoModeling(Model.Document document)
62
        {
63
            this.document = document;
64
            avevaInfo = AvevaInfo.GetInstance();
65
        }
66

    
67
        public void CreateDrawing()
68
        {
69
            string outPath = Project_DB.GetDirectiveValue("DRGPTH");
70
            string tempPath = Path.GetTempPath();
71
            string selectedFullPath = Path.Combine(tempPath, document.AvevaTemplateName + ".DWT");
72

    
73
            DWTSelector.strDrawingNumber = document.AvevaDrawingNumber;
74
            DWTSelector.strSheetNumber = document.AvevaSheetNumber;
75
            DWTSelector.strCadFileName = document.AvevaDrawingNumber + document.AvevaSheetNumber;
76
            DWTSelector.strCadFilePath = outPath;
77

    
78
            try
79
            {
80
                string text = ReadWriteDrawingData.ReadTemplateData(document.AvevaTemplateName, document.AvevaTemplateID, selectedFullPath, false);
81
                Autodesk.AutoCAD.Interop.AcadApplication acadApplication = Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication as Autodesk.AutoCAD.Interop.AcadApplication;
82
                Autodesk.AutoCAD.Interop.AcadDocument acadDocument = acadApplication.Documents.Add(text);
83

    
84
                Commands.addLatestPidvesrionToDictionary();
85
                AVVPropCmd.ActivateAcad();
86

    
87
                if (acadDocument != null)
88
                {
89
                    Running = this;
90
                    acadApplication.ActiveDocument = acadDocument;
91
                    acadDocument.SendCommand("QSAVE ");
92
                    acadDocument.SendCommand("APPIDRun ");
93
                    acadDocument.SendCommand("QSAVE ");
94
                    Running = null;
95
                }
96
            }
97
            catch (System.Exception ex)
98
            {
99
                
100
            }
101

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

    
113
                SetConvertRule();
114

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

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

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

    
222
        #region Modeling Method
223
        private void LineModeling(Model.Line line)
224
        {
225
            List<Model.Line> groupLine = new List<Model.Line>();
226
            List<string> points = new List<string>();
227
            GetConnectedGroupLine(line, groupLine, false);
228
            GetGroupLinePoints(groupLine, points);
229

    
230
            LineNumber lineNumber = null;
231
            if (line.Aveva.Type == Model.Type.Pipe)
232
            {
233
                foreach (var item in groupLine)
234
                {
235
                    lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == item.UID);
236
                    if (lineNumber != null)
237
                    {
238
                        GUIUtils.SetAutoLabelCheck(true);
239
                        AvevaThread.Run(ThreadType.OkBtnClick, null);
240
                        break;
241
                    }
242
                }
243
            }
244

    
245

    
246
            long handle = 0;
247
            if (line.Aveva.Type == Model.Type.Pipe)
248
                handle = DrawPipe(line.Aveva.Name, points, lineNumber);
249
            else if (line.Aveva.Type == Model.Type.Signal)
250
                handle = DrawSignal(line.Aveva.Name, points);
251

    
252
            if (lineNumber != null)
253
            {
254
                GUIUtils.SetAutoLabelCheck(false);
255
                AvevaThread.Stop(ThreadType.OkBtnClick);
256
            }
257

    
258
            foreach (var item in groupLine)
259
                item.Aveva.Handle = handle;
260
        }
261
        private void SymbolModeling(Symbol symbol)
262
        {
263
            DataRow[] allRows = avevaInfo.AvevaSymbolTable.Select(string.Format("Symbol_Name = '{0}'", symbol.Aveva.Name));
264
            if (allRows.Length == 1)
265
            {
266
                DataRow symbolRow = allRows[0];
267
                bool bAngle = CheckAngle(symbolRow);
268
                bool bBalloon = CheckBalloon(symbol);
269

    
270
                long handle = InsertSymbol(symbol, symbolRow, bAngle, bBalloon);
271
                if (handle != 0)
272
                {
273
                    symbol.Aveva.Handle = handle;
274

    
275
                    if (!bAngle)
276
                    {
277
                        ObjectId objectId = GetObjectIdByHandle(handle);
278
                        if (objectId != ObjectId.Null)
279
                        {
280
                            SetBlockReferenceRotation(objectId, symbol.ANGLE);
281
                        }
282
                    }
283
                }
284
            }
285
        }
286
        private void TextModeling(Text text)
287
        {
288
            if (text.TextAngle == TextAngle.None)
289
                return;
290

    
291
            if (text.Aveva.LabelType == LabelType.SingleText)
292
                DrawText(text.Aveva.X, text.Aveva.Y, text.Aveva.Height, text.VALUE, text.Aveva.Angle);
293
            else if (text.Aveva.LabelType == LabelType.MultiText)
294
            {
295
                string[] valueArray = text.VALUE.Split(new string[] { "\n" }, StringSplitOptions.None);
296
                List<string> values = new List<string>();
297
                for (int i = 0; i < valueArray.Length; i++)
298
                    values.Insert(0, valueArray[i]);
299

    
300
                for (int i = 0; i < values.Count; i++)
301
                {
302
                    double x = text.Aveva.X;
303
                    double y = text.Aveva.Y;
304
                    int heightIndex = i;
305

    
306
                    if (text.TextAngle == TextAngle.Degree0 || text.TextAngle == TextAngle.Degree180)
307
                        y = y + text.Aveva.Height * i;
308
                    else if (text.TextAngle == TextAngle.Degree90 || text.TextAngle == TextAngle.Degree270)
309
                        x = x + text.Aveva.Height * i;
310

    
311
                    DrawText(x, y, text.Aveva.Height, values[i], text.Aveva.Angle);
312
                }
313
            }
314
                
315

    
316
        }
317
        private void NoteModeling(Model.Note note)
318
        {
319
            if (note.TextAngle == TextAngle.None)
320
                return;
321

    
322
            if (note.Aveva.LabelType == LabelType.SingleNote)
323
                DrawText(note.Aveva.X, note.Aveva.Y, note.Aveva.Height, note.VALUE, note.Aveva.Angle);
324
            else if (note.Aveva.LabelType == LabelType.MultiNote)
325
            {
326
                string[] valueArray = note.VALUE.Split(new string[] { "\n" }, StringSplitOptions.None);
327
                List<string> values = new List<string>();
328
                for (int i = 0; i < valueArray.Length; i++)
329
                    values.Insert(0, valueArray[i]);
330

    
331
                for (int i = 0; i < values.Count; i++)
332
                {
333
                    double x = note.Aveva.X;
334
                    double y = note.Aveva.Y;
335
                    int heightIndex = i;
336

    
337
                    if (note.TextAngle == TextAngle.Degree0 || note.TextAngle == TextAngle.Degree180)
338
                        y = y + note.Aveva.Height * i;
339
                    else if (note.TextAngle == TextAngle.Degree90 || note.TextAngle == TextAngle.Degree270)
340
                        x = x + note.Aveva.Height * i;
341

    
342
                    DrawText(x, y, note.Aveva.Height, values[i], note.Aveva.Angle);
343
                }
344
            }
345
        }
346
        private void SetLineAttribute(Model.Line line)
347
        {
348

    
349
        }
350
        private void SetLineNumberAttribute(Model.LineNumber lineNumber)
351
        {
352
            Model.Line line = APIDUtils.FindObjectByUID(document, lineNumber.CONNLINE) as Model.Line;
353
            if (line != null)
354
            {
355
                foreach (Model.Attribute attribute in lineNumber.ATTRIBUTES)
356
                {
357
                    AttributeInfo info = avevaInfo.AttributeInfo.Find(x => x.UID == attribute.UID);
358
                    if (info != null)
359
                    {
360
                        if (info.APID_ATTRIBUTE_TYPE == AvevaAttributeType.PipeAttribute)
361
                        {
362

    
363
                        }
364
                    }
365
                }
366
            }
367
        }
368
        private void SetSymbolAttribute(Model.Symbol symbol)
369
        {
370
            if (symbol.Aveva.Handle != 0)
371
            {
372
                List<Tuple<string, string>> udaDatas = new List<Tuple<string, string>>();
373
                foreach (var attribute in symbol.ATTRIBUTES)
374
                {
375
                    AttributeInfo info = avevaInfo.AttributeInfo.Find(x => x.UID == attribute.UID);
376
                    if (info != null)
377
                    {
378
                        if (info.APID_ATTRIBUTE_TYPE == AvevaAttributeType.UDA)
379
                            udaDatas.Add(new Tuple<string, string>(info.APID_ATTRIBUTE, attribute.VALUE));
380
                    }
381
                }
382
                if (udaDatas.Count > 0)
383
                    SetSymbolUDAAttribute(GetObjectIdByHandle(symbol.Aveva.Handle), udaDatas);
384
            }
385
        }
386
        #endregion
387

    
388
        #region Drawing Method
389
        private long DrawPipe(string style, List<string> coordinates, LineNumber lineNumber = null)
390
        {
391
            List<long> prevHandles = GetAllGroupHandles();
392

    
393
            GUIUtils.SetPipeStyle(style);
394
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
395
            Editor editor = acDoc.Editor;
396
            List<object> commandParam = new List<object>();
397
            //command name
398
            commandParam.Add("DRPIPE");
399
            //coordinate
400
            foreach (var item in coordinates)
401
                commandParam.Add(item);
402

    
403
            //enter Parent(null)
404
            commandParam.Add(null);
405

    
406
            if (lineNumber != null)
407
            {
408
                Point3d point = new Point3d(lineNumber.Aveva.X, lineNumber.Aveva.Y, 0);
409
                commandParam.Add(point);
410
                commandParam.Add(lineNumber.Aveva.Angle);
411

    
412
                commandParam.Add(null);
413
            }
414
            else
415
                commandParam.Add(null);
416

    
417
            editor.Command(commandParam.ToArray());
418

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

    
425
            if (otherHandles.Count == 1)
426
                return otherHandles[0];
427
            else
428
                return 0;
429
        }
430
        private long DrawPipe(string style, List<string> coordinates, ObjectId objectId)
431
        {
432
            List<long> prevHandles = GetAllGroupHandles();
433
            GUIUtils.SetPipeStyle(style);
434

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

    
446
            //Input Object ID
447
            commandParam.Add(objectId);
448

    
449
            //enter
450
            commandParam.Add(null);
451

    
452
            editor.Command(commandParam.ToArray());
453

    
454
            List<long> newHandles = GetAllGroupHandles();
455
            List<long> otherHandles = new List<long>();
456
            foreach (var item in newHandles)
457
                if (!prevHandles.Contains(item))
458
                    otherHandles.Add(item);
459

    
460
            if (otherHandles.Count == 1)
461
                return otherHandles[0];
462
            else
463
                return 0;
464
        }
465
        private long DrawSignal(string style, List<string> coordinates)
466
        {
467
            List<long> prevHandles = GetAllGroupHandles();
468

    
469
            GUIUtils.SetPipeStyle(style);
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
            //command name
474
            commandParam.Add("VPESIGNAL");
475
            //coordinate
476
            foreach (var item in coordinates)
477
                commandParam.Add(item);
478
            //enter
479
            commandParam.Add(null);
480

    
481
            editor.Command(commandParam.ToArray());
482

    
483
            List<long> newHandles = GetAllGroupHandles();
484
            List<long> otherHandles = new List<long>();
485
            foreach (var item in newHandles)
486
                if (!prevHandles.Contains(item))
487
                    otherHandles.Add(item);
488

    
489
            if (otherHandles.Count == 1)
490
                return otherHandles[0];
491
            else
492
                return 0;
493
        }
494
        private long InsertSymbol(Symbol symbol, DataRow symbolRow, bool needAngle, bool needBalloon)
495
        {
496
            long handle = 0;
497
            try
498
            {
499
                string insertSymbolName = symbol.Aveva.Name;
500
                double x = symbol.Aveva.X;
501
                double y = symbol.Aveva.Y;
502

    
503
                List<long> prevHandles = GetAllBlockHandlesByName(insertSymbolName);
504

    
505
                AVEVA.PID.Utilities.DrawingData drawingData = new AVEVA.PID.Utilities.DrawingData();
506
                drawingData.InsertSymbolName = insertSymbolName;
507
                Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
508
                Editor editor = acDoc.Editor;
509
                List<object> commandParam = new List<object>();
510
                commandParam.Add("INSSYM");
511

    
512
                // Insert Point
513
                Point3d point = new Point3d(x, y, 0);
514
                commandParam.Add(point);
515

    
516
                // Check Insert Point
517
                if (needAngle)
518
                    commandParam.Add(symbol.ANGLE);
519

    
520
                // Check Balloon
521
                if (needBalloon)
522
                {
523
                    point = new Point3d(x + 20, y + 20, 0);
524
                    commandParam.Add(point);
525
                    
526
                    // Check LeaderLine
527
                    if (GraphicalUtility.IsLeaderReqOnSymbolBalloons())
528
                        commandParam.Add(x + "," + y);
529
                }
530

    
531
                for (int i = 0; i < 8; i++)
532
                    commandParam.Add(null);
533

    
534
                editor.Command(commandParam.ToArray());
535

    
536
                List<long> newHandles = GetAllBlockHandlesByName(insertSymbolName);
537
                List<long> otherHandles = new List<long>();
538
                foreach (var item in newHandles)
539
                    if (!prevHandles.Contains(item))
540
                        otherHandles.Add(item);
541

    
542
                if (otherHandles.Count == 1)
543
                    return otherHandles[0];
544
                else
545
                    return 0;
546
            }
547
            catch (System.Exception ex)
548
            {
549

    
550
            }
551

    
552
            return handle;
553
        }
554
        private void DrawText(double x, double y, double height, string text, double rotation)
555
        {
556
            // Get the current document and database
557
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
558
            Database acCurDb = acDoc.Database;
559

    
560
            // Start a transaction
561
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
562
            {
563
                // Open the Block table for read
564
                BlockTable acBlkTbl;
565
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
566
                                                OpenMode.ForRead) as BlockTable;
567

    
568
                // Open the Block table record Model space for write
569
                BlockTableRecord acBlkTblRec;
570
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
571
                                                OpenMode.ForWrite) as BlockTableRecord;
572

    
573
                // Create a single-line text object
574
                using (DBText acText = new DBText())
575
                {
576
                    acText.Position = new Point3d(x, y, 0);
577
                    acText.Height = height;
578
                    acText.TextString = text;
579
                    acText.Rotation = rotation;
580

    
581
                    acBlkTblRec.AppendEntity(acText);
582
                    acTrans.AddNewlyCreatedDBObject(acText, true);
583
                }
584

    
585
                // Save the changes and dispose of the transaction
586
                acTrans.Commit();
587
            }
588
        }
589
        #endregion
590

    
591
        #region Autocad Utils
592
        private List<long> GetAllBlockHandlesByName(string name)
593
        {
594
            List<long> handles = new List<long>();
595

    
596
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
597
            Database acCurDb = acDoc.Database;
598
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
599
            {
600
                BlockTable gd = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
601
                foreach (var entry in gd)
602
                {
603
                    BlockTableRecord blockTableRecord = acTrans.GetObject(entry, OpenMode.ForRead, true) as BlockTableRecord;
604
                    if (blockTableRecord != null)
605
                    {
606
                        IEnumerable<BlockReference> records = AcDbLinqExtensionMethods.GetBlockReferences(blockTableRecord);
607
                        foreach (var item in records)
608
                        {
609
                            if (item.Name == name)
610
                                handles.Add(item.Handle.Value);
611
                        }
612
                    }
613
                }
614
                    
615
                acTrans.Commit();
616
            }
617
            return handles;
618
        }
619
        private List<long> GetAllGroupHandles()
620
        {
621
            List<long> handles = new List<long>();
622

    
623
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
624
            Database acCurDb = acDoc.Database;
625
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
626
            {
627
                DBDictionary gd = (DBDictionary)acTrans.GetObject(acCurDb.GroupDictionaryId, OpenMode.ForRead);
628
                foreach (var entry in gd)
629
                    handles.Add(entry.Value.Handle.Value);
630
                acTrans.Commit();
631
            }
632
            return handles;
633
        }
634
        private ObjectId GetFirstPolyLine(long groupHandle)
635
        {
636
            ObjectId result = ObjectId.Null;
637

    
638
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
639
            Database acCurDb = acDoc.Database;
640
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
641
            {
642
                DBDictionary gd = (DBDictionary)acTrans.GetObject(acCurDb.GroupDictionaryId, OpenMode.ForRead);
643
                foreach (var entry in gd)
644
                {
645
                    if (entry.Value.Handle.Value == groupHandle)
646
                    {
647
                        Autodesk.AutoCAD.DatabaseServices.Group group = acTrans.GetObject(entry.Value, OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.Group;
648
                        foreach (var item in group.GetAllEntityIds())
649
                        {
650
                            if (acTrans.GetObject(item, OpenMode.ForRead).GetType() == typeof(Autodesk.AutoCAD.DatabaseServices.Polyline))
651
                            {
652
                                result = item;
653
                                break;
654
                            }
655
                        }
656
                        break;
657
                    }
658
                }
659
                acTrans.Commit();
660
            }
661

    
662
            return result;
663
        }
664
        private ObjectId GetObjectIdByHandle(long lHandle)
665
        {
666
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
667
            Database acCurDb = acDoc.Database;
668
            Handle handle = new Handle(lHandle);
669
            ObjectId result = ObjectId.Null;
670
            try
671
            {
672
                result = acCurDb.GetObjectId(false, handle, 0);
673
            }
674
            catch (System.Exception ex)
675
            {
676

    
677
            }
678
            return result;
679
        }
680
        private Entity GetEntityByHandle(long handle)
681
        {
682
            Entity entity = null;
683
            ObjectId objectId = GetObjectIdByHandle(handle);
684
            if (objectId != ObjectId.Null)
685
            {
686
                Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
687
                Database acCurDb = acDoc.Database;
688
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
689
                {
690
                    entity = (Entity)acTrans.GetObject(objectId, OpenMode.ForRead);
691
                    acTrans.Commit();
692
                }
693
            }
694

    
695
            return entity;
696
        }
697
        private void SetBlockReferenceRotation(ObjectId objectId, double rotation)
698
        {
699
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
700
            Database acCurDb = acDoc.Database;
701
            Editor acDocEd = acDoc.Editor;
702

    
703
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
704
            {
705
                DBObject objDB = acTrans.GetObject(objectId, OpenMode.ForWrite);
706
                if (objDB != null)
707
                {
708
                    if (objDB.GetType() == typeof(BlockReference))
709
                    {
710
                        BlockReference block = objDB as BlockReference;
711
                        block.Rotation = rotation;
712
                    }
713
                }
714
                acTrans.Commit();
715
            }
716
        }
717
        private void SetSymbolUDAAttribute(ObjectId objectId, List<Tuple<string, string>> datas)
718
        {
719
            AcadApplication acadApplication = Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication as Autodesk.AutoCAD.Interop.AcadApplication;
720
            AcadBlockReference acadBlockReference = acadApplication.ActiveDocument.ObjectIdToObject((long)objectId.OldIdPtr);
721
            if (acadBlockReference.HasAttributes)
722
            {
723
                object objectValue = RuntimeHelpers.GetObjectValue(acadBlockReference.GetAttributes());
724
                int arg_5B_0 = Microsoft.VisualBasic.Information.LBound((Array)objectValue, 1);
725
                int num = Microsoft.VisualBasic.Information.UBound((Array)objectValue, 1);
726
                for (int i = arg_5B_0; i <= num; i++)
727
                {
728
                    string text = string.Empty;
729
                    text = Conversions.ToString(NewLateBinding.LateGet(NewLateBinding.LateIndexGet(objectValue, new object[]
730
                    {
731
                                i
732
                    }, null), null, "tagString", new object[0], null, null, null));
733

    
734
                    Tuple<string, string> attribute = datas.Find(x => x.Item1 == text);
735
                    if (attribute != null)
736
                    {
737
                        NewLateBinding.LateSetComplex(NewLateBinding.LateIndexGet(objectValue, new object[]
738
                                {
739
                                    i
740
                                }, null), null, "textString", new object[]
741
                                {
742
                                    attribute.Item2.Split("|".ToCharArray())[0]
743
                                }, null, null, false, true);
744
                    }
745
                }
746
            }
747
        }
748

    
749
        #endregion
750

    
751
        #region For Aveva
752
        private void SetAttributeByAvevaForm(long handle, List<Tuple<string, string>> datas)
753
        {
754
            Entity entity = GetEntityByHandle(handle);
755

    
756
            ComponentPropertiesHelper componentPropertiesHelper = new ComponentPropertiesHelper();
757
            AvevaThread.Run(ThreadType.AddProperty, datas);
758
            if (!componentPropertiesHelper.DisplayComponentProperties(entity))
759
                AvevaThread.Stop(ThreadType.AddProperty);
760
        }
761
        #endregion
762

    
763
        #region Modeling Utils
764
        private void GetConnectedGroupLine(Model.Line line, List<Model.Line> group, bool isInsert)
765
        {
766
            if (!group.Contains(line))
767
            {
768
                if (isInsert)
769
                    group.Insert(0, line);
770
                else
771
                    group.Add(line);
772

    
773
                if (line.CONNECTORS[0].ConnectedObject != null && !IsExistEndBreak(line, line.CONNECTORS[0].ConnectedObject))
774
                {
775
                    object connObj = line.CONNECTORS[0].ConnectedObject;
776
                    if (connObj.GetType() == typeof(Model.Line) &&
777
                        APIDUtils.IsConnectedLine(connObj as Model.Line, line))
778
                        GetConnectedGroupLine(connObj as Model.Line, group, true);
779
                    else if (connObj.GetType() == typeof(Model.Symbol))
780
                    {
781
                        Model.Line connLine = FindOtherLineByRun(line, connObj as Symbol);
782
                        if (connLine != null)
783
                            GetConnectedGroupLine(connLine as Model.Line, group, true);
784
                    }
785
                }
786
                if (line.CONNECTORS[1].ConnectedObject != null && !IsExistEndBreak(line, line.CONNECTORS[1].ConnectedObject))
787
                {
788
                    object connObj = line.CONNECTORS[1].ConnectedObject;
789
                    if (connObj.GetType() == typeof(Model.Line) &&
790
                        APIDUtils.IsConnectedLine(connObj as Model.Line, line))
791
                        GetConnectedGroupLine(connObj as Model.Line, group, false);
792
                    else if (connObj.GetType() == typeof(Model.Symbol))
793
                    {
794
                        Model.Line connLine = FindOtherLineByRun(line, connObj as Symbol);
795
                        if (connLine != null)
796
                            GetConnectedGroupLine(connLine as Model.Line, group, false);
797
                    }
798
                }
799
            }
800
        }
801
        private void GetGroupLinePoints(List<Model.Line> groupLine, List<string> points)
802
        {
803
            for (int i = 0; i < groupLine.Count; i++)
804
            {
805
                Model.Line line = groupLine[i];
806
                if (i == 0)
807
                {
808
                    object connObj = line.CONNECTORS[0].ConnectedObject;
809
                    if (connObj != null)
810
                    {
811
                        string point = GetPointByConnectedItem(connObj, line, true);
812
                        if (string.IsNullOrEmpty(point))
813
                            points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
814
                        else
815
                            points.Add(point);
816
                    }
817
                    else
818
                        points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
819
                }
820
                else
821
                {
822
                    Model.Line prevLine = groupLine[i - 1];
823
                    if (line.SlopeType == SlopeType.HORIZONTAL &&
824
                        prevLine.SlopeType == SlopeType.VERTICAL)
825
                        points.Add(prevLine.Aveva.End_X + "," + line.Aveva.Start_Y);
826
                    else if (line.SlopeType == SlopeType.VERTICAL &&
827
                        prevLine.SlopeType == SlopeType.HORIZONTAL)
828
                        points.Add(line.Aveva.Start_X + "," + prevLine.Aveva.End_Y);
829
                    else
830
                        points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
831
                }
832

    
833
                if (i == groupLine.Count - 1)
834
                {
835
                    object connObj = line.CONNECTORS[1].ConnectedObject;
836
                    if (connObj != null && connObj.GetType() == typeof(Symbol))
837
                    {
838
                        string point = GetPointByConnectedItem(connObj, line, false);
839
                        if (string.IsNullOrEmpty(point))
840
                            points.Add(line.Aveva.End_X + "," + line.Aveva.End_Y);
841
                        else
842
                            points.Add(point);
843
                    }
844
                    else
845
                        points.Add(line.Aveva.End_X + "," + line.Aveva.End_Y);
846
                }
847
            }
848
        }
849
        private string GetPointByConnectedItem(object connObj, Model.Line line, bool isStart)
850
        {
851
            string result = string.Empty;
852
            double x;
853
            double y;
854
            if (isStart)
855
            {
856
                x = line.Aveva.Start_X;
857
                y = line.Aveva.Start_Y;
858
            }
859
            else
860
            {
861
                x = line.Aveva.End_X;
862
                y = line.Aveva.End_Y;
863
            }
864

    
865
            if (connObj.GetType() == typeof(Symbol))
866
            {
867
                Symbol connSymbol = connObj as Symbol;
868
                Connector connector = connSymbol.CONNECTORS.Find(loop => loop.ConnectedObject == line);
869

    
870
                SlopeType slopeType = APIDUtils.CalcSlope(connSymbol.X, connSymbol.Y, connector.X, connector.Y);
871
                if (slopeType == SlopeType.HORIZONTAL)
872
                    result = connSymbol.Aveva.X + "," + y;
873
                else if (slopeType == SlopeType.VERTICAL)
874
                    result = x + "," + connSymbol.Aveva.Y;
875
                else
876
                    result = x + "," + y;
877
            }
878
            else if (connObj.GetType() == typeof(OPC))
879
            {
880
                OPC connOPC = connObj as OPC;
881
                Connector connector = connOPC.CONNECTORS.Find(loop => loop.ConnectedObject == line);
882

    
883
                double locX = 0, locY = 0, sizeWidth = 0, sizeHeight = 0, aX = 0, aY = 0;
884
                APIDUtils.ConvertPointBystring(connOPC.LOCATION, ref locX, ref locY);
885
                APIDUtils.ConvertPointBystring(connOPC.SIZE, ref sizeWidth, ref sizeHeight);
886
                locX = locX + sizeWidth / 2;
887
                locY = locY + sizeHeight / 2;
888
                aX = locX;
889
                aY = locY;
890
                document.ConvertAvevaPoint(ref aX, ref aY);
891

    
892
                SlopeType slopeType = APIDUtils.CalcSlope(locX, locY, connector.X, connector.Y);
893
                if (slopeType == SlopeType.HORIZONTAL)
894
                    result = aX + "," + y;
895
                else if (slopeType == SlopeType.VERTICAL)
896
                    result = x + "," + aY;
897
                else
898
                    result = x + "," + y;
899
            }
900
            
901
            return result;
902
        }
903
        private bool IsExistEndBreak(object item1, object item2)
904
        {
905
            bool result = false;
906
            if (item1 != null && item2 != null)
907
            {
908
                EndBreak endBreak = document.EndBreaks.Find(x =>
909
            (APIDUtils.FindObjectByUID(document, x.OWNER) == item1 &&
910
            APIDUtils.FindObjectByUID(document, x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE) == item2) ||
911
            (APIDUtils.FindObjectByUID(document, x.OWNER) == item2 &&
912
            APIDUtils.FindObjectByUID(document, x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE) == item1));
913

    
914
                if (endBreak != null)
915
                    result = true;
916
            }
917

    
918
            return result;
919
        }
920
        private LineRun FindLineRun(Model.Line line)
921
        {
922
            List<LineRun> allLineRun = new List<LineRun>();
923
            foreach (var item in document.LINENUMBERS)
924
                allLineRun.AddRange(item.RUNS);
925
            foreach (var item in document.TRIMLINES)
926
                allLineRun.AddRange(item.RUNS);
927

    
928
            return allLineRun.Find(x => x.RUNITEMS.Contains(line));
929
        }
930
        private Model.Line FindOtherLineByRun(Model.Line line, Symbol symbol)
931
        {
932
            Model.Line result = null;
933
            LineRun run = FindLineRun(line);
934
            Connector connector = symbol.CONNECTORS.Find(x =>
935
            x.ConnectedObject != null &&
936
            x.ConnectedObject != line &&
937
            run.RUNITEMS.Contains(x.ConnectedObject) &&
938
            x.ConnectedObject.GetType() == typeof(Model.Line));
939

    
940
            if (connector != null)
941
                result = connector.ConnectedObject as Model.Line;
942
            
943
            return result;
944
        }
945
        private bool CheckAngle(DataRow symbolRow)
946
        {
947
            return int.Parse(symbolRow["Insert_Points"].ToString()).Equals(2);
948
        }
949
        private bool CheckBalloon(Symbol symbol)
950
        {
951
            bool result = false;
952

    
953
            string text = string.Empty;
954
            Hashtable symbolDefinitions = GraphicsUtility.GetSymbolDefinitions(symbol.Aveva.Name);
955
            if (symbolDefinitions.Count != 0)
956
            {
957
                text = symbolDefinitions[SymbolDefinition.symAflowType].ToString().ToUpper();
958

    
959
                if (text.Equals("VLP"))
960
                    text = "VPO";
961
                else if (text.Equals("IVP"))
962
                    text = "IPO";
963

    
964
                if (SymbolCategory.astrLabelBalloonBlockNames.Contains(text))
965
                    result = true;//dumbDwgUpgrade.addLabelBalloon(symbolForInsertion, objectId);
966
            }
967

    
968
            return result;
969
        }
970
        #endregion
971

    
972
        #region Test Source
973
        public void test()
974
        {
975

    
976
        }
977
        public static void TESTStatic(long handle)
978
        {
979
            
980
        }
981
        #endregion
982
    }
983

    
984

    
985
    public static class AcDbLinqExtensionMethods
986
    {
987
        /// <summary>
988
        /// Get all references to the given BlockTableRecord, including 
989
        /// references to anonymous dynamic BlockTableRecords.
990
        /// </summary>
991

    
992
        public static IEnumerable<BlockReference> GetBlockReferences(
993
           this BlockTableRecord btr,
994
           OpenMode mode = OpenMode.ForRead,
995
           bool directOnly = true)
996
        {
997
            if (btr == null)
998
                throw new ArgumentNullException("btr");
999
            var tr = btr.Database.TransactionManager.TopTransaction;
1000
            if (tr == null)
1001
                throw new InvalidOperationException("No transaction");
1002
            var ids = btr.GetBlockReferenceIds(directOnly, true);
1003
            int cnt = ids.Count;
1004
            for (int i = 0; i < cnt; i++)
1005
            {
1006
                yield return (BlockReference)
1007
                   tr.GetObject(ids[i], mode, false, false);
1008
            }
1009
            if (btr.IsDynamicBlock)
1010
            {
1011
                BlockTableRecord btr2 = null;
1012
                var blockIds = btr.GetAnonymousBlockIds();
1013
                cnt = blockIds.Count;
1014
                for (int i = 0; i < cnt; i++)
1015
                {
1016
                    btr2 = (BlockTableRecord)tr.GetObject(blockIds[i],
1017
                       OpenMode.ForRead, false, false);
1018
                    ids = btr2.GetBlockReferenceIds(directOnly, true);
1019
                    int cnt2 = ids.Count;
1020
                    for (int j = 0; j < cnt2; j++)
1021
                    {
1022
                        yield return (BlockReference)
1023
                           tr.GetObject(ids[j], mode, false, false);
1024
                    }
1025
                }
1026
            }
1027
        }
1028
    }
1029
}
클립보드 이미지 추가 (최대 크기: 500 MB)