프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / APIDConverter / AutoModeling.cs @ 20dd244c

이력 | 보기 | 이력해설 | 다운로드 (45.2 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
                Zoom(0, 0, 10, 10);
116
                RunLineModeling();
117

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

    
138
        private void Zoom(double minX, double minY, double maxX, double maxY)
139
        {
140
            Autodesk.AutoCAD.Interop.AcadApplication acadApplication = Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication as Autodesk.AutoCAD.Interop.AcadApplication;
141
            double[] lower = new double[3] { minX, minY, 0 };
142
            double[] upper = new double[3] { maxX, maxY, 0 };
143
            acadApplication.ZoomWindow(lower, upper);
144
            acadApplication.ActiveDocument.Activate();
145
        }
146
        private void ZoomAll()
147
        {
148
            Autodesk.AutoCAD.Interop.AcadApplication acadApplication = Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication as Autodesk.AutoCAD.Interop.AcadApplication;
149
            acadApplication.ZoomAll();
150
            acadApplication.ActiveDocument.Activate();
151
        }
152

    
153
        #region Run Method
154
        private void RunLineModeling()
155
        {
156
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
157
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling");
158
            foreach (var item in document.LINES)
159
            {
160
                if (item.Aveva.Handle == 0)
161
                    LineModeling(item);
162

    
163
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
164
            }
165
        }
166
        private void RunOPCModeling()
167
        {
168
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.OPCs.Count);
169
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "OPC Modeling");
170
            foreach (var item in document.OPCs)
171
            {
172
                if (item.Aveva.Handle == 0)
173
                    SymbolModeling(item);
174
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
175
            }
176
        }
177
        private void RunSymbolModeling()
178
        {
179
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
180
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
181
            foreach (var item in document.SYMBOLS)
182
            {
183
                if (item.Aveva.Handle == 0)
184
                    SymbolModeling(item);
185
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
186
            }
187
        }
188
        private void RunTextModeling()
189
        {
190
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Texts.Count);
191
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Text Modeling");
192
            foreach (var item in document.Texts)
193
            {
194
                TextModeling(item);
195
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
196
            }
197
        }
198
        private void RunNoteModeling()
199
        {
200
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Notes.Count);
201
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Note Modeling");
202
            foreach (var item in document.Notes)
203
            {
204
                NoteModeling(item);
205
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
206
            }
207
        }
208
        private void RunInputLineAttribute()
209
        {
210
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
211
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Input Line Attribute");
212
            foreach (var item in document.LINES)
213
            {
214
                SetLineAttribute(item);
215
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
216
            }
217
        }
218
        private void RunInputSymbolAttribute()
219
        {
220
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
221
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Input Symbol Attribute");
222
            foreach (var item in document.SYMBOLS)
223
            {
224
                SetSymbolAttribute(item);
225
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
226
            }
227
        }
228
        private void RunInputLineNumberAttribute()
229
        {
230
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
231
            SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.SetStep, "Input LineNumber Attribute");
232
            foreach (var item in document.LINENUMBERS)
233
            {
234
                SetLineNumberAttribute(item);
235
                SplashScreenManager.Default.SendCommand(APIDSplashScreen.SplashScreenCommand.UpProgress, null);
236
            }
237
        }
238
        #endregion
239

    
240
        #region Modeling Method
241
        private void LineModeling(Model.Line line)
242
        {
243
            List<Model.Line> groupLine = new List<Model.Line>();
244
            List<string> points = new List<string>();
245
            GetConnectedGroupLine(line, groupLine, false);
246
            CoordinateCorrection(groupLine);
247
            GetGroupLinePoints(groupLine, points);
248

    
249
            LineNumber lineNumber = null;
250
            if (line.Aveva.Type == Model.Type.Pipe)
251
            {
252
                foreach (var item in groupLine)
253
                {
254
                    lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == item.UID);
255
                    if (lineNumber != null)
256
                    {
257
                        GUIUtils.SetAutoLabelCheck(true);
258
                        AvevaThread.Run(ThreadType.LineNumberModeling, null);
259
                        break;
260
                    }
261
                }
262
            }
263

    
264
            long handle = 0;
265
            if (line.Aveva.Type == Model.Type.Pipe)
266
                handle = DrawPipe(line.Aveva.Name, points, lineNumber);
267
            else if (line.Aveva.Type == Model.Type.Signal)
268
                handle = DrawSignal(line.Aveva.Name, points);
269

    
270
            if (lineNumber != null)
271
            {
272
                GUIUtils.SetAutoLabelCheck(false);
273
                AvevaThread.Stop(ThreadType.LineNumberModeling);
274
            }
275

    
276
            foreach (var item in groupLine)
277
                item.Aveva.Handle = handle;
278
        }
