프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / APIDConverter / AutoModeling.cs @ d03dde83

이력 | 보기 | 이력해설 | 다운로드 (39.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.LineNumberModeling, null);
240
                        break;
241
                    }
242
                }
243
            }
244

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
348
        }
349
        private void SetLineNumberAttribute(Model.LineNumber lineNumber)
350
        {
351
            Model.Line line = APIDUtils.FindObjectByUID(document, lineNumber.CONNLINE) as Model.Line;
352
            if (line != null && line.Aveva.Handle != 0)
353
            {
354
                List<Tuple<string, string>> datas = new List<Tuple<string, string>>();
355
                foreach (Model.Attribute attribute in lineNumber.ATTRIBUTES)
356
                {
357
                    AttributeInfo info = avevaInfo.AttributeInfo.Find(x => x.UID == attribute.UID);
358
                    if (info != null && !string.IsNullOrEmpty(info.APID_ATTRIBUTE))
359
                    {
360
                        if (info.APID_ATTRIBUTE_TYPE == AvevaAttributeType.UDA)
361
                            datas.Add(new Tuple<string, string>("UDA" + info.APID_ATTRIBUTE, attribute.VALUE));
362
                        else
363
                            datas.Add(new Tuple<string, string>(info.APID_ATTRIBUTE, attribute.VALUE));
364
                    }
365
                }
366
                if (datas.Count > 0)
367
                {
368
                    ObjectId objectId = GetFirstPolyLineObjectId(line.Aveva.Handle);
369
                    if (!objectId.IsNull)
370
                        SetAttributeByAvevaForm(objectId.Handle.Value, datas);
371
                }
372
            }
373
        }
374
        private void SetSymbolAttribute(Model.Symbol symbol)
375
        {
376
            if (symbol.Aveva.Handle != 0)
377
            {
378
                List<Tuple<string, string>> datas = new List<Tuple<string, string>>();
379
                foreach (var attribute in symbol.ATTRIBUTES)
380
                {
381
                    AttributeInfo info = avevaInfo.AttributeInfo.Find(x => x.UID == attribute.UID);
382
                    if (info != null && !string.IsNullOrEmpty(info.APID_ATTRIBUTE))
383
                    {
384
                        if (info.APID_ATTRIBUTE_TYPE == AvevaAttributeType.UDA)
385
                            datas.Add(new Tuple<string, string>("UDA" + info.APID_ATTRIBUTE, attribute.VALUE));
386
                        else
387
                            datas.Add(new Tuple<string, string>(info.APID_ATTRIBUTE, attribute.VALUE));
388
                    }
389
                }
390
                if (datas.Count > 0)
391
                {
392
                    ObjectId objectId = APIDUtils.GetObjectIdByHandle(symbol.Aveva.Handle);
393
                    if (!objectId.IsNull)
394
                        SetAttributeByAvevaForm(objectId.Handle.Value, datas);
395
                }
396
            }
397
        }
398
        #endregion
399

    
400
        #region Drawing Method
401
        private long DrawPipe(string style, List<string> coordinates, LineNumber lineNumber = null)
402
        {
403
            List<long> prevHandles = GetAllGroupHandles();
404

    
405
            GUIUtils.SetPipeStyle(style);
406
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
407
            Editor editor = acDoc.Editor;
408
            List<object> commandParam = new List<object>();
409
            //command name
410
            commandParam.Add("DRPIPE");
411
            //coordinate
412
            foreach (var item in coordinates)
413
                commandParam.Add(item);
414

    
415
            //enter Parent(null)
416
            commandParam.Add(null);
417

    
418
            if (lineNumber != null)
419
            {
420
                Point3d point = new Point3d(lineNumber.Aveva.X, lineNumber.Aveva.Y, 0);
421
                commandParam.Add(point);
422
                commandParam.Add(lineNumber.Aveva.Angle);
423

    
424
                commandParam.Add(null);
425
            }
426
            else
427
                commandParam.Add(null);
428

    
429
            editor.Command(commandParam.ToArray());
430

    
431
            List<long> newHandles = GetAllGroupHandles();
432
            List<long> otherHandles = new List<long>();
433
            foreach (var item in newHandles)
434
                if (!prevHandles.Contains(item))
435
                    otherHandles.Add(item);
436

    
437
            if (otherHandles.Count == 1)
438
                return otherHandles[0];
439
            else
440
                return 0;
441
        }