279
        private void SymbolModeling(Symbol symbol)
280
        {
281
            DataRow[] allRows = avevaInfo.AvevaSymbolTable.Select(string.Format("Symbol_Name = '{0}'", symbol.Aveva.Name));
282
            if (allRows.Length == 1)
283
            {
284
                DataRow symbolRow = allRows[0];
285
                bool bAngle = CheckAngle(symbolRow);
286
                bool bBalloon = CheckBalloon(symbol);
287

    
288
                long handle = DrawSymbol(symbol, symbolRow, bAngle, bBalloon);
289
                if (handle != 0)
290
                {
291
                    symbol.Aveva.Handle = handle;
292

    
293
                    if (!bAngle)
294
                    {
295
                        ObjectId objectId = APIDUtils.GetObjectIdByHandle(handle);
296
                        if (objectId != ObjectId.Null)
297
                        {
298
                            SetBlockReferenceRotation(objectId, symbol.ANGLE);
299
                        }
300
                    }
301
                }
302
            }
303
        }
304
        private void TextModeling(Text text)
305
        {
306
            if (text.TextAngle == TextAngle.None || text.ASSOCIATION)
307
                return;
308

    
309
            if (text.Aveva.LabelType == LabelType.SingleText)
310
                DrawText(text.Aveva.X, text.Aveva.Y, text.Aveva.Height, text.VALUE, text.Aveva.Angle);
311
            else if (text.Aveva.LabelType == LabelType.MultiText)
312
            {
313
                string[] valueArray = text.VALUE.Split(new string[] { "\n" }, StringSplitOptions.None);
314
                List<string> values = new List<string>();
315
                for (int i = 0; i < valueArray.Length; i++)
316
                    values.Insert(0, valueArray[i]);
317

    
318
                for (int i = 0; i < values.Count; i++)
319
                {
320
                    double x = text.Aveva.X;
321
                    double y = text.Aveva.Y;
322
                    int heightIndex = i;
323

    
324
                    if (text.TextAngle == TextAngle.Degree0 || text.TextAngle == TextAngle.Degree180)
325
                        y = y + text.Aveva.Height * i;
326
                    else if (text.TextAngle == TextAngle.Degree90 || text.TextAngle == TextAngle.Degree270)
327
                        x = x + text.Aveva.Height * i;
328

    
329
                    DrawText(x, y, text.Aveva.Height, values[i], text.Aveva.Angle);
330
                }
331
            }
332
                
333

    
334
        }
335
        private void NoteModeling(Model.Note note)
336
        {
337
            if (note.TextAngle == TextAngle.None)
338
                return;
339

    
340
            if (note.Aveva.LabelType == LabelType.SingleNote)
341
                DrawText(note.Aveva.X, note.Aveva.Y, note.Aveva.Height, note.VALUE, note.Aveva.Angle);
342
            else if (note.Aveva.LabelType == LabelType.MultiNote)
343
            {
344
                string[] valueArray = note.VALUE.Split(new string[] { "\n" }, StringSplitOptions.None);
345
                List<string> values = new List<string>();
346
                for (int i = 0; i < valueArray.Length; i++)
347
                    values.Insert(0, valueArray[i]);
348

    
349
                for (int i = 0; i < values.Count; i++)
350
                {
351
                    double x = note.Aveva.X;
352
                    double y = note.Aveva.Y;
353
                    int heightIndex = i;
354

    
355
                    if (note.TextAngle == TextAngle.Degree0 || note.TextAngle == TextAngle.Degree180)
356
                        y = y + note.Aveva.Height * i;
357
                    else if (note.TextAngle == TextAngle.Degree90 || note.TextAngle == TextAngle.Degree270)
358
                        x = x + note.Aveva.Height * i;
359

    
360
                    DrawText(x, y, note.Aveva.Height, values[i], note.Aveva.Angle);
361
                }
362
            }
363
        }
364
        private void SetLineAttribute(Model.Line line)
365
        {
366

    
367
        }
368
        private void SetLineNumberAttribute(Model.LineNumber lineNumber)
369
        {
370
            Model.Line line = APIDUtils.FindObjectByUID(document, lineNumber.CONNLINE) as Model.Line;
371
            if (line != null && line.Aveva.Handle != 0)
372
            {
373
                List<Tuple<string, string>> datas = new List<Tuple<string, string>>();
374
                foreach (Model.Attribute attribute in lineNumber.ATTRIBUTES)
375
                {
376
                    AttributeInfo info = avevaInfo.AttributeInfo.Find(x => x.UID == attribute.UID);
377
                    if (info != null && !string.IsNullOrEmpty(info.APID_ATTRIBUTE))
378
                        datas.Add(new Tuple<string, string>(info.APID_ATTRIBUTE, attribute.VALUE));
379
                }
380
                if (datas.Count > 0)
381
                {
382
                    ObjectId objectId = GetFirstPolyLineObjectId(line.Aveva.Handle);
383
                    if (!objectId.IsNull)
384
                        SetAttributeByAvevaForm(objectId.Handle.Value, datas);
385
                }
386
            }
387
        }
388
        private void SetSymbolAttribute(Model.Symbol symbol)
389
        {
390
            if (symbol.Aveva.Handle != 0)
391
            {
392
                List<Tuple<string, string>> datas = new List<Tuple<string, string>>();
393
                foreach (var attribute in symbol.ATTRIBUTES)
394
                {
395
                    AttributeInfo info = avevaInfo.AttributeInfo.Find(x => x.UID == attribute.UID);
396
                    if (info != null && !string.IsNullOrEmpty(info.APID_ATTRIBUTE))
397
                        datas.Add(new Tuple<string, string>(info.APID_ATTRIBUTE, attribute.VALUE));
398
                }
399
                if (datas.Count > 0)
400
                {
401
                    ObjectId objectId = APIDUtils.GetObjectIdByHandle(symbol.Aveva.Handle);
402
                    if (!objectId.IsNull)
403
                        SetAttributeByAvevaForm(objectId.Handle.Value, datas);
404
                }
405
            }
406
        }
407
        #endregion
408

    
409
        #region Drawing Method
410
        private long DrawPipe(string style, List<string> coordinates, LineNumber lineNumber = null)
411
        {
412
            List<long> prevHandles = GetAllGroupHandles();
413

    
414
            GUIUtils.SetPipeStyle(style);
415
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
416
            Editor editor = acDoc.Editor;
417
            List<object> commandParam = new List<object>();
418
            //command name
419
            commandParam.Add("DRPIPE");
420
            //coordinate
421
            foreach (var item in coordinates)
422
                commandParam.Add(item);
423

    
424
            //enter Parent(null)
425
            commandParam.Add(null);
426

    
427
            if (lineNumber != null)
428
            {
429
                Point3d point = new Point3d(lineNumber.Aveva.X, lineNumber.Aveva.Y, 0);
430
                commandParam.Add(point);
431
                commandParam.Add(lineNumber.Aveva.Angle);
432

    
433
                commandParam.Add(null);
434
            }
435
            else
436
                commandParam.Add(null);
437

    
438
            editor.Command(commandParam.ToArray());
439

    
440
            List<long> newHandles = GetAllGroupHandles();
441
            List<long> otherHandles = new List<long>();
442
            foreach (var item in newHandles)
443
                if (!prevHandles.Contains(item))
444
                    otherHandles.Add(item);
445

    
446
            if (otherHandles.Count == 1)
447
                return otherHandles[0];
448
            else
449
                return 0;
450
        }
451
        private long DrawPipe(string style, List<string> coordinates, ObjectId objectId)
452
        {
453
            List<long> prevHandles = GetAllGroupHandles();
454
            GUIUtils.SetPipeStyle(style);
455

    
456
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
457
            Editor editor = acDoc.Editor;
458
            List<object> commandParam = new List<object>();
459
            //command name
460
            commandParam.Add("DRPIPE");
461
            //coordinate
462
            foreach (var item in coordinates)
463
                commandParam.Add(item);
464
            //enter
465
            commandParam.Add(null);
466

    
467
            //Input Object ID
468
            commandParam.Add(objectId);
469

    
470
            //enter
471
            commandParam.Add(null);
472

    
473
            editor.Command(commandParam.ToArray());
474

    
475
            List<long> newHandles = GetAllGroupHandles();
476
            List<long> otherHandles = new List<long>();
477
            foreach (var item in newHandles)
478
                if (!prevHandles.Contains(item))
479
                    otherHandles.Add(item);
480

    
481
            if (otherHandles.Count == 1)
482
                return otherHandles[0];
483
            else
484
                return 0;
485
        }
486
        private long DrawSignal(string style, List<string> coordinates)
487
        {
488
            List<long> prevHandles = GetAllGroupHandles();
489

    
490
            GUIUtils.SetPipeStyle(style);
491
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
492
            Editor editor = acDoc.Editor;
493
            List<object> commandParam = new List<object>();
494
            //command name
495
            commandParam.Add("VPESIGNAL");
496
            //coordinate
497
            foreach (var item in coordinates)
498
                commandParam.Add(item);
499
            //enter
500
            commandParam.Add(null);
501

    
502
            editor.Command(commandParam.ToArray());
503

    
504
            List<long> newHandles = GetAllGroupHandles();
505
            List<long> otherHandles = new List<long>();
506
            foreach (var item in newHandles)
507
                if (!prevHandles.Contains(item))
508
                    otherHandles.Add(item);
509

    
510
            if (otherHandles.Count == 1)
511
                return otherHandles[0];
512
            else
513
                return 0;
514
        }