442
        private long DrawPipe(string style, List<string> coordinates, ObjectId objectId)
443
        {
444
            List<long> prevHandles = GetAllGroupHandles();
445
            GUIUtils.SetPipeStyle(style);
446

    
447
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
448
            Editor editor = acDoc.Editor;
449
            List<object> commandParam = new List<object>();
450
            //command name
451
            commandParam.Add("DRPIPE");
452
            //coordinate
453
            foreach (var item in coordinates)
454
                commandParam.Add(item);
455
            //enter
456
            commandParam.Add(null);
457

    
458
            //Input Object ID
459
            commandParam.Add(objectId);
460

    
461
            //enter
462
            commandParam.Add(null);
463

    
464
            editor.Command(commandParam.ToArray());
465

    
466
            List<long> newHandles = GetAllGroupHandles();
467
            List<long> otherHandles = new List<long>();
468
            foreach (var item in newHandles)
469
                if (!prevHandles.Contains(item))
470
                    otherHandles.Add(item);
471

    
472
            if (otherHandles.Count == 1)
473
                return otherHandles[0];
474
            else
475
                return 0;
476
        }
477
        private long DrawSignal(string style, List<string> coordinates)
478
        {
479
            List<long> prevHandles = GetAllGroupHandles();
480

    
481
            GUIUtils.SetPipeStyle(style);
482
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
483
            Editor editor = acDoc.Editor;
484
            List<object> commandParam = new List<object>();
485
            //command name
486
            commandParam.Add("VPESIGNAL");
487
            //coordinate
488
            foreach (var item in coordinates)
489
                commandParam.Add(item);
490
            //enter
491
            commandParam.Add(null);
492

    
493
            editor.Command(commandParam.ToArray());
494

    
495
            List<long> newHandles = GetAllGroupHandles();
496
            List<long> otherHandles = new List<long>();
497
            foreach (var item in newHandles)
498
                if (!prevHandles.Contains(item))
499
                    otherHandles.Add(item);
500

    
501
            if (otherHandles.Count == 1)
502
                return otherHandles[0];
503
            else
504
                return 0;
505
        }
506
        private long InsertSymbol(Symbol symbol, DataRow symbolRow, bool needAngle, bool needBalloon)
507
        {
508
            long handle = 0;
509
            try
510
            {
511
                string insertSymbolName = symbol.Aveva.Name;
512
                double x = symbol.Aveva.X;
513
                double y = symbol.Aveva.Y;
514

    
515
                List<long> prevHandles = GetAllBlockHandlesByName(insertSymbolName);
516

    
517
                AVEVA.PID.Utilities.DrawingData drawingData = new AVEVA.PID.Utilities.DrawingData();
518
                drawingData.InsertSymbolName = insertSymbolName;
519
                Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
520
                Editor editor = acDoc.Editor;
521
                List<object> commandParam = new List<object>();
522
                commandParam.Add("INSSYM");
523

    
524
                // Insert Point
525
                Point3d point = new Point3d(x, y, 0);
526
                commandParam.Add(point);
527

    
528
                // Check Insert Point
529
                if (needAngle)
530
                    commandParam.Add(symbol.ANGLE);
531

    
532
                // Check Balloon
533
                if (needBalloon)
534
                {
535
                    point = new Point3d(x + 20, y + 20, 0);
536
                    commandParam.Add(point);
537
                    
538
                    // Check LeaderLine
539
                    if (GraphicalUtility.IsLeaderReqOnSymbolBalloons())
540
                        commandParam.Add(x + "," + y);
541
                }
542

    
543
                for (int i = 0; i < 8; i++)
544
                    commandParam.Add(null);
545

    
546
                editor.Command(commandParam.ToArray());
547

    
548
                List<long> newHandles = GetAllBlockHandlesByName(insertSymbolName);
549
                List<long> otherHandles = new List<long>();
550
                foreach (var item in newHandles)
551
                    if (!prevHandles.Contains(item))
552
                        otherHandles.Add(item);
553

    
554
                if (otherHandles.Count == 1)
555
                    return otherHandles[0];
556
                else
557
                    return 0;
558
            }
559
            catch (System.Exception ex)
560
            {
561

    
562
            }
563

    
564
            return handle;
565
        }