515
        private long DrawSymbol(Symbol symbol, DataRow symbolRow, bool needAngle, bool needBalloon)
516
        {
517
            long handle = 0;
518
            try
519
            {
520
                string insertSymbolName = symbol.Aveva.Name;
521
                double x = symbol.Aveva.X;
522
                double y = symbol.Aveva.Y;
523

    
524
                List<long> prevHandles = GetAllBlockHandlesByName(insertSymbolName);
525

    
526
                AVEVA.PID.Utilities.DrawingData drawingData = new AVEVA.PID.Utilities.DrawingData();
527
                drawingData.InsertSymbolName = insertSymbolName;
528
                Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
529
                Editor editor = acDoc.Editor;
530
                List<object> commandParam = new List<object>();
531
                commandParam.Add("INSSYM");
532

    
533
                // Insert Point
534
                Point3d point = new Point3d(x, y, 0);
535
                commandParam.Add(point);
536

    
537
                // Check Insert Point
538
                if (needAngle)
539
                {
540
                    double degree = RadianToDegree(symbol.ANGLE);
541
                    commandParam.Add(degree);
542
                }
543
                    
544

    
545
                // Check Balloon
546
                if (needBalloon)
547
                {
548
                    point = new Point3d(x + 20, y + 20, 0);
549
                    commandParam.Add(point);
550
                    
551
                    // Check LeaderLine
552
                    if (GraphicalUtility.IsLeaderReqOnSymbolBalloons())
553
                        commandParam.Add(x + "," + y);
554
                }
555

    
556
                for (int i = 0; i < 8; i++)
557
                    commandParam.Add(null);
558

    
559
                editor.Command(commandParam.ToArray());
560

    
561
                List<long> newHandles = GetAllBlockHandlesByName(insertSymbolName);
562
                List<long> otherHandles = new List<long>();
563
                foreach (var item in newHandles)
564
                    if (!prevHandles.Contains(item))
565
                        otherHandles.Add(item);
566

    
567
                if (otherHandles.Count == 1)
568
                    return otherHandles[0];
569
                else
570
                    return 0;
571
            }
572
            catch (System.Exception ex)
573
            {
574

    
575
            }
576

    
577
            return handle;
578
        }
579
        private void DrawText(double x, double y, double height, string text, double rotation)
580
        {
581
            // Get the current document and database
582
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
583
            Database acCurDb = acDoc.Database;
584

    
585
            // Start a transaction
586
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
587
            {
588
                // Open the Block table for read
589
                BlockTable acBlkTbl;
590
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
591
                                                OpenMode.ForRead) as BlockTable;
592

    
593
                // Open the Block table record Model space for write
594
                BlockTableRecord acBlkTblRec;
595
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
596
                                                OpenMode.ForWrite) as BlockTableRecord;
597

    
598
                // Create a single-line text object
599
                using (DBText acText = new DBText())
600
                {
601
                    acText.Position = new Point3d(x, y, 0);
602
                    acText.Height = height;
603
                    acText.TextString = text;
604
                    acText.Rotation = rotation;
605

    
606
                    acBlkTblRec.AppendEntity(acText);
607
                    acTrans.AddNewlyCreatedDBObject(acText, true);
608
                }
609

    
610
                // Save the changes and dispose of the transaction
611
                acTrans.Commit();
612
            }
613
        }
614
        #endregion
615

    
616
        #region Autocad Utils
617
        private List<long> GetAllBlockHandlesByName(string name)
618
        {
619
            List<long> handles = new List<long>();
620

    
621
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
622
            Database acCurDb = acDoc.Database;
623
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
624
            {
625
                BlockTable gd = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
626
                foreach (var entry in gd)
627
                {
628
                    BlockTableRecord blockTableRecord = acTrans.GetObject(entry, OpenMode.ForRead, true) as BlockTableRecord;
629
                    if (blockTableRecord != null)
630
                    {
631
                        IEnumerable<BlockReference> records = AcDbLinqExtensionMethods.GetBlockReferences(blockTableRecord);
632
                        foreach (var item in records)
633
                        {
634
                            if (item.Name == name)
635
                                handles.Add(item.Handle.Value);
636
                        }
637
                    }
638
                }
639
                    
640
                acTrans.Commit();
641
            }
642
            return handles;
643
        }
644
        private List<long> GetAllGroupHandles()
645
        {
646
            List<long> handles = new List<long>();
647

    
648
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
649
            Database acCurDb = acDoc.Database;
650
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
651
            {
652
                DBDictionary gd = (DBDictionary)acTrans.GetObject(acCurDb.GroupDictionaryId, OpenMode.ForRead);
653
                foreach (var entry in gd)
654
                    handles.Add(entry.Value.Handle.Value);
655
                acTrans.Commit();
656
            }
657
            return handles;
658
        }
659
        private ObjectId GetFirstPolyLineObjectId(long groupHandle)
660
        {
661
            ObjectId result = ObjectId.Null;
662

    
663
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
664
            Database acCurDb = acDoc.Database;
665
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
666
            {
667
                DBDictionary gd = (DBDictionary)acTrans.GetObject(acCurDb.GroupDictionaryId, OpenMode.ForRead);
668
                foreach (var entry in gd)
669
                {
670
                    if (entry.Value.Handle.Value == groupHandle)
671
                    {
672
                        Autodesk.AutoCAD.DatabaseServices.Group group = acTrans.GetObject(entry.Value, OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.Group;
673
                        foreach (var item in group.GetAllEntityIds())
674
                        {
675
                            if (acTrans.GetObject(item, OpenMode.ForRead).GetType() == typeof(Autodesk.AutoCAD.DatabaseServices.Polyline))
676
                            {
677
                                result = item;
678
                                break;
679
                            }
680
                        }
681
                        break;
682
                    }
683
                }
684
                acTrans.Commit();
685
            }
686

    
687
            return result;
688
        }
689
        private void SetBlockReferenceRotation(ObjectId objectId, double rotation)
690
        {
691
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
692
            Database acCurDb = acDoc.Database;
693
            Editor acDocEd = acDoc.Editor;
694

    
695
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
696
            {
697
                DBObject objDB = acTrans.GetObject(objectId, OpenMode.ForWrite);
698
                if (objDB != null)
699
                {
700
                    if (objDB.GetType() == typeof(BlockReference))
701
                    {
702
                        BlockReference block = objDB as BlockReference;
703
                        block.Rotation = rotation;
704
                    }
705
                }
706
                acTrans.Commit();
707
            }
708
        }
709
        #endregion
710

    
711
        #region For Aveva
712
        private void SetAttributeByAvevaForm(long handle, List<Tuple<string, string>> datas)
713
        {
714
            Entity entity = APIDUtils.GetEntityByHandle(handle);
715

    
716
            ComponentPropertiesHelper componentPropertiesHelper = new ComponentPropertiesHelper();
717
            AvevaThread.Run(ThreadType.AddProperty, datas);
718
            if (!componentPropertiesHelper.DisplayComponentProperties(entity))
719
                AvevaThread.Stop(ThreadType.AddProperty);
720
        }
721
        #endregion
722

    
723
        #region Modeling Utils
724
        private void GetConnectedGroupLine(Model.Line line, List<Model.Line> group, bool isInsert)
725
        {
726
            if (!group.Contains(line))
727
            {
728
                if (isInsert)
729
                    group.Insert(0, line);
730
                else
731
                    group.Add(line);
732

    
733
                if (line.CONNECTORS[0].ConnectedObject != null && !IsExistEndBreak(line, line.CONNECTORS[0].ConnectedObject))
734
                {
735
                    object connObj = line.CONNECTORS[0].ConnectedObject;
736
                    if (connObj.GetType() == typeof(Model.Line) &&
737
                        APIDUtils.IsConnectedLine(connObj as Model.Line, line))
738
                        GetConnectedGroupLine(connObj as Model.Line, group, true);
739
                    else if (connObj.GetType() == typeof(Model.Symbol))
740
                    {
741
                        Model.Line connLine = FindOtherLineByRun(line, connObj as Symbol);
742
                        if (connLine != null)
743
                            GetConnectedGroupLine(connLine as Model.Line, group, true);
744
                    }
745
                }
746
                if (line.CONNECTORS[1].ConnectedObject != null && !IsExistEndBreak(line, line.CONNECTORS[1].ConnectedObject))
747
                {
748
                    object connObj = line.CONNECTORS[1].ConnectedObject;
749
                    if (connObj.GetType() == typeof(Model.Line) &&
750
                        APIDUtils.IsConnectedLine(connObj as Model.Line, line))
751
                        GetConnectedGroupLine(connObj as Model.Line, group, false);
752
                    else if (connObj.GetType() == typeof(Model.Symbol))
753
                    {
754
                        Model.Line connLine = FindOtherLineByRun(line, connObj as Symbol);
755
                        if (connLine != null)
756
                            GetConnectedGroupLine(connLine as Model.Line, group, false);
757
                    }
758
                }
759
            }
760
        }
761
        private void GetGroupLinePoints(List<Model.Line> groupLine, List<string> points)
762
        {
763
            for (int i = 0; i < groupLine.Count; i++)
764
            {
765
                Model.Line line = groupLine[i];
766
                if (i == 0)
767
                {
768
                    object connObj = line.CONNECTORS[0].ConnectedObject;
769
                    if (connObj != null)
770
                    {
771
                        string point = GetPointByConnectedItem(connObj, line, true);
772
                        if (string.IsNullOrEmpty(point))
773
                            points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
774
                        else
775
                            points.Add(point);
776
                    }
777
                    else
778
                        points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
779
                }
780
                else
781
                {
782
                    Model.Line prevLine = groupLine[i - 1];
783
                    if (line.SlopeType == SlopeType.HORIZONTAL &&
784
                        prevLine.SlopeType == SlopeType.VERTICAL)
785
                        points.Add(prevLine.Aveva.End_X + "," + line.Aveva.Start_Y);
786
                    else if (line.SlopeType == SlopeType.VERTICAL &&
787
                        prevLine.SlopeType == SlopeType.HORIZONTAL)
788
                        points.Add(line.Aveva.Start_X + "," + prevLine.Aveva.End_Y);
789
                    else
790
                        points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
791
                }
792

    
793
                if (i == groupLine.Count - 1)
794
                {
795
                    object connObj = line.CONNECTORS[1].ConnectedObject;
796
                    if (connObj != null)
797
                    {
798
                        string point = GetPointByConnectedItem(connObj, line, false);
799
                        if (string.IsNullOrEmpty(point))
800
                            points.Add(line.Aveva.End_X + "," + line.Aveva.End_Y);
801
                        else
802
                            points.Add(point);
803
                    }
804
                    else
805
                        points.Add(line.Aveva.End_X + "," + line.Aveva.End_Y);
806
                }
807
            }
808
        }
809
        private void CoordinateCorrection(List<Model.Line> groupLine)
810
        {
811
            for (int i = 0; i < groupLine.Count; i++)
812
            {
813
                Model.Line line = groupLine[i];
814
                Model.Line line2 = null;
815
                if (i + 1 < groupLine.Count)
816
                    line2 = groupLine[i + 1];
817

    
818
                if (line2 != null)
819
                {
820
                    if (APIDUtils.IsConnectedLine(line, line2))
821
                    {
822
                        #region ConnLine corrdinate
823
                        if (line.SlopeType == SlopeType.HORIZONTAL && line2.SlopeType == SlopeType.VERTICAL)
824
                        {
825
                            line2.Aveva.Start_X = line.Aveva.End_X;
826
                            line2.Aveva.End_X = line.Aveva.End_X;
827
                        }
828
                        else if (line.SlopeType == SlopeType.VERTICAL && line2.SlopeType == SlopeType.HORIZONTAL)
829
                        {
830
                            line2.Aveva.Start_Y = line.Aveva.End_Y;
831
                            line2.Aveva.End_Y = line.Aveva.End_Y;
832
                        }
833
                        else if (line.SlopeType == SlopeType.HORIZONTAL && line2.SlopeType == SlopeType.HORIZONTAL)
834
                        {
835
                            line2.Aveva.Start_Y = line.Aveva.End_Y;
836
                            line2.Aveva.End_Y = line.Aveva.End_Y;
837
                        }
838
                        else if (line.SlopeType == SlopeType.VERTICAL && line2.SlopeType == SlopeType.VERTICAL)
839
                        {
840
                            line2.Aveva.Start_X = line.Aveva.End_X;
841
                            line2.Aveva.End_X = line.Aveva.End_X;
842
                        }
843
                        #endregion
844
                    }
845
                    else
846
                    {
847
                        SlopeType slopeType = APIDUtils.CalcSlope(line.Aveva.End_X, line.Aveva.End_Y, line2.Aveva.Start_X, line2.Aveva.Start_Y);
848
                        #region corrdinate
849
                        if (slopeType == SlopeType.HORIZONTAL && line.SlopeType == SlopeType.HORIZONTAL && line2.SlopeType == SlopeType.HORIZONTAL)
850
                        {
851
                            line2.Aveva.Start_Y = line.Aveva.End_Y;
852
                            line2.Aveva.End_Y = line.Aveva.End_Y;
853
                        }
854
                        else if (slopeType == SlopeType.VERTICAL && line.SlopeType == SlopeType.VERTICAL && line2.SlopeType == SlopeType.VERTICAL)
855
                        {
856
                            line2.Aveva.Start_X = line.Aveva.End_X;
857
                            line2.Aveva.End_X = line.Aveva.End_X;
858
                        }
859
                        #endregion
860

    
861
                    }
862
                }
863

    
864
                if (line.SlopeType == SlopeType.HORIZONTAL || line.SlopeType == SlopeType.VERTICAL)
865
                {
866
                    foreach (var connector in line.CONNECTORS.FindAll(loop => loop.ConnectedObject != null))
867
                    {
868
                        double lineX = 0;
869
                        double lineY = 0;
870
                        int index = line.CONNECTORS.IndexOf(connector);
871
                        if (index == 0)
872
                        {
873
                            lineX = line.Aveva.End_X;
874
                            lineY = line.Aveva.End_Y;
875
                        }
876
                        else
877
                        {
878
                            lineX = line.Aveva.Start_X;
879
                            lineY = line.Aveva.Start_Y;
880
                        }
881
                        System.Type type = connector.ConnectedObject.GetType();
882
                        if (type == typeof(Model.Symbol))
883
                        {
884
                            Symbol item = connector.ConnectedObject as Symbol;
885
                            SlopeType slopeType = APIDUtils.CalcSlope(item.Aveva.X, item.Aveva.Y, lineX, lineY);
886
                            if (slopeType == line.SlopeType)
887
                            {
888
                                if (line.SlopeType == SlopeType.HORIZONTAL)
889
                                    item.Aveva.Y = line.Aveva.End_Y;
890
                                else if (line.SlopeType == SlopeType.VERTICAL)
891
                                    item.Aveva.X = line.Aveva.End_X;
892
                            }
893
                        }
894
                        else if (type == typeof(OPC))
895
                        {
896
                            OPC item = connector.ConnectedObject as OPC;
897
                            SlopeType slopeType = APIDUtils.CalcSlope(item.Aveva.X, item.Aveva.Y, lineX, lineY);
898
                            if (slopeType == line.SlopeType)
899
                            {
900
                                if (line.SlopeType == SlopeType.HORIZONTAL)
901
                                    item.Aveva.Y = line.Aveva.End_Y;
902
                                else if (line.SlopeType == SlopeType.VERTICAL)
903
                                    item.Aveva.X = line.Aveva.End_X;
904
                            }
905
                        }
906
                    }
907
                }
908
            }
909
        }
910
        private string GetPointByConnectedItem(object connObj, Model.Line line, bool isStart)
911
        {
912
            string result = string.Empty;
913
            double x;
914
            double y;
915
            if (isStart)
916
            {
917
                x = line.Aveva.Start_X;
918
                y = line.Aveva.Start_Y;
919
            }
920
            else
921
            {
922
                x = line.Aveva.End_X;
923
                y = line.Aveva.End_Y;
924
            }
925

    
926
            if (connObj.GetType() == typeof(Symbol))
927
            {
928
                Symbol connSymbol = connObj as Symbol;
929
                Connector connector = connSymbol.CONNECTORS.Find(loop => loop.ConnectedObject == line);
930

    
931
                SlopeType slopeType = APIDUtils.CalcSlope(connSymbol.X, connSymbol.Y, connector.X, connector.Y);
932
                if (slopeType == SlopeType.HORIZONTAL)
933
                    result = connSymbol.Aveva.X + "," + y;
934
                else if (slopeType == SlopeType.VERTICAL)
935
                    result = x + "," + connSymbol.Aveva.Y;
936
                else
937
                    result = x + "," + y;
938
            }
939
            else if (connObj.GetType() == typeof(OPC))
940
            {
941
                OPC connOPC = connObj as OPC;
942
                Connector connector = connOPC.CONNECTORS.Find(loop => loop.ConnectedObject == line);
943

    
944
                double locX = 0, locY = 0, sizeWidth = 0, sizeHeight = 0, aX = 0, aY = 0;
945
                APIDUtils.ConvertPointBystring(connOPC.LOCATION, ref locX, ref locY);
946
                APIDUtils.ConvertPointBystring(connOPC.SIZE, ref sizeWidth, ref sizeHeight);
947
                locX = locX + sizeWidth / 2;
948
                locY = locY + sizeHeight / 2;
949
                aX = locX;
950
                aY = locY;
951
                document.ConvertAvevaPoint(ref aX, ref aY);
952

    
953
                SlopeType slopeType = APIDUtils.CalcSlope(locX, locY, connector.X, connector.Y);
954
                if (slopeType == SlopeType.HORIZONTAL)
955
                    result = aX + "," + y;
956
                else if (slopeType == SlopeType.VERTICAL)
957
                    result = x + "," + aY;
958
                else
959
                    result = x + "," + y;
960
            }
961
            
962
            return result;
963
        }
964
        private bool IsExistEndBreak(object item1, object item2)
965
        {
966
            bool result = false;
967
            if (item1 != null && item2 != null)
968
            {
969
                EndBreak endBreak = document.EndBreaks.Find(x =>
970
            (APIDUtils.FindObjectByUID(document, x.OWNER) == item1 &&
971
            APIDUtils.FindObjectByUID(document, x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE) == item2) ||
972
            (APIDUtils.FindObjectByUID(document, x.OWNER) == item2 &&
973
            APIDUtils.FindObjectByUID(document, x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE) == item1));
974

    
975
                if (endBreak != null)
976
                    result = true;
977
            }
978

    
979
            return result;
980
        }
981
        private LineRun FindLineRun(Model.Line line)
982
        {
983
            List<LineRun> allLineRun = new List<LineRun>();
984
            foreach (var item in document.LINENUMBERS)
985
                allLineRun.AddRange(item.RUNS);
986
            foreach (var item in document.TRIMLINES)
987
                allLineRun.AddRange(item.RUNS);
988

    
989
            return allLineRun.Find(x => x.RUNITEMS.Contains(line));
990
        }
991
        private Model.Line FindOtherLineByRun(Model.Line line, Symbol symbol)
992
        {
993
            Model.Line result = null;
994
            LineRun run = FindLineRun(line);
995
            Connector connector = symbol.CONNECTORS.Find(x =>
996
            x.ConnectedObject != null &&
997
            x.ConnectedObject != line &&
998
            run.RUNITEMS.Contains(x.ConnectedObject) &&
999
            x.ConnectedObject.GetType() == typeof(Model.Line));
1000

    
1001
            if (connector != null)
1002
                result = connector.ConnectedObject as Model.Line;
1003
            
1004
            return result;
1005
        }
1006
        private bool CheckAngle(DataRow symbolRow)
1007
        {
1008
            return int.Parse(symbolRow["Insert_Points"].ToString()).Equals(2);
1009
        }
1010
        private bool CheckBalloon(Symbol symbol)
1011
        {
1012
            bool result = false;
1013

    
1014
            string text = string.Empty;
1015
            Hashtable symbolDefinitions = GraphicsUtility.GetSymbolDefinitions(symbol.Aveva.Name);
1016
            if (symbolDefinitions.Count != 0)
1017
            {
1018
                text = symbolDefinitions[SymbolDefinition.symAflowType].ToString().ToUpper();
1019

    
1020
                if (text.Equals("VLP"))
1021
                    text = "VPO";
1022
                else if (text.Equals("IVP"))
1023
                    text = "IPO";
1024

    
1025
                if (SymbolCategory.astrLabelBalloonBlockNames.Contains(text))
1026
                    result = true;//dumbDwgUpgrade.addLabelBalloon(symbolForInsertion, objectId);
1027
            }
1028

    
1029
            return result;
1030
        }
1031
        private double RadianToDegree(double angle)
1032
        {
1033
            return angle * (180.0 / Math.PI);
1034
        }
1035
        #endregion
1036

    
1037
        #region Test Source
1038
        public void test()
1039
        {
1040

    
1041
        }
1042
        public static void TESTStatic(long handle)
1043
        {
1044

    
1045
        }
1046
        #endregion
1047
    }