566
        private void DrawText(double x, double y, double height, string text, double rotation)
567
        {
568
            // Get the current document and database
569
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
570
            Database acCurDb = acDoc.Database;
571

    
572
            // Start a transaction
573
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
574
            {
575
                // Open the Block table for read
576
                BlockTable acBlkTbl;
577
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
578
                                                OpenMode.ForRead) as BlockTable;
579

    
580
                // Open the Block table record Model space for write
581
                BlockTableRecord acBlkTblRec;
582
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
583
                                                OpenMode.ForWrite) as BlockTableRecord;
584

    
585
                // Create a single-line text object
586
                using (DBText acText = new DBText())
587
                {
588
                    acText.Position = new Point3d(x, y, 0);
589
                    acText.Height = height;
590
                    acText.TextString = text;
591
                    acText.Rotation = rotation;
592

    
593
                    acBlkTblRec.AppendEntity(acText);
594
                    acTrans.AddNewlyCreatedDBObject(acText, true);
595
                }
596

    
597
                // Save the changes and dispose of the transaction
598
                acTrans.Commit();
599
            }
600
        }
601
        #endregion
602

    
603
        #region Autocad Utils
604
        private List<long> GetAllBlockHandlesByName(string name)
605
        {
606
            List<long> handles = new List<long>();
607

    
608
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
609
            Database acCurDb = acDoc.Database;
610
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
611
            {
612
                BlockTable gd = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
613
                foreach (var entry in gd)
614
                {
615
                    BlockTableRecord blockTableRecord = acTrans.GetObject(entry, OpenMode.ForRead, true) as BlockTableRecord;
616
                    if (blockTableRecord != null)
617
                    {
618
                        IEnumerable<BlockReference> records = AcDbLinqExtensionMethods.GetBlockReferences(blockTableRecord);
619
                        foreach (var item in records)
620
                        {
621
                            if (item.Name == name)
622
                                handles.Add(item.Handle.Value);
623
                        }
624
                    }
625
                }
626
                    
627
                acTrans.Commit();
628
            }
629
            return handles;
630
        }
631
        private List<long> GetAllGroupHandles()
632
        {
633
            List<long> handles = new List<long>();
634

    
635
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
636
            Database acCurDb = acDoc.Database;
637
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
638
            {
639
                DBDictionary gd = (DBDictionary)acTrans.GetObject(acCurDb.GroupDictionaryId, OpenMode.ForRead);
640
                foreach (var entry in gd)
641
                    handles.Add(entry.Value.Handle.Value);
642
                acTrans.Commit();
643
            }
644
            return handles;
645
        }
646
        private ObjectId GetFirstPolyLineObjectId(long groupHandle)