1048

    
1049

    
1050
    public static class AcDbLinqExtensionMethods
1051
    {
1052
        /// <summary>
1053
        /// Get all references to the given BlockTableRecord, including 
1054
        /// references to anonymous dynamic BlockTableRecords.
1055
        /// </summary>
1056

    
1057
        public static IEnumerable<BlockReference> GetBlockReferences(
1058
           this BlockTableRecord btr,
1059
           OpenMode mode = OpenMode.ForRead,
1060
           bool directOnly = true)
1061
        {
1062
            if (btr == null)
1063
                throw new ArgumentNullException("btr");
1064
            var tr = btr.Database.TransactionManager.TopTransaction;
1065
            if (tr == null)
1066
                throw new InvalidOperationException("No transaction");
1067
            var ids = btr.GetBlockReferenceIds(directOnly, true);
1068
            int cnt = ids.Count;
1069
            for (int i = 0; i < cnt; i++)
1070
            {
1071
                yield return (BlockReference)
1072
                   tr.GetObject(ids[i], mode, false, false);
1073
            }
1074
            if (btr.IsDynamicBlock)
1075
            {
1076
                BlockTableRecord btr2 = null;
1077
                var blockIds = btr.GetAnonymousBlockIds();
1078
                cnt = blockIds.Count;
1079
                for (int i = 0; i < cnt; i++)
1080
                {
1081
                    btr2 = (BlockTableRecord)tr.GetObject(blockIds[i],
1082
                       OpenMode.ForRead, false, false);
1083
                    ids = btr2.GetBlockReferenceIds(directOnly, true);
1084
                    int cnt2 = ids.Count;
1085
                    for (int j = 0; j < cnt2; j++)
1086
                    {
1087
                        yield return (BlockReference)
1088
                           tr.GetObject(ids[j], mode, false, false);
1089
                    }
1090
                }
1091
            }
1092
        }
1093
    }
1094
}
클립보드 이미지 추가 (최대 크기: 500 MB)