647
        {
648
            ObjectId result = ObjectId.Null;
649

    
650
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
651
            Database acCurDb = acDoc.Database;
652
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
653
            {
654
                DBDictionary gd = (DBDictionary)acTrans.GetObject(acCurDb.GroupDictionaryId, OpenMode.ForRead);
655
                foreach (var entry in gd)
656
                {
657
                    if (entry.Value.Handle.Value == groupHandle)
658
                    {
659
                        Autodesk.AutoCAD.DatabaseServices.Group group = acTrans.GetObject(entry.Value, OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.Group;
660
                        foreach (var item in group.GetAllEntityIds())
661
                        {
662
                            if (acTrans.GetObject(item, OpenMode.ForRead).GetType() == typeof(Autodesk.AutoCAD.DatabaseServices.Polyline))
663
                            {
664
                                result = item;
665
                                break;
666
                            }
667
                        }
668
                        break;
669
                    }
670
                }
671
                acTrans.Commit();
672
            }
673

    
674
            return result;
675
        }
676
        private void SetBlockReferenceRotation(ObjectId objectId, double rotation)
677
        {
678
            Autodesk.AutoCAD.ApplicationServices.Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
679
            Database acCurDb = acDoc.Database;
680
            Editor acDocEd = acDoc.Editor;
681

    
682
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
683
            {
684
                DBObject objDB = acTrans.GetObject(objectId, OpenMode.ForWrite);
685
                if (objDB != null)
686
                {
687
                    if (objDB.GetType() == typeof(BlockReference))
688
                    {
689
                        BlockReference block = objDB as BlockReference;
690
                        block.Rotation = rotation;
691
                    }
692
                }
693
                acTrans.Commit();
694
            }
695
        }
696
        #endregion
697

    
698
        #region For Aveva
699
        private void SetAttributeByAvevaForm(long handle, List<Tuple<string, string>> datas)
700
        {
701
            Entity entity = APIDUtils.GetEntityByHandle(handle);
702

    
703
            ComponentPropertiesHelper componentPropertiesHelper = new ComponentPropertiesHelper();
704
            AvevaThread.Run(ThreadType.AddProperty, datas);
705
            if (!componentPropertiesHelper.DisplayComponentProperties(entity))
706
                AvevaThread.Stop(ThreadType.AddProperty);
707
        }
708
        #endregion
709

    
710
        #region Modeling Utils
711
        private void GetConnectedGroupLine(Model.Line line, List<Model.Line> group, bool isInsert)
712
        {
713
            if (!group.Contains(line))
714
            {
715
                if (isInsert)
716
                    group.Insert(0, line);
717
                else
718
                    group.Add(line);
719

    
720
                if (line.CONNECTORS[0].ConnectedObject != null && !IsExistEndBreak(line, line.CONNECTORS[0].ConnectedObject))
721
                {
722
                    object connObj = line.CONNECTORS[0].ConnectedObject;
723
                    if (connObj.GetType() == typeof(Model.Line) &&
724
                        APIDUtils.IsConnectedLine(connObj as Model.Line, line))
725
                        GetConnectedGroupLine(connObj as Model.Line, group, true);
726
                    else if (connObj.GetType() == typeof(Model.Symbol))
727
                    {
728
                        Model.Line connLine = FindOtherLineByRun(line, connObj as Symbol);
729
                        if (connLine != null)
730
                            GetConnectedGroupLine(connLine as Model.Line, group, true);
731
                    }
732
                }
733
                if (line.CONNECTORS[1].ConnectedObject != null && !IsExistEndBreak(line, line.CONNECTORS[1].ConnectedObject))
734
                {
735
                    object connObj = line.CONNECTORS[1].ConnectedObject;
736
                    if (connObj.GetType() == typeof(Model.Line) &&
737
                        APIDUtils.IsConnectedLine(connObj as Model.Line, line))
738
                        GetConnectedGroupLine(connObj as Model.Line, group, false);
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, false);
744
                    }
745
                }
746
            }
747
        }
748
        private void GetGroupLinePoints(List<Model.Line> groupLine, List<string> points)
749
        {
750
            for (int i = 0; i < groupLine.Count; i++)
751
            {
752
                Model.Line line = groupLine[i];
753
                if (i == 0)
754
                {
755
                    object connObj = line.CONNECTORS[0].ConnectedObject;
756
                    if (connObj != null)
757
                    {
758
                        string point = GetPointByConnectedItem(connObj, line, true);
759
                        if (string.IsNullOrEmpty(point))
760
                            points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
761
                        else
762
                            points.Add(point);
763
                    }
764
                    else
765
                        points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
766
                }
767
                else
768
                {
769
                    Model.Line prevLine = groupLine[i - 1];
770
                    if (line.SlopeType == SlopeType.HORIZONTAL &&
771
                        prevLine.SlopeType == SlopeType.VERTICAL)
772
                        points.Add(prevLine.Aveva.End_X + "," + line.Aveva.Start_Y);
773
                    else if (line.SlopeType == SlopeType.VERTICAL &&
774
                        prevLine.SlopeType == SlopeType.HORIZONTAL)
775
                        points.Add(line.Aveva.Start_X + "," + prevLine.Aveva.End_Y);
776
                    else
777
                        points.Add(line.Aveva.Start_X + "," + line.Aveva.Start_Y);
778
                }
779

    
780
                if (i == groupLine.Count - 1)
781
                {
782
                    object connObj = line.CONNECTORS[1].ConnectedObject;
783
                    if (connObj != null && connObj.GetType() == typeof(Symbol))
784
                    {
785
                        string point = GetPointByConnectedItem(connObj, line, false);
786
                        if (string.IsNullOrEmpty(point))
787
                            points.Add(line.Aveva.End_X + "," + line.Aveva.End_Y);
788
                        else
789
                            points.Add(point);
790
                    }
791
                    else
792
                        points.Add(line.Aveva.End_X + "," + line.Aveva.End_Y);
793
                }
794
            }
795
        }
796
        private string GetPointByConnectedItem(object connObj, Model.Line line, bool isStart)
797
        {
798
            string result = string.Empty;
799
            double x;
800
            double y;
801
            if (isStart)
802
            {
803
                x = line.Aveva.Start_X;
804
                y = line.Aveva.Start_Y;
805
            }
806
            else
807
            {
808
                x = line.Aveva.End_X;
809
                y = line.Aveva.End_Y;
810
            }
811

    
812
            if (connObj.GetType() == typeof(Symbol))
813
            {
814
                Symbol connSymbol = connObj as Symbol;
815
                Connector connector = connSymbol.CONNECTORS.Find(loop => loop.ConnectedObject == line);
816

    
817
                SlopeType slopeType = APIDUtils.CalcSlope(connSymbol.X, connSymbol.Y, connector.X, connector.Y);
818
                if (slopeType == SlopeType.HORIZONTAL)
819
                    result = connSymbol.Aveva.X + "," + y;
820
                else if (slopeType == SlopeType.VERTICAL)
821
                    result = x + "," + connSymbol.Aveva.Y;
822
                else
823
                    result = x + "," + y;
824
            }
825
            else if (connObj.GetType() == typeof(OPC))
826
            {
827
                OPC connOPC = connObj as OPC;
828
                Connector connector = connOPC.CONNECTORS.Find(loop => loop.ConnectedObject == line);
829

    
830
                double locX = 0, locY = 0, sizeWidth = 0, sizeHeight = 0, aX = 0, aY = 0;
831
                APIDUtils.ConvertPointBystring(connOPC.LOCATION, ref locX, ref locY);
832
                APIDUtils.ConvertPointBystring(connOPC.SIZE, ref sizeWidth, ref sizeHeight);
833
                locX = locX + sizeWidth / 2;
834
                locY = locY + sizeHeight / 2;
835
                aX = locX;
836
                aY = locY;
837
                document.ConvertAvevaPoint(ref aX, ref aY);
838

    
839
                SlopeType slopeType = APIDUtils.CalcSlope(locX, locY, connector.X, connector.Y);
840
                if (slopeType == SlopeType.HORIZONTAL)
841
                    result = aX + "," + y;
842
                else if (slopeType == SlopeType.VERTICAL)
843
                    result = x + "," + aY;
844
                else
845
                    result = x + "," + y;
846
            }
847
            
848
            return result;
849
        }
850
        private bool IsExistEndBreak(object item1, object item2)
851
        {
852
            bool result = false;
853
            if (item1 != null && item2 != null)
854
            {
855
                EndBreak endBreak = document.EndBreaks.Find(x =>
856
            (APIDUtils.FindObjectByUID(document, x.OWNER) == item1 &&
857
            APIDUtils.FindObjectByUID(document, x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE) == item2) ||
858
            (APIDUtils.FindObjectByUID(document, x.OWNER) == item2 &&
859
            APIDUtils.FindObjectByUID(document, x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE) == item1));
860

    
861
                if (endBreak != null)
862
                    result = true;
863
            }
864

    
865
            return result;
866
        }
867
        private LineRun FindLineRun(Model.Line line)
868
        {
869
            List<LineRun> allLineRun = new List<LineRun>();
870
            foreach (var item in document.LINENUMBERS)
871
                allLineRun.AddRange(item.RUNS);
872
            foreach (var item in document.TRIMLINES)
873
                allLineRun.AddRange(item.RUNS);
874

    
875
            return allLineRun.Find(x => x.RUNITEMS.Contains(line));
876
        }
877
        private Model.Line FindOtherLineByRun(Model.Line line, Symbol symbol)
878
        {
879
            Model.Line result = null;
880
            LineRun run = FindLineRun(line);
881
            Connector connector = symbol.CONNECTORS.Find(x =>
882
            x.ConnectedObject != null &&
883
            x.ConnectedObject != line &&
884
            run.RUNITEMS.Contains(x.ConnectedObject) &&
885
            x.ConnectedObject.GetType() == typeof(Model.Line));
886

    
887
            if (connector != null)
888
                result = connector.ConnectedObject as Model.Line;
889
            
890
            return result;
891
        }
892
        private bool CheckAngle(DataRow symbolRow)
893
        {
894
            return int.Parse(symbolRow["Insert_Points"].ToString()).Equals(2);
895
        }
896
        private bool CheckBalloon(Symbol symbol)
897
        {
898
            bool result = false;
899

    
900
            string text = string.Empty;
901
            Hashtable symbolDefinitions = GraphicsUtility.GetSymbolDefinitions(symbol.Aveva.Name);
902
            if (symbolDefinitions.Count != 0)
903
            {
904
                text = symbolDefinitions[SymbolDefinition.symAflowType].ToString().ToUpper();
905

    
906
                if (text.Equals("VLP"))
907
                    text = "VPO";
908
                else if (text.Equals("IVP"))
909
                    text = "IPO";
910

    
911
                if (SymbolCategory.astrLabelBalloonBlockNames.Contains(text))
912
                    result = true;//dumbDwgUpgrade.addLabelBalloon(symbolForInsertion, objectId);
913
            }
914

    
915
            return result;
916
        }
917
        #endregion
918

    
919
        #region Test Source
920
        public void test()
921
        {
922

    
923
        }
924
        public static void TESTStatic(long handle)
925
        {
926

    
927
        }
928
        #endregion
929
    }
930

    
931

    
932
    public static class AcDbLinqExtensionMethods
933
    {
934
        /// <summary>
935
        /// Get all references to the given BlockTableRecord, including 
936
        /// references to anonymous dynamic BlockTableRecords.
937
        /// </summary>
938

    
939
        public static IEnumerable<BlockReference> GetBlockReferences(
940
           this BlockTableRecord btr,
941
           OpenMode mode = OpenMode.ForRead,
942
           bool directOnly = true)
943
        {
944
            if (btr == null)
945
                throw new ArgumentNullException("btr");
946
            var tr = btr.Database.TransactionManager.TopTransaction;
947
            if (tr == null)
948
                throw new InvalidOperationException("No transaction");
949
            var ids = btr.GetBlockReferenceIds(directOnly, true);
950
            int cnt = ids.Count;
951
            for (int i = 0; i < cnt; i++)
952
            {
953
                yield return (BlockReference)
954
                   tr.GetObject(ids[i], mode, false, false);
955
            }
956
            if (btr.IsDynamicBlock)
957
            {
958
                BlockTableRecord btr2 = null;
959
                var blockIds = btr.GetAnonymousBlockIds();
960
                cnt = blockIds.Count;
961
                for (int i = 0; i < cnt; i++)
962
                {
963
                    btr2 = (BlockTableRecord)tr.GetObject(blockIds[i],
964
                       OpenMode.ForRead, false, false);
965
                    ids = btr2.GetBlockReferenceIds(directOnly, true);
966
                    int cnt2 = ids.Count;
967
                    for (int j = 0; j < cnt2; j++)
968
                    {
969
                        yield return (BlockReference)
970
                           tr.GetObject(ids[j], mode, false, false);
971
                    }
972
                }
973
            }
974
        }
975
    }
976
}
클립보드 이미지 추가 (최대 크기: 500 MB)