프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ 284fa2c9

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

1
using System;
2
using System.Collections.Generic;
3
using System.Data;
4
using System.IO;
5
using System.Linq;
6
using System.Text;
7
using System.Threading.Tasks;
8
using ID2PSN.Properties;
9
using System.Text.RegularExpressions;
10
using System.Windows.Forms;
11
using DevExpress.XtraSplashScreen;
12

    
13
namespace ID2PSN
14
{
15
    public enum PSNType
16
    {
17
        None,
18
        Branch,
19
        Equipment,
20
        Header,
21
        Symbol,
22
        OPC,
23
    }
24

    
25
    public enum ErrorType
26
    {
27
        Error = -1,
28
        OK,
29
        InValid //이값은 들어가는데가 없음..
30
    }
31

    
32
    public class PSN
33
    {
34
        private double[] DrawingSize = null;
35
        private double DrawingWidth = double.NaN;
36
        private double DrawingHeight = double.NaN;
37
        public int Revision;
38
        public string EquipTagNoAttributeName = string.Empty;
39
        public DataTable PathItems { get; set; }
40
        public DataTable SequenceData { get; set; }
41
        public DataTable PipeSystemNetwork { get; set; }
42
        public DataTable TopologySet { get; set; }
43
        public DataTable Equipment { get; set; }
44
        public DataTable Nozzle { get; set; }
45
        public DataTable PipeLine { get; set; }
46
        public DataTable PipeSystem { get; set; }
47

    
48
        public string Rule1 = "Missing LineNumber_1"; //Line Disconnected에서 변경
49
        public string Rule2 = "Missing LineNumber_2"; //Missing LineNumber에서 변경
50
        public string Rule3 = "OPC Disconnected";
51
        public string Rule4 = "Missing ItemTag or Description";
52
        public string Rule5 = "Line Disconnected";
53

    
54
        int tieInPointIndex = 1;
55

    
56
        List<Document> Documents;
57
        List<Group> groups = new List<Group>();
58
        List<PSNItem> PSNItems = new List<PSNItem>();
59
        List<Topology> Topologies = new List<Topology>();
60

    
61
        DataTable opcDT = null;
62
        DataTable topologyRuleDT = null;
63

    
64
        ID2Info id2Info = ID2Info.GetInstance();
65

    
66

    
67

    
68
        //const string FluidPriorityType = "FLUIDCODE";
69
        //const string PipingMaterialsPriorityType = "PIPINGMATERIALSCLASS";
70

    
71
        public PSN()
72
        {
73

    
74
        }
75

    
76
        public PSN(List<Document> documents, int Revision)
77
        {
78
            try
79
            {
80
                Documents = documents;
81
                foreach (Document document in Documents)
82
                    groups.AddRange(document.Groups);
83
                opcDT = GetOPCInfo();
84
                topologyRuleDT = GetTopologyRule();
85
                this.Revision = Revision;
86
                DrawingSize = DB.GetDrawingSize();
87
                if (DrawingSize == null)
88
                {
89
                    MessageBox.Show("There is no data whose Section is Area and Key is Drawing in the drawing table.", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
90
                    return;
91
                }
92
                DrawingWidth = DrawingSize[2] - DrawingSize[0];
93
                DrawingHeight = DrawingSize[3] - DrawingSize[1];
94
            }
95
            catch (Exception ex)
96
            {
97
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
98
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
99
            }
100
        }
101

    
102
        private string GetItemTag(Item item)
103
        {
104
            string result = string.Empty;
105
            if (item.ItemType == ItemType.Line)
106
                result = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
107
            else if (item.ItemType == ItemType.Symbol && item.SubItemType == SubItemType.Nozzle)
108
                result = Nozzle.Select(string.Format("OID = '{0}'", item.UID)).First()["ITEMTAG"].ToString();
109

    
110
            return result;
111
        }
112
        private string GetItemName(Item item, string itemOID)
113
        {
114
            string result = string.Empty;
115
            if (item.ItemType == ItemType.Line && (item.Name == "Secondary" || item.Name == "Primary"))
116
            {
117
                if (itemOID.Contains("_"))
118
                {
119
                    string split = itemOID.Split(new char[] { '_' })[1];
120
                    if (split.StartsWith("B"))
121
                        result = "Branch";
122
                    else
123
                        result = "PipeRun";
124
                }
125
                else
126
                    result = "PipeRun";
127
            }
128
            else if (item.ItemType == ItemType.Symbol)
129
            {
130
                if (item.ID2DBCategory == "Instrumentation")
131
                    result = "Instrument";
132
                else if (item.ID2DBType == "Nozzles")
133
                    result = "Nozzle";
134
                else if (item.ID2DBType == "Fittings" ||
135
                        item.ID2DBType == "Piping OPC's" ||
136
                        item.ID2DBType == "Specialty Components" ||
137
                        item.ID2DBType == "Valves" ||
138
                        item.ID2DBType == "Reducers")
139
                    result = "PipingComp";
140
            }
141
            return result;
142
        }
143

    
144
        private string GetClass(Item item, string itemOID)
145
        {
146
            string result = string.Empty;
147
            if (item.ItemType == ItemType.Line && (item.Name == "Secondary" || item.Name == "Primary"))
148
            {
149
                if (itemOID.Contains("_"))
150
                {
151
                    string split = itemOID.Split(new char[] { '_' })[1];
152
                    if (split.StartsWith("B"))
153
                        result = "Branch";
154
                    else
155
                        result = "Piping";
156
                }
157
                else
158
                    result = "Piping";
159
            }
160
            else if (item.ItemType == ItemType.Symbol)
161
            {
162
                if (item.ID2DBCategory == "Instrumentation")
163
                    result = item.ID2DBType;
164
                else if (item.ID2DBType == "Nozzles")
165
                    result = string.Empty;
166
                else if (item.ID2DBType == "Fittings" ||
167
                       item.ID2DBType == "Piping OPC's" ||
168
                       item.ID2DBType == "Specialty Components" ||
169
                       item.ID2DBType == "Valves" ||
170
                       item.ID2DBType == "Reducers")
171
                    result = item.ID2DBType;
172
            }
173
            return result;
174
        }
175

    
176
        private string GetSubClass(Item item, string itemOID)
177
        {
178
            string result = string.Empty;
179
            if (item.ItemType == ItemType.Line && (item.Name == "Secondary" || item.Name == "Primary"))
180
            {
181
                if (itemOID.Contains("_"))
182
                {
183
                    string split = itemOID.Split(new char[] { '_' })[1];
184
                    if (split.StartsWith("B"))
185
                        result = "Tee";
186
                    else
187
                        result = "";
188
                }
189
                else
190
                    result = "";
191
            }
192
            else if (item.ItemType == ItemType.Symbol)
193
            {
194
                if (item.ID2DBCategory == "Instrumentation")
195
                    result = string.Empty;
196
                else if (item.ID2DBType == "Nozzles")
197
                    result = string.Empty;
198
                else if (item.ID2DBType == "Fittings" ||
199
                       item.ID2DBType == "Piping OPC's" ||
200
                       item.ID2DBType == "Specialty Components" ||
201
                       item.ID2DBType == "Valves" ||
202
                       item.ID2DBType == "Reducers")
203
                    result = "In-line component";
204
            }
205
            return result;
206
        }
207

    
208
        public void SetPSNData(SplashScreenManager splashScreenManager1)
209
        {
210
            // Item들의 속성으로 Topology Data를 생성한다.
211
            // Topology Data는 Topology Rule Setting을 기준으로 생성한다.
212
            int i = 1;
213
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopologyData ( 3 % )");
214
            SetTopologyData();
215
            // ID2의 OPC연결 Data 기반으로 Group(도면단위 PSN)을 연결한다.
216
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  ConnectByOPC ( 5 % )");
217
            ConnectByOPC();
218
            // 실제 PSN 생성 로직
219
            // 연결된 Group을 하나의 PSN으로 만든다.
220
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNItem ( 10 % )");
221
            SetPSNItem();
222
            // 생성된 PSN의 Type을 설정한다.
223
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNType ( 15 % )");
224
            SetPSNType();
225
            // ID2에는 Branch 정보가 없어서 Branch 정보를 생성한다.
226
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetBranchInfo ( 20 % )");
227
            SetBranchInfo();
228
            // 생성된 Topology Data들을 정리하며 Main, Branch를 판단한다.
229
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopology ( 25 % )");
230
            SetTopology();
231
            // PSN이 Bypass인지 검사 
232
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNBypass ( 30 % )");
233
            SetPSNBypass();
234
            // Topology들에게 Index를 부여한다
235
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopologyIndex ( 35 % )");
236
            SetTopologyIndex();
237
            // Nozzle, Equipment의 정보를 저장
238
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SaveNozzleAndEquipment ( 40 % )");
239
            SaveNozzleAndEquipment();
240
            // PSN의 정보를 저장
241
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNData ( 45 % )");
242
            SavePSNData();
243
            // Update Keyword
244
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateKeywordForPSN ( 55 % )");
245
            UpdateKeywordForPSN();
246
          
247
            // Topology의 subtype을 update(bypass, Header, 등등) 
248
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateSubType ( 60 % )");
249
            UpdateSubType();
250
            // Update Error
251
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateErrorForPSN ( 65 % )");
252
            PathItemSorting();
253
            UpdateErrorForPSN();
254
            // Insert Tee
255
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  InsertTeePSN ( 70 % )");
256
            InsertTeePSN();
257
         
258
            // ValveGrouping
259
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateValveGrouping ( 75 % )");
260
            UpdateValveGrouping();
261

    
262
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  PathItemSorting ( 80 % )");
263
            PathItemSorting();
264

    
265
            // AirFinCooler 
266
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAirFinCooler ( 85 % )");
267
            UpdateAirFinCooler();
268

    
269
            // Vent/Drain PSN 데이터 제거
270
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  DeleteVentDrain ( 90 % )");
271
            DeleteVentDrain();
272

    
273
            // 확도 계산
274
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAccuracy ( 95 % )");
275
            UpdateAccuracy();
276

    
277
            //UpdatePSNType();
278

    
279
        }
280

    
281
        private void UpdatePSNType()
282
        {
283
            try
284
            {
285
                foreach (PSNItem PSNItem in PSNItems)
286
                {    
287
                    foreach (Group group in PSNItem.Groups)
288
                    {
289
                        foreach (Item item in group.Items)
290
                        {
291
                            DataRow[] pipeSystems = PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID()));
292
                           // PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
293

    
294
                            foreach(DataRow dr in pipeSystems)
295
                            {
296
                                dr["Type"] = PSNItem.GetPSNType();
297
                            }                            
298
                        }
299
                    }                
300
                }
301
            }
302
            catch (Exception ex)
303
            {
304
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
305
            }
306
        }
307

    
308
        private void PathItemSorting()
309
        {
310
            try
311
            {
312
                DataTable dtPathItems = PathItems.Clone();
313
                DataTable dtPipeSystemNetwork = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
314

    
315
                foreach (DataRow drpipe in dtPipeSystemNetwork.Rows)
316
                {
317
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drpipe["OID"].ToString()));
318
                    DataTable dtSequenceItems = SequenceData.Clone();
319
                    foreach (DataRow drpath in pathItemRows)
320
                    {
321
                        DataRow sequenceRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", drpath.Field<string>("OID"))).First();
322

    
323
                        DataRow newRow = dtSequenceItems.NewRow();
324
                        foreach (DataColumn column in SequenceData.Columns)
325
                            if (dtSequenceItems.Columns[column.ColumnName] != null)
326
                                newRow[column.ColumnName] = sequenceRows[column.ColumnName];
327

    
328
                        dtSequenceItems.Rows.Add(newRow);
329
                    }
330

    
331
                    foreach (DataRow sqrow in dtSequenceItems.Select().OrderBy(x => Convert.ToInt32(x.Field<string>("SERIALNUMBER"))))
332
                    {
333
                        DataRow newRow = dtPathItems.NewRow();
334
                        DataRow row = PathItems.Select(string.Format("OID = '{0}'", sqrow["PathItem_OID"])).First();
335

    
336
                        foreach (DataColumn column in PathItems.Columns)
337
                            if (dtPathItems.Columns[column.ColumnName] != null)
338
                                newRow[column.ColumnName] = row[column.ColumnName];
339

    
340
                        dtPathItems.Rows.Add(newRow);
341
                    }
342
                }
343

    
344
                PathItems.Clear();
345
                PathItems = dtPathItems.Copy();
346
            }
347
            catch (Exception ex)
348
            {
349
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
350
            }
351
        }
352
        
353
        private void UpdateAirFinCooler()
354
        {
355
            try
356
            {
357
                
358
                int pumpTagNum = 0;
359
                #region EquipmentAirFinCooler Info
360
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
361
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
362
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
363
                {
364
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
365
                    {
366
                        Type = row["Type"].ToString(),
367
                        Name = row["Name"].ToString()
368
                    });
369
                }
370
                #endregion
371

    
372
                
373
                DataRow[] pumpRows = PipeSystemNetwork.Select("PUMP = 'PUMP'");
374
                // 1, 2번
375
                foreach (DataRow dataRow in pumpRows) 
376
                {
377
                    pumpTagNum++;
378

    
379
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
380

    
381
                    string eqTag = string.Empty;
382
                    string EGFlowDirection = string.Empty;
383
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
384
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
385
                    {
386
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
387
                        {
388
                            eqTag = PSNItem.Groups.First().Items.First().Equipment.ItemTag;
389
                            EGFlowDirection = "O";
390
                        }                        
391
                    } 
392
                    else if(PSNItem.Groups.Last().Items.Last().Equipment != null)
393
                    {
394
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
395
                        {
396
                            eqTag = PSNItem.Groups.Last().Items.Last().Equipment.ItemTag;
397
                            EGFlowDirection = "I";
398
                        }
399
                    }
400

    
401
                    if(!string.IsNullOrEmpty(eqTag))
402
                    {
403
                        foreach (DataRow dr in pathItemRows)
404
                        {
405
                            dr["EqpGroupTag"] = eqTag;
406
                            dr["EGFlowDirection"] = EGFlowDirection;
407
                        }
408
                    }
409
                }
410

    
411
                // 3, 4번
412
                foreach (DataRow dataRow in pumpRows) 
413
                {
414

    
415
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
416
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
417
                    string EGFlowDirection = string.Empty;
418

    
419
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
420
                    {
421
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
422
                        {
423
                            EGFlowDirection = "O";
424
                        }
425
                    }
426
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
427
                    {
428
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
429
                        {
430
                            EGFlowDirection = "I";
431
                        }
432
                    }
433

    
434

    
435
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
436

    
437
                    foreach (DataRow dr in pathItemRows)
438
                    {
439
                        if(dr.Field<string>("ViewPipeSystemNetwork_OID") != dataRow["OID"].ToString())
440
                        {
441
                            string viewEGFlowDirection = string.Empty;
442
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
443
                            {
444
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));                               
445

    
446
                                if (viewPSNItem.Groups.First().Items.First().Equipment != null)
447
                                {
448
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
449
                                    {
450
                                        viewEGFlowDirection = "O";
451
                                    }
452
                                }
453
                                else if (viewPSNItem.Groups.Last().Items.Last().Equipment != null)
454
                                {
455
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
456
                                    {
457
                                        viewEGFlowDirection = "I";
458
                                    }
459
                                }
460

    
461
                                if (EGFlowDirection.Equals(viewEGFlowDirection) && !lstViewPipeSystemNetwork_OID.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
462
                                    lstViewPipeSystemNetwork_OID.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
463
                            }
464
                            else
465
                            {
466
                            }
467
                        }
468
                    }
469

    
470
                    string selectViewOID = string.Empty;
471

    
472
                    if (EGFlowDirection == "O") //From 이면 시작점에서 제일 먼 값
473
                    {
474
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
475
                        {
476
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
477
                            {                                
478
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
479
                            }
480
                        }
481
                    }
482
                    else if (EGFlowDirection == "I") //To 이면 시작점에서 제일 가까운 값
483
                    {
484
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
485
                        {
486
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
487
                            {
488
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
489
                                break;
490
                            }
491
                        }
492
                    }
493

    
494
                    if (!string.IsNullOrEmpty(selectViewOID)) //selectViewOID 가 있으면
495
                    {              
496
                        string EqpGroupTag = string.Empty;                       
497

    
498
                        if((EGFlowDirection == "O" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.Last().Field<string>("ViewPipeSystemNetwork_OID"))) ||
499
                            (EGFlowDirection == "I" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID"))))
500
                        { 
501
                            DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID")));
502

    
503
                            foreach (DataRow row in viewpathItemRows)
504
                            {
505
                                if (!string.IsNullOrEmpty(row.Field<string>("EqpGroupTag")))
506
                                {
507
                                    EqpGroupTag = row.Field<string>("EqpGroupTag");
508
                                    break;
509
                                }
510
                            }
511

    
512
                            foreach (DataRow dr in pathItemRows)
513
                            {
514
                                dr["EqpGroupTag"] = EqpGroupTag;
515
                            }
516

    
517
                        }
518
                        else
519
                        {
520
                            bool bCheck = false;
521
                            if (EGFlowDirection == "I") //To 일때
522
                            {
523
                                foreach (DataRow dr in pathItemRows)
524
                                {
525
                                    if (selectViewOID == dr["OID"].ToString())
526
                                    {
527
                                        dr["EGTConnectedPoint"] = "1";
528
                                        bCheck = true;
529
                                    }
530

    
531
                                    if (!bCheck)
532
                                    {
533
                                        dr["EqpGroupTag"] = string.Empty;
534
                                        dr["MainLineTag"] = string.Empty;
535
                                        dr["EGTConnectedPoint"] = "0";
536
                                        dr["EGFlowDirection"] = string.Empty;
537
                                    }
538
                                    else
539
                                    {
540
                                        dr["MainLineTag"] = "M";
541
                                    }
542
                                    
543
                                }
544

    
545
                            }
546
                            else if (EGFlowDirection == "O") //From 일 때
547
                            {
548
                                foreach (DataRow dr in pathItemRows)
549
                                {
550
                                    if (bCheck)
551
                                    {
552
                                        
553
                                        dr["EqpGroupTag"] = string.Empty;
554
                                        dr["MainLineTag"] = string.Empty;
555
                                        dr["EGTConnectedPoint"] = "0";
556
                                        dr["EGFlowDirection"] = string.Empty;
557
                                    }
558
                                    else
559
                                    {
560
                                        dr["MainLineTag"] = "M";
561
                                    }
562

    
563
                                    if (selectViewOID == dr["OID"].ToString())
564
                                    {
565
                                        dr["EGTConnectedPoint"] = "1";
566
                                        bCheck = true;
567
                                    }
568
                                }
569
                            }
570
                        }
571
                    }
572
                    else
573
                    {
574
                        foreach (DataRow dr in pathItemRows)
575
                        {
576
                            dr["EqpGroupTag"] = string.Empty;
577
                            dr["EGFlowDirection"] = string.Empty;
578
                        }
579
                    }
580
                }
581
                                
582
                // 5번
583
                foreach (DataRow dataRow in pumpRows)
584
                {
585
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
586

    
587
                    bool bCheck = false;
588
                    string EqpGroupTag = string.Empty;
589

    
590
                    string EGFlowDirection = string.Empty;                   
591

    
592
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow.Field<string>("OID"));
593

    
594
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
595
                    {
596
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
597
                        {
598
                            EGFlowDirection = "O";
599
                        }
600
                    }
601
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
602
                    {
603
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
604
                        {
605
                            EGFlowDirection = "I";
606
                        }
607
                    }
608

    
609
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
610
                    List<string> lstEqTagRows = new List<string>();
611
                    if (EGFlowDirection.Equals("I"))
612
                    {
613
                        foreach (DataRow dr in pathItemRows)
614
                        {                            
615
                            if (!string.IsNullOrEmpty(dr.Field<string>("MainLineTag")) && dr.Field<string>("MainLineTag").Equals("M") && !string.IsNullOrEmpty(dr.Field<string>("EqpGroupTag")))
616
                            {
617
                                bCheck = true;
618
                                EqpGroupTag = dr.Field<string>("EqpGroupTag");
619
                                if(!lstEqTagRows.Contains(EqpGroupTag))
620
                                    lstEqTagRows.Add(EqpGroupTag);
621

    
622
                                if(dataRow["OID"].ToString() != dr.Field<string>("ViewPipeSystemNetwork_OID"))
623
                                {
624
                                    PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));
625
                                    if (viewPSNItem.Groups.Last().Items.Last().Equipment == null)
626
                                        continue;
627

    
628
                                    if (!lstEqTagRows.Contains(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag))
629
                                        lstEqTagRows.Add(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag);
630
                                }
631
                                
632
                            }
633

    
634
                        }
635
                        if(bCheck)
636
                        {
637
                            foreach (DataRow row in pumpRows)
638
                            {
639
                                if (row.Field<string>("OID").Equals(dataRow["OID"].ToString()))
640
                                    continue;
641

    
642
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == row["OID"].ToString());
643

    
644
                                if (viewPSNItem.Groups.First().Items.First().Equipment == null)
645
                                    continue;
646
                                
647
                                if (lstEqTagRows.Contains(viewPSNItem.Groups.First().Items.First().Equipment.ItemTag) && !lstViewPipeSystemNetwork_OID.Contains(row.Field<string>("OID")))
648
                                    lstViewPipeSystemNetwork_OID.Add(row.Field<string>("OID"));
649
                            }
650

    
651
                                
652

    
653
                            if (lstViewPipeSystemNetwork_OID.Count() > 0)
654
                            {
655
                                foreach (string viewPipesystem in lstViewPipeSystemNetwork_OID)
656
                                {
657
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewPipesystem));
658
                                    foreach (DataRow viewdr in viewpathItemRows)
659
                                    {
660
                                        if (!string.IsNullOrEmpty(viewdr["EqpGroupTag"].ToString()))
661
                                            viewdr["EqpGroupTag"] = EqpGroupTag;
662
                                    }
663
                                }
664
                            }
665
                        }                        
666
                    }                   
667
                }
668
                
669
                int afcTagNum = 0;
670
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
671
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
672
                foreach (DataRow dataRow in airFinCoolerRows)
673
                {
674
                    string[] afcTag = dataRow.Field<string>("AFC").Split(new string[] { "\\" }, StringSplitOptions.None);
675
                    if (afcTag.Length > 1)
676
                    {                        
677
                        string afc = string.Empty;
678
                        if(!keyValuePairs.ContainsKey(afcTag[1]))
679
                        {
680
                            afcTagNum++;
681
                            afc = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));
682
                            keyValuePairs.Add(afcTag[1], afc);                            
683
                        }
684
                        else
685
                        {
686
                            afc = keyValuePairs[afcTag[1]];
687
                        }
688

    
689
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
690
                        foreach (DataRow dr in pathItemRows)
691
                        {
692
                            dr["EqpGroupTag"] = afc;
693
                        }
694
                    }                    
695
                }
696
                
697
                foreach (DataRow dataRow in airFinCoolerRows)
698
                {
699
                    
700
                    string EGFlowDirection = string.Empty;
701
                    
702
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
703
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
704
                    {
705
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
706
                        {
707
                            EGFlowDirection = "O";
708
                        }
709
                    }
710
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
711
                    {
712
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
713
                        {
714
                            EGFlowDirection = "I";
715
                        }
716
                    }
717

    
718
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
719
                    string AFCTag = pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");
720
                    List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).ToList();
721
                    //ViewPipeSystemNetwork_OID
722
                    string MainLineTag = "";
723
                    if (dataRow["Type"].ToString() == "E2E")
724
                    {
725
                        MainLineTag = "M";
726
                         dataRow["AFC"] = "P3";
727
                    }
728
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
729
                    {
730
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
731
                        {
732
                            if (viewOID == dataRow["OID"].ToString())
733
                                continue;
734

    
735
                            DataRow dr = PipeSystemNetwork.Select(string.Format("OID = '{0}'", viewOID)).First();
736
                            if (!dr.Field<string>("AFC").Contains("P1"))
737
                            {
738
                                if (lstViewPipeSystemNetwork_OID.Where(x => x.Equals(viewOID)).Count() == 1)
739
                                {
740
                                    MainLineTag = "M";
741
                                    dataRow["AFC"] = "P3";
742
                                }
743
                                else if(lstViewPipeSystemNetwork_OID.Where(x => x.Equals(viewOID)).Count() > 1)
744
                                {
745
                                    DataRow[] viewpipeSystem = PipeSystemNetwork.Select(string.Format("OID = '{0}'", viewOID));
746
                                    foreach (DataRow row in viewpipeSystem)
747
                                    {
748
                                        row["AFC"] = "P4";
749
                                    }
750

    
751
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID));
752

    
753
                                    //if(viewpathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).Count() > 0)
754
                                    //    AFCTag = viewpathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");                                    
755
                                    afcTagNum++;
756
                                    AFCTag = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));
757
                                    foreach (DataRow viewdr in viewpathItemRows)
758
                                    {
759
                                        viewdr["EqpGroupTag"] = AFCTag;
760
                                        viewdr["MainLineTag"] = "M";
761
                                    }
762
                                }
763
                            }
764
                        }                            
765
                    }
766

    
767
                    foreach (DataRow dr in pathItemRows)
768
                    {
769
                        dr["EqpGroupTag"] = AFCTag;// "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));  //ATG Sequence No Rule 여쭤봐야함.
770
                        dr["MainLineTag"] = MainLineTag; 
771
                        dr["EGFlowDirection"] = EGFlowDirection; 
772
                    }
773
                }
774

    
775
                //P3을 제외한 P1
776
                airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
777
                foreach (DataRow dataRow in airFinCoolerRows)
778
                {
779
                    //ML이 공란
780
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = ''", dataRow["OID"].ToString()));
781
                 
782
                    if (pathItemRows.Count() > 0)
783
                    {
784
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
785
                        List<string> lstpsn = new List<string>();
786
                        List<string> lstAll = new List<string>();
787
                        string EqpGroupTag = string.Empty;
788
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
789
                        {
790
                            if (dataRow["OID"].ToString() == viewOID)
791
                                continue;
792

    
793
                            //P3이면
794
                            DataRow viewPSN = null;
795
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
796
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
797
                            
798
                            if (viewPSN != null)
799
                            {
800
                                //P3의 AGT를 가져와 P1에 입력
801
                                EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
802
                                foreach (DataRow dr in pathItemRows)
803
                                {
804
                                    dr["EqpGroupTag"] = EqpGroupTag;
805

    
806
                                    //P1의 AGT와 같은 모든 AGT를 P3의 AGT로 변경하기위해 
807
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
808
                                    {
809
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
810
                                        lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
811
                                    }
812
                                }
813
                            }
814
                            
815
                        }
816

    
817
                        while (lstpsn.Count() != 0)
818
                        {
819
                            int lstCount = lstpsn.Count;
820
                            for (int i = 0; i < lstpsn.Count(); i++) //string psn in lstpsn
821
                            {
822

    
823
                                DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstpsn[i]));
824
                                foreach (DataRow dr in rule4pathItems)
825
                                {
826
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstAll.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
827
                                    {
828
                                        DataRow viewPSN = null;
829
                                        //연결된 PathItem-Tee (P3인것만) 의 PathItem-Tee에 또 P3가 있다면 해당 PSN도 Tag변경 만약 P3가 아닌 모든 OID면 해당 로직 삭제 (위에로직도 변경필요)
830
                                        if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
831
                                            viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).First();
832
                                        if(viewPSN != null)
833
                                        {
834
                                            lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
835
                                            lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
836
                                        }
837
                                    }
838

    
839
                                    if (dr["EqpGroupTag"].Equals(EqpGroupTag))
840
                                        continue;
841

    
842
                                    dr["EqpGroupTag"] = EqpGroupTag;
843
                                }
844

    
845
                                lstpsn.Remove(lstpsn[i]);
846
                            }
847

    
848
                        }
849
                    }
850
                    
851
                }
852

    
853
                foreach(DataRow dr in PipeSystemNetwork.Rows)
854
                {
855
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
856
                    if(pathItemRows.Count() > 0)
857
                    {
858
                        if(dr["Type"].ToString() == "HD2")
859
                        {
860
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
861
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
862
                            {                              
863
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
864
                                {
865
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
866
                                    {
867
                                        dataRow["EGTConnectedPoint"] = "1";
868
                                    }
869
                                }
870
                            }
871
                        }
872
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
873
                        {
874
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
875
                            string lastP1 = string.Empty;
876
                            foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
877
                            {
878
                                if (viewpsn == dr["OID"].ToString())
879
                                    continue;
880

    
881
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC Like 'P1%'", viewpsn)).Length == 0)
882
                                    continue;
883

    
884
                                DataRow rows = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC Like 'P1%'", viewpsn)).First();
885
                                if(rows != null)
886
                                {
887
                                    lastP1 = viewpsn;
888
                                }
889
                            }
890

    
891
                            if(!string.IsNullOrEmpty(lastP1))
892
                            {
893
                                bool bCheck = false;
894
                                foreach (DataRow dataRow in pathItemRows)
895
                                {
896
                                    if (bCheck)
897
                                        dataRow["EqpGroupTag"] = string.Empty;
898

    
899
                                    if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
900
                                    {
901
                                        bCheck = true;
902
                                        dataRow["EGTConnectedPoint"] = 1;
903
                                    }                       
904
                                }
905
                            }
906
                        }
907
                    }
908
                }
909

    
910
                //psn data 정리
911
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
912
                {
913
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
914
                    string EGTag = string.Empty;
915
                    string HasMLTags = "False";
916

    
917
                    foreach (DataRow dataRow in pathItemRows)
918
                    {
919
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
920
                            EGTag = dataRow.Field<string>("EqpGroupTag");
921

    
922
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
923
                            HasMLTags = "True";
924

    
925
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
926
                            break;
927
                    }
928

    
929
                    pipesystem["EGTag"] = EGTag;
930
                    pipesystem["HasMLTags"] = HasMLTags;
931
                }
932
            }
933
            catch (Exception ex)
934
            {
935
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
936
            }
937
            //}
938
        }
939

    
940
        private void UpdateValveGrouping()
941
        {
942
            try
943
            {
944
                #region ValveGrouping Info
945
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
946
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
947
                foreach (DataRow row in dtValveGroupung.Rows)
948
                {
949
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
950
                    {
951
                        OID = row["OID"].ToString(),
952
                        GroupType = row["GroupType"].ToString(),
953
                        TagIdentifier = row["TagIdentifier"].ToString(),
954
                        AttributeName = row["AttributeName"].ToString(),
955
                        SppidSymbolName = row["SppidSymbolName"].ToString()
956
                    });
957
                }
958
                #endregion
959

    
960

    
961
                int vgTagNum = 1;
962
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
963
                foreach (DataRow drPathitem in tagpathItemRows)
964
                {
965
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
966
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
967
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
968
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
969
                        continue;
970
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
971
                    List<Item> valveGroupingItem = new List<Item>();
972
                    int bCnt = 0;
973

    
974
                    //bool bCheck = false;
975
                    if (drPathitem["PipeSystemNetwork_OID"].ToString().Contains("901"))
976
                    {
977

    
978
                    }
979
                    List<DataRow> lstitem = new List<DataRow>();
980
                    foreach (DataRow dr in pathItemRows)
981
                    {
982
                        //if (!string.IsNullOrEmpty(dr["GROUPTAG"].ToString()))
983
                        //    break;
984

    
985
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
986
                        {
987
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
988
                            if (dr["GROUPTAG"].ToString() == "Scope Break")
989
                            {
990
                                dr["GROUPTAG"] = string.Empty;
991
                                keyValuePairs.Add(bCnt, lstitem.ToList());
992
                                bCnt++;
993
                                lstitem.Clear();
994
                                //break;
995
                            }
996
                            else
997
                            {
998
                                if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
999
                                {
1000
                                    // bCheck = true;
1001
                                    if (lstitem.ToList().Where(x => !string.IsNullOrEmpty(x.Field<string>("GROUPTAG"))).Count() > 0)
1002
                                    {
1003
                                        lstitem.Add(dr);
1004
                                        keyValuePairs.Add(bCnt, lstitem.ToList());
1005
                                        lstitem.Clear();
1006
                                    }
1007
                                    else
1008
                                    {
1009
                                        keyValuePairs.Add(bCnt, lstitem.ToList());
1010
                                        lstitem.Clear();
1011
                                        lstitem.Add(dr);
1012
                                    }
1013
                                    bCnt++;
1014

    
1015
                                }
1016
                                else
1017
                                    lstitem.Add(dr);
1018
                            }
1019

    
1020
                        }
1021
                        else
1022
                            lstitem.Add(dr);
1023
                    }
1024

    
1025
                    if (lstitem.Count > 0)
1026
                    {
1027
                        keyValuePairs.Add(bCnt, lstitem);
1028
                        //bCnt++;
1029
                    }
1030

    
1031
                    if (keyValuePairs.Count() == 0)
1032
                        continue;
1033

    
1034
                    string VGTag = string.Empty;
1035
                    if (valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
1036
                    {
1037
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1038
                        vgTagNum++;
1039
                    }
1040
                    else
1041
                    {
1042
                        if(string.IsNullOrEmpty(valvetag[1]))
1043
                            VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1044
                        else
1045
                            VGTag = valveitem.TagIdentifier + "-" + valvetag[1] + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1046

    
1047
                        vgTagNum++;
1048
                    }
1049

    
1050
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
1051
                    {
1052
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
1053
                        {
1054
                            foreach (DataRow dr in keyValuePair.Value)
1055
                            {
1056
                                dr["GROUPTAG"] = VGTag;
1057

    
1058
                                if(!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1059
                                {
1060
                                    if(TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1061
                                    {
1062
                                        DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1063
                                        foreach(DataRow path in rows)
1064
                                        {
1065
                                            DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1066
                                            if (topology.Field<string>("SubType").Equals("Bypass"))
1067
                                            {
1068
                                                DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1069
                                                foreach(DataRow pathitem in drPathItem)
1070
                                                {
1071
                                                    pathitem["GROUPTAG"] = VGTag;
1072
                                                }
1073
                                            }
1074
                                        }
1075
                                    }
1076
                                    
1077

    
1078
                                    //ViewPipeSystemNetwork_OID
1079
                                    //DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
1080
                                }
1081
                            }
1082
                        }
1083
                    }
1084

    
1085
                    if(valveitem.GroupType.Contains("PSV"))
1086
                    {
1087
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1088
                        foreach (DataRow row in psnRows)
1089
                            row["Pocket"] = "Yes";
1090
                    }                    
1091
                }
1092

    
1093

    
1094
            }
1095
            catch (Exception ex)
1096
            {
1097
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1098
            }
1099
            //}
1100
        }
1101

    
1102
        private void SetTopologyData()
1103
        {
1104
            // 13번 excel
1105
            foreach (Group group in groups)
1106
            {
1107
                LineNumber prevLineNumber = null;
1108
                for (int i = 0; i < group.Items.Count; i++)
1109
                {
1110
                    Item item = group.Items[i];
1111
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1112
                    if (lineNumber == null)
1113
                    {
1114
                        if (prevLineNumber != null)
1115
                        {
1116
                            if (!prevLineNumber.IsCopy)
1117
                            {
1118
                                prevLineNumber = prevLineNumber.Copy();
1119
                                item.Document.LineNumbers.Add(prevLineNumber);
1120
                                item.MissingLineNumber1 = true;
1121
                            }
1122
                            item.Owner = prevLineNumber.UID;
1123
                        }
1124
                    }
1125
                    else
1126
                        prevLineNumber = lineNumber;
1127
                }
1128

    
1129
                prevLineNumber = null;
1130
                for (int i = group.Items.Count - 1; i > -1; i--)
1131
                {
1132
                    Item item = group.Items[i];
1133
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1134
                    if (lineNumber == null)
1135
                    {
1136
                        if (prevLineNumber != null)
1137
                        {
1138
                            if (!prevLineNumber.IsCopy)
1139
                            {
1140
                                prevLineNumber = prevLineNumber.Copy();
1141
                                item.Document.LineNumbers.Add(prevLineNumber);
1142
                                item.MissingLineNumber1 = true;
1143
                            }
1144

    
1145
                            item.Owner = prevLineNumber.UID;
1146
                        }
1147
                    }
1148
                    else
1149
                        prevLineNumber = lineNumber;
1150
                }
1151

    
1152
                if (prevLineNumber == null)
1153
                {
1154
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1155
                    Random random = new Random();
1156
                    int index = random.Next(lineNumbers.Count - 1);
1157

    
1158
                    // Copy
1159
                    LineNumber cLineNumber = lineNumbers[index].Copy();
1160
                    group.Document.LineNumbers.Add(cLineNumber);
1161

    
1162
                    foreach (Item item in group.Items)
1163
                    {
1164
                        item.Owner = cLineNumber.UID;
1165
                        item.MissingLineNumber2 = true;
1166
                    }
1167
                }
1168
            }
1169

    
1170
            foreach (Document document in Documents)
1171
            {
1172
                foreach (Item item in document.Items)
1173
                {
1174
                    item.TopologyData = string.Empty;
1175
                    item.PSNPipeLineID = string.Empty;
1176
                    List<string> pipeLineID = new List<string>();
1177
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1178
                    if (lineNumber != null)
1179
                    {
1180
                        item.LineNumber = lineNumber;
1181

    
1182
                        foreach (DataRow row in topologyRuleDT.Rows)
1183
                        {
1184
                            string uid = row["UID"].ToString();
1185
                            //if (uid == "-")
1186
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1187
                            if (uid != "-")
1188
                            {
1189
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1190

    
1191
                                Attribute attribute = lineNumber.Attributes.Find(x => x.DisplayName == uid);
1192
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1193
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1194
                            }
1195
                        }
1196

    
1197
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1198
                        {
1199
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1200
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1201
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1202
                                                                 //else
1203
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1204
                        }
1205

    
1206
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1207
                        item.TopologyData = string.Join("-", pipeLineID);
1208

    
1209
                    }
1210
                    else
1211
                    {
1212
                        item.TopologyData = "Empty LineNumber";
1213
                        item.LineNumber = new LineNumber();
1214
                    }
1215
                }
1216
            }
1217

    
1218
            int emptyIndex = 1;
1219
            foreach (Group group in groups)
1220
            {
1221
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1222
                if (groupItems.Count > 0)
1223
                {
1224
                    foreach (var item in groupItems)
1225
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1226
                    emptyIndex++;
1227
                }
1228
            }
1229

    
1230
        }
1231

    
1232
        private void ConnectByOPC()
1233
        {
1234
            try
1235
            {
1236
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1237
                {
1238
                    Item opcItem = group.Items.Last();
1239
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1240
                    if (fromRows.Length.Equals(1))
1241
                    {
1242
                        DataRow opcRow = fromRows.First();
1243
                        string toDrawing = opcRow["ToDrawing"].ToString();
1244
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
1245

    
1246
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1247
                        if (toDocument != null)
1248
                        {
1249
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1250
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1251
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1252
                            if (toRows.Length > 1)
1253
                            {
1254
                                //throw new Exception("OPC error(multi connect)");
1255
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1256
                                return;
1257
                            }
1258
                            group.EndGroup = toGroup;
1259
                            toGroup.StartGroup = group;
1260
                        }
1261
                    }
1262
                }
1263
            }
1264
            catch (Exception ex)
1265
            {
1266
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1267
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1268
            }
1269
        }
1270

    
1271
        private void SetPSNItem()
1272
        {
1273
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1274
            foreach (Group group in groups)
1275
                groupDic.Add(group, Guid.NewGuid().ToString());
1276

    
1277
            foreach (Group group in groups)
1278
            {
1279
                string groupKey = groupDic[group];
1280
                if (group.StartGroup != null)
1281
                {
1282
                    string otherKey = groupDic[group.StartGroup];
1283
                    ChangeGroupID(otherKey, groupKey);
1284
                }
1285
            }
1286

    
1287
            // PSN 정리
1288
            foreach (var item in groupDic)
1289
            {
1290
                Group group = item.Key;
1291
                string uid = item.Value;
1292
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1293
                if (PSNItem == null)
1294
                {
1295
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1296
                    PSNItems.Add(PSNItem);
1297
                }
1298
                PSNItem.Groups.Add(group);
1299
                foreach (Item groupItem in group.Items)
1300
                    groupItem.PSNItem = PSNItem;
1301
            }
1302

    
1303
            // Sort PSN
1304
            foreach (PSNItem PSNItem in PSNItems)
1305
            {
1306
                List<Group> _groups = new List<Group>();
1307

    
1308
                Stack<Group> stacks = new Stack<Group>();
1309
                stacks.Push(PSNItem.Groups.First());
1310
                while (stacks.Count > 0)
1311
                {
1312
                    Group stack = stacks.Pop();
1313
                    if (_groups.Contains(stack))
1314
                        continue;
1315

    
1316
                    if (_groups.Count == 0)
1317
                        _groups.Add(stack);
1318
                    else
1319
                    {
1320
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1321
                        {
1322
                            int index = _groups.IndexOf(stack.StartGroup);
1323
                            _groups.Insert(index + 1, stack);
1324
                        }
1325
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1326
                        {
1327
                            int index = _groups.IndexOf(stack.EndGroup);
1328
                            _groups.Insert(index, stack);
1329
                        }
1330
                    }
1331

    
1332
                    if (stack.StartGroup != null)
1333
                        stacks.Push(stack.StartGroup);
1334
                    if (stack.EndGroup != null)
1335
                        stacks.Push(stack.EndGroup);
1336
                }
1337

    
1338
                PSNItem.Groups.Clear();
1339
                PSNItem.Groups.AddRange(_groups);
1340
            }
1341

    
1342
            void ChangeGroupID(string from, string to)
1343
            {
1344
                if (from.Equals(to))
1345
                    return;
1346

    
1347
                List<Group> changeItems = new List<Group>();
1348
                foreach (var _item in groupDic)
1349
                    if (_item.Value.Equals(from))
1350
                        changeItems.Add(_item.Key);
1351
                foreach (var _item in changeItems)
1352
                    groupDic[_item] = to;
1353
            }
1354
        }
1355

    
1356
        private void SetPSNType()
1357
        {
1358
            foreach (PSNItem PSNItem in PSNItems)
1359
            {
1360
                Group firstGroup = PSNItem.Groups.First();
1361
                Group lastGroup = PSNItem.Groups.Last();
1362

    
1363
                Item firstItem = firstGroup.Items.First();
1364
                Item lastItem = lastGroup.Items.Last();
1365

    
1366
                PSNItem.StartType = GetPSNType(firstItem, true);
1367
                PSNItem.EndType = GetPSNType(lastItem, false);
1368

    
1369
            }
1370

    
1371
            PSNType GetPSNType(Item item, bool bFirst = true)
1372
            {
1373
                PSNType type = PSNType.None;
1374

    
1375
                if (item.ItemType == ItemType.Line)
1376
                {
1377
                    Group group = groups.Find(x => x.Items.Contains(item));
1378
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1379
                    {
1380
                        Item connItem = item.Relations[0].Item;
1381
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1382
                            type = PSNType.Branch;
1383
                        else if (connItem.ItemType == ItemType.Symbol)
1384
                            type = PSNType.Symbol;
1385
                    }
1386
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1387
                    {
1388
                        Item connItem = item.Relations[1].Item;
1389
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1390
                            type = PSNType.Branch;
1391
                        else if (connItem.ItemType == ItemType.Symbol)
1392
                            type = PSNType.Symbol;
1393
                    }
1394
                }
1395
                else if (item.ItemType == ItemType.Symbol)
1396
                {
1397
                    if (item.SubItemType == SubItemType.Nozzle)
1398
                        type = PSNType.Equipment;
1399
                    else if (item.SubItemType == SubItemType.Header)
1400
                        type = PSNType.Header;
1401
                    else if (item.SubItemType == SubItemType.OPC)
1402
                        type = PSNType.OPC;
1403
                }
1404

    
1405
                return type;
1406
            }
1407
        }
1408

    
1409
        private void SetBranchInfo()
1410
        {
1411
            foreach (Document document in Documents)
1412
            {
1413
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1414
                foreach (Item line in lines)
1415
                {
1416
                    double[] point = line.Relations[0].Point;
1417
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1418
                    connLines.Sort(SortBranchLine);
1419
                    line.BranchItems.AddRange(connLines);
1420

    
1421
                    int SortBranchLine(Item a, Item b)
1422
                    {
1423
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1424
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1425

    
1426
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1427
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1428

    
1429
                        // 내림차순
1430
                        return distanceA.CompareTo(distanceB);
1431
                    }
1432
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1433
                    {
1434
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1435
                    }
1436
                }
1437
            }
1438
        }
1439

    
1440
        private void SetTopology()
1441
        {
1442
            try
1443
            {
1444
                #region 기본 topology 정리
1445
                foreach (PSNItem PSNItem in PSNItems)
1446
                {
1447
                    Topology topology = null;
1448
                    foreach (Group group in PSNItem.Groups)
1449
                    {
1450
                        foreach (Item item in group.Items)
1451
                        {
1452
                            if (string.IsNullOrEmpty(item.TopologyData))
1453
                                topology = null;
1454
                            else
1455
                            {
1456
                                if (topology == null)
1457
                                {
1458
                                    topology = new Topology()
1459
                                    {
1460
                                        ID = item.TopologyData
1461
                                    };
1462
                                    Topologies.Add(topology);
1463

    
1464
                                    if (!PSNItem.Topologies.Contains(topology))
1465
                                        PSNItem.Topologies.Add(topology);
1466
                                }
1467
                                else
1468
                                {
1469
                                    if (topology.ID != item.TopologyData)
1470
                                    {
1471
                                        topology = new Topology()
1472
                                        {
1473
                                            ID = item.TopologyData
1474
                                        };
1475
                                        Topologies.Add(topology);
1476

    
1477
                                        if (!PSNItem.Topologies.Contains(topology))
1478
                                            PSNItem.Topologies.Add(topology);
1479
                                    }
1480
                                }
1481

    
1482
                                item.Topology = topology;
1483
                                topology.Items.Add(item);
1484
                            }
1485
                        }
1486
                    }
1487
                }
1488
                #endregion
1489

    
1490
                #region Type
1491
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1492
                foreach (string id in ids)
1493
                {
1494
                    try
1495
                    {
1496

    
1497

    
1498
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1499

    
1500
                        // Main
1501
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1502
                        foreach (Topology topology in mainTopologies)
1503
                            topology.Type = "M";
1504

    
1505
                        // Branch
1506
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1507
                        foreach (Topology topology in branchToplogies)
1508
                            topology.Type = "B";
1509
                    }
1510
                    catch (Exception ex)
1511
                    {
1512
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1513
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1514
                    }
1515
                }
1516
                #endregion
1517
            }
1518
            catch (Exception ex)
1519
            {
1520
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1521
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1522
            }
1523

    
1524
        }
1525

    
1526
        private void SetTopologyIndex()
1527
        {
1528
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1529
            foreach (string id in ids)
1530
            {
1531
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1532

    
1533
                // Main
1534
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1535
                foreach (Topology topology in mainTopologies)
1536
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1537

    
1538
                // Branch
1539
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1540
                foreach (Topology topology in branchToplogies)
1541
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1542
            }
1543
        }
1544

    
1545
        private void SetPSNBypass()
1546
        {
1547
            foreach (PSNItem PSNItem in PSNItems)
1548
                PSNItem.IsBypass = IsBypass(PSNItem);
1549
        }
1550

    
1551
        private List<Topology> FindMainTopology(List<Topology> data)
1552
        {
1553
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1554
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1555
            //2021.11.17 안쓰네 JY
1556
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1557

    
1558
            List<Topology> main = new List<Topology>();
1559
            main.AddRange(data);
1560
            //
1561
            main = GetNozzleTopology(data);
1562
            if (main.Count == 1)
1563
                return main;
1564
            else
1565
            {
1566
                if (main.Count > 0)
1567
                    main = GetPMCTopology(main);
1568
                else
1569
                    main = GetPMCTopology(data);
1570

    
1571
                if (main.Count == 1)
1572
                    return main;
1573
                else
1574
                {
1575
                    if (main.Count > 0)
1576
                        main = GetDiaTopology(main);
1577
                    else
1578
                        main = GetDiaTopology(data);
1579

    
1580

    
1581
                    if (main.Count == 1)
1582
                        return main;
1583
                    else
1584
                    {
1585
                        if (main.Count > 0)
1586
                            main = GetItemTopology(main);
1587
                        else
1588
                            main = GetItemTopology(data);
1589
                    }
1590
                }
1591
            }
1592

    
1593
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1594
            {
1595
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1596
            }
1597

    
1598
            List<Topology> GetPMCTopology(List<Topology> topologies)
1599
            {
1600
                List<Topology> result = new List<Topology>();
1601
                foreach (DataRow row in PMCDT.Rows)
1602
                {
1603
                    string value = row["CODE"].ToString();
1604
                    foreach (Topology topology in topologies)
1605
                    {
1606
                        foreach (Item item in topology.Items)
1607
                        {
1608
                            if (item.LineNumber == null)
1609
                                continue;
1610
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1611
                            if (attribute != null && value == attribute.Value)
1612
                            {
1613
                                result.Add(topology);
1614
                                break;
1615
                            }
1616
                        }
1617
                    }
1618

    
1619
                    if (result.Count > 0)
1620
                        break;
1621
                }
1622

    
1623
                return result;
1624
            }
1625

    
1626
            List<Topology> GetDiaTopology(List<Topology> topologies)
1627
            {
1628
                List<Topology> result = new List<Topology>();
1629
                foreach (DataRow row in nominalDiameterDT.Rows)
1630
                {
1631
                    string inchValue = row["InchStr"].ToString();
1632
                    string metricValue = row["MetricStr"].ToString();
1633
                    foreach (Topology topology in topologies)
1634
                    {
1635
                        foreach (Item item in topology.Items)
1636
                        {
1637
                            if (item.LineNumber == null)
1638
                                continue;
1639
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1640
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1641
                            {
1642
                                result.Add(topology);
1643
                                break;
1644
                            }
1645
                        }
1646
                    }
1647

    
1648
                    if (result.Count > 0)
1649
                        break;
1650
                }
1651

    
1652
                return result;
1653
            }
1654

    
1655
            List<Topology> GetItemTopology(List<Topology> topologies)
1656
            {
1657
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1658
            }
1659

    
1660
            return main;
1661
        }
1662

    
1663
        private DataTable GetOPCInfo()
1664
        {
1665
            DataTable opc = DB.SelectOPCRelations();
1666
            DataTable drawing = DB.AllDrawings();
1667

    
1668
            DataTable dt = new DataTable();
1669
            dt.Columns.Add("FromDrawing", typeof(string));
1670
            dt.Columns.Add("FromDrawingUID", typeof(string));
1671
            dt.Columns.Add("FromOPCUID", typeof(string));
1672
            dt.Columns.Add("ToDrawing", typeof(string));
1673
            dt.Columns.Add("ToDrawingUID", typeof(string));
1674
            dt.Columns.Add("ToOPCUID", typeof(string));
1675
            foreach (DataRow row in opc.Rows)
1676
            {
1677
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1678
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1679
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1680
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1681
                if (!string.IsNullOrEmpty(toOPCUID))
1682
                {
1683
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
1684
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
1685
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
1686
                    {
1687
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
1688
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
1689

    
1690
                        DataRow newRow = dt.NewRow();
1691
                        newRow["FromDrawing"] = fromDrawingName;
1692
                        newRow["FromDrawingUID"] = fromDrawingUID;
1693
                        newRow["FromOPCUID"] = fromOPCUID;
1694
                        newRow["ToDrawing"] = toDrawingName;
1695
                        newRow["ToDrawingUID"] = toDrawingUID;
1696
                        newRow["ToOPCUID"] = toOPCUID;
1697

    
1698
                        dt.Rows.Add(newRow);
1699
                    }
1700
                }
1701
            }
1702

    
1703
            return dt;
1704
        }
1705

    
1706
        private DataTable GetTopologyRule()
1707
        {
1708
            DataTable dt = DB.SelectTopologyRule();
1709

    
1710
            return dt;
1711
        }
1712

    
1713
        private bool IsConnected(Item item1, Item item2)
1714
        {
1715
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
1716
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
1717
                return true;
1718
            else
1719
                return false;
1720
        }
1721

    
1722
        private void SaveNozzleAndEquipment()
1723
        {
1724
            List<Item> nozzles = new List<Item>();
1725
            List<Equipment> equipments = new List<Equipment>();
1726
            foreach (Document document in Documents)
1727
            {
1728
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1729
                equipments.AddRange(document.Equipments);
1730
            }
1731

    
1732

    
1733
            DataTable nozzleDT = new DataTable();
1734
            nozzleDT.Columns.Add("OID", typeof(string));
1735
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1736
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1737
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1738
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1739
            nozzleDT.Columns.Add("FLUID", typeof(string));
1740
            nozzleDT.Columns.Add("NPD", typeof(string));
1741
            nozzleDT.Columns.Add("PMC", typeof(string));
1742
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1743
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1744

    
1745
            foreach (Item item in nozzles)
1746
            {
1747
                DataRow row = nozzleDT.NewRow();
1748
                row["OID"] = item.UID;
1749

    
1750
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
1751
                if (relation != null)
1752
                {
1753
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
1754
                    equipment.Nozzles.Add(item);
1755
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
1756
                    row["Equipment_OID"] = equipment.UID;
1757
                    item.Equipment = equipment;
1758
                }
1759
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
1760
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
1761
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
1762
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
1763
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1764
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
1765
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1766
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
1767

    
1768
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1769
                if (angle >= Math.PI * 2)
1770
                    angle = angle - Math.PI * 2;
1771
                row["ROTATION"] = angle.ToString();
1772

    
1773
                if (item.Topology.Items.First().Equals(item))
1774
                    row["FlowDirection"] = "Outlet";
1775
                else if (item.Topology.Items.Last().Equals(item))
1776
                    row["FlowDirection"] = "Inlet";
1777
                else
1778
                    row["FlowDirection"] = string.Empty;
1779

    
1780
                nozzleDT.Rows.Add(row);
1781
            }
1782

    
1783
            DataTable equipDT = new DataTable();
1784
            equipDT.Columns.Add("OID", typeof(string));
1785
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1786
            equipDT.Columns.Add("XCOORDS", typeof(string));
1787
            equipDT.Columns.Add("YCOORDS", typeof(string));
1788

    
1789
            foreach (Equipment equipment in equipments)
1790
            {
1791
                DataRow row = equipDT.NewRow();
1792
                row["OID"] = equipment.UID;
1793
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
1794
                {
1795
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
1796
                    if (attribute != null)
1797
                        equipment.ItemTag = attribute.Value;
1798
                }
1799
                else
1800
                    equipment.ItemTag = equipment.Name;
1801

    
1802
                row["ITEMTAG"] = equipment.ItemTag;
1803
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
1804
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
1805

    
1806
                List<double> yList = equipment.POINT.Select(x => x[1]).ToList();
1807
                row["YCOORDS"] = (yList.Sum() / (double)yList.Count) / DrawingHeight;
1808

    
1809
                equipDT.Rows.Add(row);
1810
            }
1811

    
1812
            Equipment = equipDT;
1813
            Nozzle = nozzleDT;
1814
        }
1815

    
1816
        private void SavePSNData()
1817
        {
1818
            try
1819
            {
1820
                DataTable pathItemsDT = new DataTable();
1821
                pathItemsDT.Columns.Add("OID", typeof(string));
1822
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
1823
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
1824
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
1825
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
1826
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
1827
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
1828
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
1829
                pathItemsDT.Columns.Add("Class", typeof(string));
1830
                pathItemsDT.Columns.Add("SubClass", typeof(string));
1831
                pathItemsDT.Columns.Add("TYPE", typeof(string));
1832
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
1833
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
1834
                pathItemsDT.Columns.Add("NPD", typeof(string));
1835
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
1836
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
1837
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
1838
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
1839
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
1840
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
1841
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
1842
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
1843

    
1844
                DataTable sequenceDataDT = new DataTable();
1845
                sequenceDataDT.Columns.Add("OID", typeof(string));
1846
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
1847
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
1848
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1849

    
1850
                DataTable pipeSystemNetworkDT = new DataTable();
1851
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
1852
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
1853
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
1854
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
1855
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
1856
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
1857
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1858
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
1859
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
1860
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
1861
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
1862
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
1863
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
1864
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
1865
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
1866
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
1867
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
1868
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
1869
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
1870

    
1871
                DataTable topologySetDT = new DataTable();
1872
                topologySetDT.Columns.Add("OID", typeof(string));
1873
                topologySetDT.Columns.Add("Type", typeof(string));
1874
                topologySetDT.Columns.Add("SubType", typeof(string));
1875
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
1876
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
1877
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
1878
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
1879

    
1880
                DataTable pipelineDT = new DataTable();
1881
                pipelineDT.Columns.Add("OID", typeof(string));
1882
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
1883
                pipelineDT.Columns.Add("FLUID", typeof(string));
1884
                pipelineDT.Columns.Add("PMC", typeof(string));
1885
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
1886
                pipelineDT.Columns.Add("INSULATION", typeof(string));
1887
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
1888
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
1889
                pipelineDT.Columns.Add("Unit", typeof(string));
1890

    
1891
                DataTable pipesystemDT = new DataTable();
1892
                pipesystemDT.Columns.Add("OID", typeof(string));
1893
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
1894
                pipesystemDT.Columns.Add("FLUID", typeof(string));
1895
                pipesystemDT.Columns.Add("PMC", typeof(string));
1896
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
1897
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
1898

    
1899
                // Set Vent/Drain Info
1900
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1901
                DataTable dt = DB.SelectVentDrainSetting();
1902
                foreach (DataRow row in dt.Rows)
1903
                {
1904
                    string groupID = row["GROUP_ID"].ToString();
1905
                    string desc = row["DESCRIPTION"].ToString();
1906
                    int index = Convert.ToInt32(row["INDEX"]);
1907
                    string name = row["NAME"].ToString();
1908

    
1909
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1910
                    if (ventDrainInfo == null)
1911
                    {
1912
                        ventDrainInfo = new VentDrainInfo(groupID);
1913
                        ventDrainInfo.Description = desc;
1914
                        VentDrainInfos.Add(ventDrainInfo);
1915
                    }
1916

    
1917
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1918
                    {
1919
                        Index = index,
1920
                        Name = name
1921
                    });
1922
                }
1923
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1924
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
1925

    
1926
                #region Keyword Info
1927
                KeywordInfo KeywordInfos = new KeywordInfo();
1928
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1929
                foreach (DataRow row in dtKeyword.Rows)
1930
                {
1931
                    int index = Convert.ToInt32(row["INDEX"]);
1932
                    string name = row["NAME"].ToString();
1933
                    string keyword = row["KEYWORD"].ToString();
1934

    
1935
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1936
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1937
                    {
1938
                        Index = index,
1939
                        Name = name,
1940
                        Keyword = keyword
1941
                    });
1942
                }
1943
                #endregion
1944

    
1945
                #region ValveGrouping Info
1946
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1947
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1948
                foreach (DataRow row in dtValveGroupung.Rows)
1949
                {
1950
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1951
                    {
1952
                        OID = row["OID"].ToString(),
1953
                        GroupType = row["GroupType"].ToString(),
1954
                        TagIdentifier = row["TagIdentifier"].ToString(),
1955
                        AttributeName = row["AttributeName"].ToString(),
1956
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1957
                    });
1958
                }
1959
                #endregion
1960

    
1961
                #region EquipmentNoPocket Info
1962
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
1963
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
1964
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
1965
                {
1966
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
1967
                    {
1968
                        Index = Convert.ToInt32(row["INDEX"]),
1969
                        Type = row["TYPE"].ToString(),
1970
                        Name = row["NAME"].ToString()
1971
                    });
1972
                }
1973
                #endregion
1974

    
1975
                #region EquipmentAirFinCooler Info
1976
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
1977
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
1978
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
1979
                {
1980
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
1981
                    {
1982
                        Type = row["Type"].ToString(),
1983
                        Name = row["Name"].ToString()
1984
                    });
1985
                }
1986
                #endregion
1987

    
1988
                // key = 미입력 branch
1989
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1990
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1991
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
1992
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
1993
                foreach (PSNItem PSNItem in PSNItems)
1994
                {
1995
                    try
1996
                    {
1997
                        int psnOrder = 0;
1998
                        int index = 0;
1999
                        bool bPSNStart = true;
2000
                        string sPSNData = string.Empty;
2001
                        bool bVentDrain = false;
2002

    
2003
                        List<Group> Groups = PSNItem.Groups;
2004
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
2005
                        List<Item> valveGroupingItem = new List<Item>();
2006

    
2007
                        //VentDrain 검사
2008
                        if (PSNItem.Groups.Count.Equals(1))
2009
                        {
2010
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
2011
                            for (int g = 0; g < Groups.Count; g++)
2012
                            {
2013
                                Group group = Groups[g];
2014
                                for (int i = 0; i < group.Items.Count; i++)
2015
                                {
2016
                                    Item item = group.Items[i];
2017
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2018
                                    {
2019
                                        if (endInfos.Contains(ventDrainInfo))
2020
                                            continue;
2021

    
2022
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
2023
                                        {
2024
                                            endInfos.Add(ventDrainInfo);
2025
                                            continue;
2026
                                        }
2027

    
2028
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
2029
                                        {
2030
                                            bVentDrain = true;
2031
                                            break;
2032
                                        }
2033
                                    }
2034

    
2035
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
2036
                                        break;
2037
                                }
2038

    
2039
                                if (!bVentDrain)
2040
                                {
2041
                                    endInfos = new List<VentDrainInfo>();
2042
                                    for (int i = 0; i < group.Items.Count; i++)
2043
                                    {
2044
                                        Item item = group.Items[group.Items.Count - i - 1];
2045
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2046
                                        {
2047
                                            if (endInfos.Contains(ventDrainInfo))
2048
                                                continue;
2049

    
2050
                                            if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
2051
                                            {
2052
                                                endInfos.Add(ventDrainInfo);
2053
                                                continue;
2054
                                            }
2055

    
2056
                                            if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
2057
                                            {
2058
                                                bVentDrain = true;
2059
                                                break;
2060
                                            }
2061
                                        }
2062

    
2063
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
2064
                                            break;
2065
                                    }
2066
                                }
2067
                            }
2068
                        }
2069

    
2070
                        try
2071
                        {
2072
                            foreach (Group group in PSNItem.Groups)
2073
                            {
2074
                                foreach (Item item in group.Items)
2075
                                {
2076
                                    string VgTag = string.Empty;
2077
                                    
2078
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
2079
                                    {
2080
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
2081
                                        string value = string.Empty;
2082

    
2083
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
2084
                                            value = "NoSelection";
2085
                                        else
2086
                                        {
2087
                                            if(item.Attributes.Find(x => x.Name == valveitem.AttributeName) == null)
2088
                                                value = "NoSelection";
2089
                                            else
2090
                                                value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
2091
                                        }
2092

    
2093
                                        if (valveitem.GroupType == "Scope Break")
2094
                                            VgTag = "Scope Break";
2095
                                        else
2096
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
2097

    
2098
                                    }
2099

    
2100
                                    string PathitemUID = string.Empty;
2101
                                    if (item.BranchItems.Count == 0)
2102
                                    {
2103
                                        PathitemUID = item.UID;
2104
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2105
                                        CreateSequenceDataDataRow(PathitemUID);
2106
                                        index++;
2107
                                    }
2108
                                    else
2109
                                    {
2110
                                        PathitemUID = item.UID + "_L1";
2111
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2112
                                        CreateSequenceDataDataRow(PathitemUID);
2113
                                        index++;
2114
                                        for (int i = 0; i < item.BranchItems.Count; i++)
2115
                                        {
2116
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
2117
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
2118
                                            index++;
2119

    
2120
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
2121
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
2122
                                            index++;
2123

    
2124
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
2125
                                                startBranchDic.Add(item.BranchItems[i], item);
2126
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
2127
                                                endBranchDic.Add(item.BranchItems[i], item);
2128
                                        }
2129
                                    }
2130

    
2131
                                    if (bPSNStart)
2132
                                    {
2133
                                        CreatePipeSystemNetworkDataRow();
2134
                                        sPSNData = item.TopologyData;
2135
                                        psnOrder++;
2136
                                        bPSNStart = false;
2137
                                    }
2138
                                    else
2139
                                    {
2140
                                        if (item.TopologyData != sPSNData)
2141
                                        {
2142
                                            CreatePipeSystemNetworkDataRow();
2143
                                            sPSNData = item.TopologyData;
2144
                                            psnOrder++;
2145
                                        }
2146
                                    }
2147

    
2148
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
2149
                                    {
2150
                                        DataRow newRow = pathItemsDT.NewRow();
2151

    
2152
                                        if (itemType == "Nozzles")
2153
                                        {
2154
                                            newRow["Equipment_OID"] = item.Equipment != null ? item.Equipment.UID : "";
2155
                                        }
2156

    
2157
                                        newRow["OID"] = itemOID;
2158
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2159
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
2160
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2161
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2162
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
2163
                                        newRow["ITEMTAG"] = GetItemTag(item);
2164
                                        newRow["Class"] = GetClass(item, itemOID);
2165
                                        string subClass = GetSubClass(item, itemOID);
2166
                                        newRow["SubClass"] = subClass;
2167

    
2168
                                        if (item.ItemType == ItemType.Symbol)
2169
                                            newRow["TYPE"] = item.ID2DBName;
2170
                                        else if (item.ItemType == ItemType.Line)
2171
                                            newRow["TYPE"] = item.ID2DBType;
2172
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2173

    
2174
                                        // NPD
2175
                                        if (item.LineNumber != null)
2176
                                        {
2177
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2178
                                            if (attribute != null)
2179
                                                newRow["NPD"] = attribute.Value;
2180
                                        }
2181
                                        else
2182
                                            newRow["NPD"] = null;
2183

    
2184
                                        newRow["GROUPTAG"] = GROUPTAG;
2185
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2186
                                        if (branchItem == null)
2187
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2188
                                        else
2189
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2190

    
2191
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2192
                                        newRow["EGTConnectedPoint"] = 0;
2193
                                        pathItemsDT.Rows.Add(newRow);
2194
                                    }
2195

    
2196

    
2197
                                    void CreateSequenceDataDataRow(string itemOID)
2198
                                    {
2199
                                        DataRow newRow = sequenceDataDT.NewRow();
2200
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2201
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2202
                                        newRow["PathItem_OID"] = itemOID;
2203
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2204

    
2205
                                        sequenceDataDT.Rows.Add(newRow);
2206
                                    }
2207

    
2208
                                    void CreatePipeSystemNetworkDataRow()
2209
                                    {
2210
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2211
                                        string FluidCode = string.Empty;
2212
                                        if (lineNumber != null)
2213
                                        {
2214
                                            List<Attribute> att = lineNumber.Attributes;
2215
                                            if (att != null)
2216
                                            {
2217
                                                List<string> oid = new List<string>();
2218
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2219
                                                string PMC = lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("PIPINGMATERIALSCLASS")).FirstOrDefault() != null ? lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("PIPINGMATERIALSCLASS")).FirstOrDefault().Value : string.Empty;
2220
                                                string SEQNUMBER = lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("TAG SEQ NO")).FirstOrDefault() != null ? lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("TAG SEQ NO")).FirstOrDefault().Value : string.Empty;
2221
                                                string INSULATION = lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("INSULATIONPURPOSE")).FirstOrDefault() != null ? lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("INSULATIONPURPOSE")).FirstOrDefault().Value : string.Empty;
2222
                                                //InsulationPurpose
2223
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2224
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2225

    
2226
                                                string PipeSystem_OID = string.Join("-", oid);
2227

    
2228
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2229
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2230

    
2231
                                                string OID = string.Join("-", oid);
2232
                                                string FluidCodeGL = string.Empty;
2233
                                                string PMCGL = string.Empty;
2234

    
2235

    
2236
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2237
                                                {
2238
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2239
                                                    newPipelineRow["OID"] = OID;
2240
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2241
                                                    newPipelineRow["FLUID"] = FluidCode;
2242
                                                    newPipelineRow["PMC"] = PMC;
2243
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2244
                                                    newPipelineRow["INSULATION"] = INSULATION;
2245
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2246
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2247
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2248
                                                    pipelineDT.Rows.Add(newPipelineRow);
2249
                                                }
2250

    
2251
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2252
                                                {
2253
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2254
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2255
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2256
                                                    newPipesystemRow["FLUID"] = FluidCode;
2257
                                                    newPipesystemRow["PMC"] = PMC;
2258
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2259
                                                    string GroundLevel = string.Empty;
2260
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2261
                                                    {
2262
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2263
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2264
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2265
                                                            GroundLevel = "AG";
2266
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2267
                                                            GroundLevel = "UG";
2268
                                                        else
2269
                                                            GroundLevel = "AG_UG";
2270
                                                    }
2271
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2272

    
2273
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2274
                                                }
2275
                                            }
2276
                                        }
2277

    
2278
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2279
                                        newRow["OID"] = PSNItem.PSN_OID();
2280

    
2281
                                        newRow["OrderNumber"] = psnOrder;
2282
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2283
                                        PSNItem.KeywordInfos = KeywordInfos;
2284
                                        PSNItem.Nozzle = Nozzle;
2285

    
2286
                                        string FromType = string.Empty;
2287
                                        Item From_item = new Item();
2288

    
2289
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
2290
                                        string status = string.Empty;
2291
                                        if (psnOrder == 0)
2292
                                        {
2293
                                            status = PSNItem.Status;
2294
                                        }
2295

    
2296
                                        if (PSNItem.IsKeyword)
2297
                                        {
2298
                                            PSNItem.StartType = PSNType.Equipment;
2299
                                        }
2300
                                        string ToType = string.Empty;
2301
                                        Item To_item = new Item();
2302
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
2303
                                        if (PSNItem.IsKeyword)
2304
                                        {
2305
                                            PSNItem.EndType = PSNType.Equipment;
2306
                                        }
2307

    
2308
                                        //if (Groups.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
2309
                                        //{
2310
                                        if (!string.IsNullOrEmpty(PSNItem.Status))
2311
                                            status += PSNItem.Status;
2312
                                        //}
2313

    
2314
                                        newRow["FROM_DATA"] = FROM_DATA;
2315
                                        newRow["TO_DATA"] = TO_DATA;
2316
                                        //if(TO_DATA.Contains("Free Vent W-Screen") || TO_DATA.Contains("Empty LineNumber") || FROM_DATA.Contains("Empty LineNumber"))
2317
                                        //{
2318

    
2319
                                        //}
2320
                                        newRow["Type"] = PSNItem.GetPSNType();
2321

    
2322
                                        if (psnOrder > 0)
2323
                                        {
2324
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2325
                                            if (!string.IsNullOrEmpty(PSNItem.Status))
2326
                                            {//status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2327
                                                if (dr["Status"].ToString().Contains(PSNItem.Status))
2328
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
2329
                                                else if (dr["Status"].ToString().Contains(PSNItem.Status.Remove(0, 2)))
2330
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
2331

    
2332
                                            }
2333

    
2334
                                            if (dr != null)
2335
                                            {
2336
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2337
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2338
                                                newRow["Type"] = dr.Field<string>("Type");
2339
                                            }
2340
                                        }
2341

    
2342
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2343
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
2344
                                        {
2345
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
2346
                                            int cnt = matches.Count;
2347
                                            if (cnt > 1)
2348
                                                status.Replace(", Missing LineNumber_1", string.Empty);
2349
                                        }
2350
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2351
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
2352

    
2353

    
2354
                                        newRow["IsValid"] = PSNItem.IsValid;
2355
                                        newRow["Status"] = status;
2356
                                        newRow["PBS"] = PSNItem.GetPBSData();
2357

    
2358
                                        List<string> drawingNames = new List<string>();
2359
                                        foreach (Group _group in PSNItem.Groups)
2360
                                        {
2361
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2362
                                            {
2363
                                                if (drawingNames.Count == 0)
2364
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2365
                                                else
2366
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2367
                                                drawingNames.Add(_group.Document.DrawingName);
2368
                                            }
2369
                                        }
2370

    
2371
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2372
                                        if (bVentDrain)
2373
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2374
                                        else
2375
                                            newRow["IncludingVirtualData"] = "No";
2376
                                        //    return;
2377
                                        //newRow["IncludingVirtualData"] = "No";
2378
                                        newRow["PSNAccuracy"] = "100";
2379

    
2380
                                        string Pocket = "No";
2381
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2382
                                        if (Condition.Equals("Flare"))
2383
                                            Pocket = "Yes";
2384

    
2385
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null) 
2386
                                        {
2387
                                          //  string itemName = From_item.Name;
2388
                                            Equipment Equipment = From_item.Equipment;
2389
                                      
2390
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2391
                                          
2392

    
2393
                                            if (nopocket != null)
2394
                                            {
2395
                                                DataRow bNozzle = null;
2396
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2397
                                                {
2398
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2399
                                                    if (drNozzle != null)
2400
                                                    {
2401
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2402
                                                        {
2403
                                                            bNozzle = drNozzle;
2404
                                                        }
2405

    
2406
                                                        if (bNozzle == null)
2407
                                                        {
2408
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2409

    
2410
                                                            if (drNozzle != null)
2411
                                                            {
2412
                                                                bNozzle = drNozzle;
2413
                                                                foreach (DataRow it in nozzleRows)
2414
                                                                {
2415
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2416
                                                                    {
2417
                                                                        bNozzle = null;
2418
                                                                        break;
2419
                                                                    }
2420
                                                                }
2421
                                                            }
2422
                                                        }
2423
                                                    }
2424

    
2425
                                                    if (bNozzle != null)
2426
                                                        Pocket = "Yes";
2427
                                                }
2428
                                                else
2429
                                                    Pocket = "Yes";
2430
                                            }
2431
                                        }
2432
                                        
2433
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null) //To는 전체
2434
                                        {
2435
                                           // string itemName = To_item.Name;
2436
                                            Equipment Equipment = To_item.Equipment;
2437
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2438
                                            if (nopocket != null)
2439
                                            {
2440
                                                DataRow bNozzle = null;
2441
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2442
                                                {
2443
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2444
                                                    if(drNozzle != null)
2445
                                                    {
2446
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2447
                                                        {
2448
                                                            bNozzle = drNozzle;
2449
                                                        }
2450

    
2451
                                                        if (bNozzle == null)
2452
                                                        {
2453
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2454

    
2455
                                                            if (drNozzle != null)
2456
                                                            {
2457
                                                                bNozzle = drNozzle;
2458
                                                                foreach (DataRow it in nozzleRows)
2459
                                                                {
2460
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2461
                                                                    {
2462
                                                                        bNozzle = null;
2463
                                                                        break;
2464
                                                                    }
2465
                                                                }
2466
                                                            }
2467
                                                        }
2468
                                                    }                                                   
2469

    
2470
                                                    if (bNozzle != null)
2471
                                                        Pocket = "Yes";
2472
                                                }
2473
                                                else
2474
                                                    Pocket = "Yes";
2475
                                            }
2476
                                        }
2477
                                        
2478
                                        newRow["Pocket"] = Pocket;
2479
                                        string AFC = "P2";
2480
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2481
                                        {
2482
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2483
                                                AFC = "P1\\" + From_item.Equipment.Name;
2484
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2485
                                                newRow["PUMP"] = "PUMP";
2486
                                        }
2487

    
2488
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2489
                                        {
2490
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2491
                                                AFC = "P1\\" + To_item.Equipment.Name;
2492
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2493
                                                newRow["PUMP"] = "PUMP";
2494
                                        }
2495

    
2496
                                        newRow["AFC"] = AFC;
2497

    
2498
                                        newRow["EGTag"] = string.Empty;
2499
                                        newRow["HasMLTags"] = "False";
2500
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2501
                                    }
2502
                                }
2503

    
2504
                            }
2505
                        
2506

    
2507
                        }
2508
                        catch (Exception ex)
2509
                        {
2510
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2511
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2512
                        }
2513

    
2514
                        //TopologySet 관련
2515
                        foreach (Topology topology in PSNItem.Topologies)
2516
                        {
2517
                            DataRow newRow = topologySetDT.NewRow();
2518
                            newRow["OID"] = topology.FullName;
2519
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
2520
                            if (bVentDrain)
2521
                                newRow["SubType"] = "Vent_Drain";
2522
                            else
2523
                                newRow["SubType"] = null;
2524
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
2525
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
2526
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
2527
                            newRow["TailItemSPID"] = topology.Items.First().UID;
2528
                            topologySetDT.Rows.Add(newRow);
2529
                        }
2530

    
2531
                    }
2532
                    catch (Exception ee)
2533
                    {
2534

    
2535
                    }
2536
                }
2537

    
2538

    
2539
                foreach (var item in startBranchDic)
2540
                {
2541
                    string uid = item.Key.UID;
2542
                    string topologyName = item.Value.Topology.FullName;
2543
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2544

    
2545
                    if (rows.Length == 1)
2546
                    {
2547
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2548
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2549
                    }
2550
                    else if (rows.Length > 1)
2551
                    {
2552
                        DataRow targetRow = null;
2553
                        int index = int.MaxValue;
2554
                        foreach (DataRow row in rows)
2555
                        {
2556
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2557
                            if (split.StartsWith("L"))
2558
                            {
2559
                                int num = Convert.ToInt32(split.Remove(0, 1));
2560
                                if (index > num)
2561
                                {
2562
                                    index = num;
2563
                                    targetRow = row;
2564
                                }
2565
                            }
2566
                        }
2567

    
2568
                        if (targetRow != null)
2569
                        {
2570
                            targetRow["BranchTopologySet_OID"] = topologyName;
2571
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2572
                        }
2573
                    }
2574
                }
2575

    
2576
                foreach (var item in endBranchDic)
2577
                {
2578
                    string uid = item.Key.UID;
2579
                    string topologyName = item.Value.Topology.FullName;
2580
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2581
                    if (rows.Length == 1)
2582
                    {
2583
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2584
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2585
                    }
2586
                    else if (rows.Length > 1)
2587
                    {
2588
                        DataRow targetRow = null;
2589
                        int index = int.MinValue;
2590
                        foreach (DataRow row in rows)
2591
                        {
2592
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2593
                            if (split.StartsWith("L"))
2594
                            {
2595
                                int num = Convert.ToInt32(split.Remove(0, 1));
2596
                                if (index < num)
2597
                                {
2598
                                    index = num;
2599
                                    targetRow = row;
2600
                                }
2601
                            }
2602
                        }
2603

    
2604
                        if (targetRow != null)
2605
                        {
2606
                            targetRow["BranchTopologySet_OID"] = topologyName;
2607
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2608
                        }
2609
                    }
2610
                }
2611

    
2612
                PathItems = pathItemsDT;
2613
                SequenceData = sequenceDataDT;
2614
                PipeSystemNetwork = pipeSystemNetworkDT;
2615
                TopologySet = topologySetDT;
2616
                PipeLine = pipelineDT;
2617
                PipeSystem = pipesystemDT;
2618
            }
2619
            catch (Exception ex)
2620
            {
2621
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2622
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2623
            }
2624
        }
2625

    
2626
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2627
        {
2628
            foreach (double lacc in lstAcc)
2629
            {
2630
                acc *= lacc;
2631
            }
2632
            return acc;
2633
        }
2634

    
2635
        private void UpdateSubType()
2636
        {
2637
            try
2638
            {
2639
                foreach (PSNItem PSNItem in PSNItems)
2640
                {
2641
                    if (PSNItem.IsBypass)
2642
                    {
2643
                        foreach (Topology topology in PSNItem.Topologies)
2644
                        {
2645
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2646
                            if (rows.Length.Equals(1))
2647
                                rows.First()["SubType"] = "Bypass";
2648
                        }
2649
                    }
2650

    
2651
                    if (PSNItem.StartType == PSNType.Header)
2652
                    {
2653
                        Topology topology = PSNItem.Topologies.First();
2654
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2655
                        if (rows.Length.Equals(1))
2656
                            rows.First()["SubType"] = "Header";
2657
                    }
2658
                    else if (PSNItem.EndType == PSNType.Header)
2659
                    {
2660
                        Topology topology = PSNItem.Topologies.Last();
2661
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2662
                        if (rows.Length.Equals(1))
2663
                            rows.First()["SubType"] = "Header";
2664
                    }
2665
                }
2666

    
2667

    
2668
                foreach (Topology topology in Topologies)
2669
                {
2670
                    try
2671
                    {
2672
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2673

    
2674
                        if (rows.Count() > 0)
2675
                        {
2676
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2677
                            {
2678
                                if (topology.Items == null)
2679
                                    continue;
2680

    
2681
                                Item firstItem = topology.Items.First();
2682
                                Item lastItem = topology.Items.Last();
2683

    
2684
                                List<Relation> relations = new List<Relation>();
2685

    
2686
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2687
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2688

    
2689
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2690
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2691

    
2692
                                if (relations.Count > 0)
2693
                                    rows.First()["SubType"] = "OtherSystem";
2694
                            }
2695
                        }
2696
                    }
2697
                    catch (Exception ex)
2698
                    {
2699

    
2700
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2701
                    }
2702
                }
2703

    
2704
                foreach (DataRow row in TopologySet.Rows)
2705
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
2706
                        row["SubType"] = "Normal";
2707
            }
2708
            catch (Exception ex)
2709
            {
2710
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2711
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2712
            }
2713
        }
2714

    
2715
        private bool IsBypass(PSNItem PSNItem)
2716
        {
2717
            bool bResult = false;
2718

    
2719
            if (PSNItem.GetPSNType() == "B2B")
2720
            {
2721
                Group firstGroup = PSNItem.Groups.First();
2722
                Group lastGroup = PSNItem.Groups.Last();
2723
                Item firstItem = firstGroup.Items.First();
2724
                Item lastItem = lastGroup.Items.Last();
2725

    
2726
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
2727
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
2728

    
2729
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
2730
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
2731
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
2732
                    bResult = true;
2733
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
2734
                    bResult = true;
2735
            }
2736

    
2737
            Item GetConnectedItemByPSN(Item item)
2738
            {
2739
                Item result = null;
2740

    
2741
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
2742
                if (relation != null)
2743
                    result = relation.Item;
2744

    
2745

    
2746
                return result;
2747
            }
2748

    
2749
            return bResult;
2750
        }
2751

    
2752
        private void DeleteVentDrain()
2753
        {
2754
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
2755

    
2756
            foreach (DataRow dataRow in ventdrainRows)
2757
            {
2758
                dataRow.Delete();
2759
            }
2760
        }
2761

    
2762
        private void UpdateAccuracy()
2763
        {
2764
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
2765
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
2766
            List<double> lstAcc = null;
2767
            string Status = string.Empty;
2768

    
2769
            foreach (DataRow dataRow in statusRows)
2770
            {
2771
                lstAcc = new List<double>();
2772
                Status = dataRow.Field<string>("Status");
2773
                if (!string.IsNullOrEmpty(Status))
2774
                {
2775
                    string[] arrStatus = Status.Split(',');
2776
                    foreach (string arrstr in arrStatus)
2777
                    {
2778
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
2779
                            lstAcc.Add(0.75);
2780

    
2781
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2782
                            lstAcc.Add(0.7);
2783

    
2784
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2785
                            lstAcc.Add(0.5);
2786

    
2787
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2788
                            lstAcc.Add(0.65);
2789

    
2790
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2791
                            lstAcc.Add(0.6);
2792
                    }
2793
                }
2794

    
2795
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
2796
                if (PSNAccuracy == "100")
2797
                    PSNAccuracy = "1";
2798

    
2799
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
2800
                //if (PSNAccuracy != "100")
2801
                //{
2802
                //    //dataRow["IncludingVirtualData"] = "No";
2803
                dataRow["PSNAccuracy"] = PSNAccuracy;
2804
                //}
2805
            }
2806
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
2807
            foreach (DataRow dr in dt.Rows)
2808
            {
2809
                string oid = dr.Field<string>("OID");
2810
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
2811
                double totalDdr = 0;
2812
                foreach (DataRow ddr in select)
2813
                {
2814
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
2815
                    if (acc == 100) acc = 1;
2816
                    if (totalDdr == 0) totalDdr = acc;
2817
                    else totalDdr *= acc;
2818
                }
2819

    
2820
                totalDdr *= 100;
2821

    
2822
                if (totalDdr != 100)
2823
                {
2824
                    foreach (DataRow ddr in select)
2825
                    {
2826
                        ddr["IncludingVirtualData"] = "Yes";
2827
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2828
                    }
2829
                }
2830
                else
2831
                {
2832
                    foreach (DataRow ddr in select)
2833
                    {
2834
                        ddr["IncludingVirtualData"] = "No";
2835
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2836
                    }
2837
                }
2838
            }
2839

    
2840
        }
2841

    
2842
        private void UpdateKeywordForPSN()
2843
        {
2844
            #region Keyword Info
2845
            KeywordInfo KeywordInfos = new KeywordInfo();
2846
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2847
            foreach (DataRow row in dtKeyword.Rows)
2848
            {
2849
                int index = Convert.ToInt32(row["INDEX"]);
2850
                string name = row["NAME"].ToString();
2851
                string keyword = row["KEYWORD"].ToString();
2852

    
2853
                //KeywordInfo keywordInfo = new KeywordInfo();   
2854
                KeywordInfos.KeywordItems.Add(new KeywordItem()
2855
                {
2856
                    Index = index,
2857
                    Name = name,
2858
                    Keyword = keyword
2859
                });
2860
            }
2861
            #endregion
2862

    
2863
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
2864
            foreach (DataRow dataRow in endofHeaderRows)
2865
            {
2866
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2867

    
2868
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
2869
                {
2870
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2871
                    DataRow dr = pathItemRows.First();
2872
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
2873
                    dr["TYPE"] = "End";
2874
                    dr["ITEMTAG"] = "ENDOFHEADER";
2875
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2876
                }
2877

    
2878
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
2879
                {
2880
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2881
                    DataRow dr = pathItemRows.Last();
2882
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
2883
                    dr["TYPE"] = "End";
2884
                    dr["ITEMTAG"] = "ENDOFHEADER";
2885
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2886
                }
2887
            }
2888

    
2889
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2890
            {
2891
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
2892
                foreach (DataRow dataRow in keywordRows)
2893
                {
2894
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2895

    
2896
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
2897
                    {
2898
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2899

    
2900
                        //
2901
                        //if(.)
2902
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
2903
                        {
2904
                            DataRow dr = pathItemRows.First();
2905
                            //dr["CLASS"] = ""; //Type
2906
                            dr["TYPE"] = "End";
2907
                            dr["ITEMTAG"] = keyitem.Keyword;
2908
                            dr["DESCRIPTION"] = keyitem.Keyword;
2909
                        }
2910

    
2911
                    }
2912

    
2913
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
2914
                    {
2915
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2916

    
2917
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
2918
                        {
2919
                            DataRow dr = pathItemRows.Last();
2920
                            //dr["CLASS"] = ""; //Type
2921
                            dr["TYPE"] = "End";
2922
                            dr["ITEMTAG"] = keyitem.Keyword;
2923
                            dr["DESCRIPTION"] = keyitem.Keyword;
2924
                            //dr.Field<string>("Type")
2925
                        }
2926

    
2927
                    }
2928
                }
2929
            }
2930
        }
2931

    
2932
        private void UpdateErrorForPSN()
2933
        {
2934
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
2935
            foreach (DataRow dataRow in errorRows)
2936
            {
2937
                try
2938
                {
2939
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2940
                   
2941
                    bool change = false;
2942
                    bool bCheck = false;
2943
                    if (!PSNItem.EnableType(PSNItem.StartType))
2944
                    {
2945
                        change = true;
2946
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2947
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2948

    
2949
                        Item item = PSNItem.Groups.First().Items.First();
2950
                        try
2951
                        {
2952
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2953

    
2954
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2955
                            {
2956
                                loopRow["FROM_DATA"] = FROM_DATA;
2957
                                if (item.ItemType == ItemType.Line)
2958
                                {
2959
                                    if (loopRow.Field<string>("OrderNumber") == "0")
2960
                                    {
2961
                                        string status = loopRow.Field<string>("Status");
2962
                                        //string isvali
2963
                                        if (string.IsNullOrEmpty(status))
2964
                                            status = "Line Disconnected";
2965
                                        else if (!status.Contains("Line Disconnected"))
2966
                                            status += ", Line Disconnected";
2967
                                        loopRow["Status"] = status;
2968
                                        if (!string.IsNullOrEmpty(status))
2969
                                            loopRow["IsValid"] = "Error";
2970
                                    }
2971
                                }
2972
                            }
2973

    
2974
                            tieInPointIndex++;
2975

    
2976
                            if (item.ItemType == ItemType.Line)
2977
                            {
2978
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);                                
2979
                            }
2980
                            else
2981
                            {
2982
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
2983
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2984

    
2985
                                bCheck = true;
2986
                            }
2987

    
2988
                            PSNItem.StartType = PSNType.Equipment;
2989
                        }
2990
                        catch (Exception ex)
2991
                        {
2992
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2993
                            return;
2994
                        }
2995
                    }
2996

    
2997
                    if (!PSNItem.EnableType(PSNItem.EndType))
2998
                    {                        
2999
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3000
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
3001
                        DataRow dr = pathItemRows.Last();
3002
                        if (change)
3003
                        {
3004
                            if(bCheck)
3005
                                dr = pathItemRows[pathItemRows.Count() - 3];
3006
                            else
3007
                            {
3008
                                dr = pathItemRows[pathItemRows.Count() - 2];
3009
                            }
3010
                        }
3011

    
3012
                        change = true;
3013
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3014

    
3015
                        Item item = PSNItem.Groups.Last().Items.Last();
3016
                        try
3017
                        {
3018
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3019

    
3020
                           
3021
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3022
                            {
3023
                                loopRow["TO_DATA"] = TO_DATA;
3024
                                if (item.ItemType == ItemType.Line)
3025
                                {
3026
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
3027
                                    {
3028
                                        string status = loopRow.Field<string>("Status");
3029
                                        if (string.IsNullOrEmpty(status))
3030
                                            status = "Line Disconnected";
3031
                                        else if (!status.Contains("Line Disconnected"))
3032
                                            status += ", Line Disconnected";
3033
                                        loopRow["Status"] = status;
3034
                                        if (!string.IsNullOrEmpty(status))
3035
                                            loopRow["IsValid"] = "Error";
3036
                                    }
3037
                                }
3038
                            }                            
3039

    
3040
                            tieInPointIndex++;
3041

    
3042
                            if (item.ItemType == ItemType.Line)
3043
                            {
3044
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3045
                            }
3046
                            else
3047
                            {
3048
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3049
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
3050
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
3051
                            }
3052

    
3053
                            PSNItem.EndType = PSNType.Equipment;
3054
                        }
3055
                        catch (Exception ex)
3056
                        {
3057
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3058
                            return;
3059
                        }
3060
                    }
3061

    
3062
                    dataRow["Type"] = PSNItem.GetPSNType();
3063
                    if (change)
3064
                    {
3065
                        int rowIndex = 0;
3066
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3067
                        {
3068
                            DataRow row = PathItems.Rows[i];
3069
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
3070
                                continue;
3071
                            string sequenceData = row["SequenceData_OID"].ToString();
3072
                            string[] split = sequenceData.Split(new char[] { '_' });
3073

    
3074
                            StringBuilder sb = new StringBuilder();
3075
                            for (int j = 0; j < split.Length - 1; j++)
3076
                                sb.Append(split[j] + "_");
3077
                            sb.Append(rowIndex++);
3078
                            row["SequenceData_OID"] = sb.ToString();
3079

    
3080
                            DataRow seqItemRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", row["OID"])).FirstOrDefault();
3081
                            int insertSeqIndex = SequenceData.Rows.IndexOf(seqItemRows);
3082

    
3083
                            string[] splitseq = sb.ToString().Split(new char[] { '_' });
3084

    
3085
                            if (seqItemRows == null)
3086
                            {
3087
                                DataRow newRow = SequenceData.NewRow();
3088
                                newRow["OID"] = sb.ToString();
3089
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3090
                                newRow["PathItem_OID"] = row["OID"];
3091
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3092
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3093
                            }
3094
                            else
3095
                            {
3096
                                seqItemRows["OID"] = sb.ToString();
3097
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3098
                                seqItemRows["PathItem_OID"] = row["OID"];
3099
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3100
                            }
3101
                        }
3102
                    }
3103

    
3104
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
3105
                    {
3106
                        DataRow newRow = PathItems.NewRow();
3107
                        newRow["OID"] = Guid.NewGuid().ToString();
3108
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3109
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3110
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3111
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3112
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
3113
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
3114
                        newRow["DESCRIPTION"] = DATA;
3115
                        newRow["Class"] = "End of line terminator";
3116
                        newRow["SubClass"] = "End of line terminator";
3117
                        newRow["TYPE"] = "End";
3118
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3119
                        newRow["NPD"] = itemRow["NPD"];
3120
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3121
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3122
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3123
                        newRow["EGTConnectedPoint"] = "0";
3124
                        return newRow;
3125
                    }
3126

    
3127
                    DataRow createLineRow(DataRow itemRow)
3128
                    {
3129
                        DataRow newRow = PathItems.NewRow();
3130
                        newRow["OID"] = Guid.NewGuid().ToString();
3131
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3132
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3133
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3134
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3135
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
3136
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3137
                        newRow["Class"] = itemRow["Class"];
3138
                        newRow["SubClass"] = itemRow["SubClass"];
3139
                        newRow["TYPE"] = itemRow["TYPE"];
3140
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3141
                        newRow["NPD"] = itemRow["NPD"];
3142
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3143
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3144
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3145
                        newRow["EGTConnectedPoint"] = "0";
3146
                        return newRow;
3147
                    }
3148
                }
3149
                catch (Exception ex)
3150
                {
3151

    
3152
                }
3153
            }
3154
        }
3155

    
3156
        private void InsertTeePSN()
3157
        {
3158
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
3159
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
3160
            bool change = false;
3161
            foreach (DataRow dataRow in branchRows)
3162
            {
3163
                try
3164
                {
3165
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3166
                    change = false;
3167

    
3168
                    if (PSNItem.StartType == PSNType.Branch)
3169
                    {
3170
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3171
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3172
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3173
                        try
3174
                        {
3175
                            if (Teeitem.ItemType == ItemType.Line)
3176
                            {
3177
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3178
                                {
3179
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3180
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3181
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3182
                                    change = true;
3183
                                }
3184

    
3185
                            }
3186
                        }
3187
                        catch (Exception ex)
3188
                        {
3189
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3190
                            return;
3191
                        }
3192
                    }
3193

    
3194
                    if (PSNItem.EndType == PSNType.Branch)
3195
                    {
3196
                        //change = true;
3197
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3198

    
3199
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3200

    
3201
                        DataRow dr = pathItemRows.Last();
3202
                        if (change)
3203
                            dr = pathItemRows[pathItemRows.Count() - 2];
3204

    
3205
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3206

    
3207
                        try
3208
                        {
3209
                            if (Teeitem.ItemType == ItemType.Line)
3210
                            {
3211
                                if (dr.Field<string>("SubClass") != "Tee")
3212
                                {
3213
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3214
                                    change = true;
3215
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3216
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3217
                                }
3218

    
3219
                            }
3220
                        }
3221
                        catch (Exception ex)
3222
                        {
3223
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3224
                            return;
3225
                        }
3226
                    }
3227

    
3228
                    if (change)
3229
                    {
3230
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3231
                        int rowIndex = 0;
3232
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3233
                        {
3234
                            DataRow row = PathItems.Rows[i];
3235
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3236
                                continue;
3237
                            string sequenceData = row["SequenceData_OID"].ToString();
3238
                            string[] split = sequenceData.Split(new char[] { '_' });
3239

    
3240
                            StringBuilder sb = new StringBuilder();
3241
                            for (int j = 0; j < split.Length - 1; j++)
3242
                                sb.Append(split[j] + "_");
3243
                            sb.Append(rowIndex++);
3244
                            row["SequenceData_OID"] = sb.ToString();
3245

    
3246
                            DataRow seqItemRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", row["OID"])).FirstOrDefault();
3247
                            int insertSeqIndex = SequenceData.Rows.IndexOf(seqItemRows);
3248

    
3249
                            string[] splitseq = sb.ToString().Split(new char[] { '_' });
3250

    
3251
                            if (seqItemRows == null)
3252
                            {
3253
                                DataRow newRow = SequenceData.NewRow();
3254
                                newRow["OID"] = sb.ToString();
3255
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3256
                                newRow["PathItem_OID"] = row["OID"];
3257
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3258
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3259
                            }
3260
                            else
3261
                            {
3262
                                seqItemRows["OID"] = sb.ToString();
3263
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3264
                                seqItemRows["PathItem_OID"] = row["OID"];
3265
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3266
                            }
3267
                        }
3268
                    }
3269

    
3270
                    DataRow createTeeRow(DataRow itemRow)
3271
                    {
3272
                        DataRow newRow = PathItems.NewRow();
3273
                        newRow["OID"] = Guid.NewGuid().ToString();
3274
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3275
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3276
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3277
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3278
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3279
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3280
                        newRow["DESCRIPTION"] = "";
3281
                        newRow["Class"] = "Branch";
3282
                        newRow["SubClass"] = "Tee";
3283
                        newRow["TYPE"] = itemRow["TYPE"];
3284
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3285
                        newRow["NPD"] = itemRow["NPD"];
3286
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3287
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3288
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3289
                      
3290
                        newRow["EGTConnectedPoint"] = 0;
3291
                        return newRow;
3292
                    }
3293
                }
3294
                catch (Exception ex)
3295
                {
3296

    
3297
                }
3298
            }
3299
        }
3300
    }
3301

    
3302
    public class PSNItem
3303
    {
3304
        public PSNItem(int count, int Revision)
3305
        {
3306
            Groups = new List<Group>();
3307
            Topologies = new List<Topology>();
3308

    
3309
            Index = count + 1;
3310
            this.Revision = Revision;
3311
        }
3312

    
3313
        private int Revision;
3314
        public string UID { get; set; }
3315
        public List<Group> Groups { get; set; }
3316
        public List<Topology> Topologies { get; set; }
3317
        public PSNType StartType { get; set; }
3318
        public PSNType EndType { get; set; }
3319
        public int Index { get; set; }
3320
        public string IsValid { get; set; }
3321
        public bool IsKeyword { get; set; }
3322
        public string Status { get; set; }
3323
        public string IncludingVirtualData { get; set; }
3324
        public string PSNAccuracy { get; set; }
3325
        public KeywordInfo KeywordInfos = new KeywordInfo();
3326
        public DataTable Nozzle = new DataTable();
3327

    
3328
        public string PSN_OID()
3329
        {
3330
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
3331
        }
3332

    
3333
        public string GetPSNType()
3334
        {
3335
            string result = string.Empty;
3336

    
3337
            if (EnableType(StartType) && EnableType(EndType))
3338
            {
3339
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
3340
                    result = "E2E";
3341
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
3342
                    result = "B2B";
3343
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
3344
                    result = "HD2";
3345

    
3346
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
3347
                    result = "E2B";
3348
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
3349
                    result = "B2E";
3350

    
3351
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
3352
                    result = "HDB";
3353
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
3354
                    result = "HDB";
3355

    
3356
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
3357
                    result = "HDE";
3358
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
3359
                    result = "HDE";
3360
                else
3361
                    result = "Error";
3362
            }
3363
            else
3364
                result = "Error";
3365

    
3366
            return result;
3367

    
3368

    
3369
        }
3370

    
3371
        public bool EnableType(PSNType type)
3372
        {
3373
            bool result = false;
3374

    
3375
            if (type == PSNType.Branch ||
3376
                type == PSNType.Equipment ||
3377
                type == PSNType.Header)
3378
            {
3379
                result = true;
3380
            }
3381

    
3382
            return result;
3383
        }
3384

    
3385
        public bool IsBypass { get; set; }
3386

    
3387
        public string GetFromData(ref string Type, ref Item item)
3388
        {
3389
            Status = string.Empty;
3390
            string result = string.Empty;
3391
            if (IsKeyword)
3392
                IsKeyword = false;
3393
            try
3394
            {
3395
                item = Groups.First().Items.First();
3396

    
3397
                if (StartType == PSNType.Header)
3398
                    result = "ENDOFHEADER";
3399
                else if (StartType == PSNType.Branch)
3400
                {
3401
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3402
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3403
                        result = item.Relations.First().Item.LineNumber.Name;
3404
                    else
3405
                    {
3406
                        IsValid = "Error";
3407
                        result = "Empty LineNumber";
3408
                    }
3409

    
3410
                    if (item.MissingLineNumber2)
3411
                        Status += ", Missing LineNumber_2";
3412

    
3413

    
3414
                    //if (item.MissingLineNumber1)
3415
                    //{
3416
                    //    Status += ", Missing LineNumber_1";
3417
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3418

    
3419
                    //}
3420
                }
3421
                else if (StartType == PSNType.Equipment)
3422
                {
3423
                    if (Groups.First().Items.First().Equipment != null)
3424
                        result = Groups.First().Items.First().Equipment.ItemTag;
3425
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
3426

    
3427
                    if (drNozzle != null)
3428
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3429
                }
3430
                else
3431
                {
3432
                    IsValid = "Error";
3433
                    item = Groups.First().Items.First();
3434
                    if (item.ItemType == ItemType.Symbol)
3435
                    {
3436

    
3437
                        string keyword = string.Empty;
3438
                        keyword = GetFromKeywordData(ref Type, item);
3439

    
3440
                        if (string.IsNullOrEmpty(keyword))
3441
                        {
3442
                            if (item.ID2DBType.Contains("OPC's"))
3443
                                Status += ", OPC Disconnected";
3444
                            else
3445
                                Status += ", Missing ItemTag or Description";
3446

    
3447
                            result = item.ID2DBName;
3448
                        }
3449
                        else
3450
                        {
3451
                            result = keyword;
3452
                            IsKeyword = true;
3453
                            IsValid = string.Empty;
3454
                        }
3455

    
3456
                    }
3457
                    else if (item.ItemType == ItemType.Line)
3458
                    {
3459

    
3460
                        if (item.MissingLineNumber1)
3461
                        {
3462
                            IsValid = "Error";
3463
                            Status += ", Missing LineNumber_1";
3464
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3465
                        }
3466
                        else
3467
                            result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3468
                    }
3469
                    else
3470
                        result = "Unknown";
3471

    
3472
                }
3473
            }
3474
            catch (Exception ex)
3475
            {
3476

    
3477
            }
3478

    
3479
            return result;
3480
        }
3481

    
3482
        public string GetFromKeywordData(ref string Type, Item item)
3483
        {
3484
            string result = string.Empty;
3485

    
3486
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3487
            {
3488
                if (keyitem.Name.Equals(item.Name))
3489
                {
3490
                    result = keyitem.Keyword;
3491
                    Type = item.ID2DBType;
3492
                    break;
3493
                }
3494
            }
3495

    
3496
            return result;
3497
        }
3498

    
3499
        public string GetToKeywordData(ref string Type, Item item)
3500
        {
3501
            string result = string.Empty;
3502

    
3503
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3504
            {
3505
                if (keyitem.Name.Equals(item.Name))
3506
                {
3507
                    result = keyitem.Keyword;
3508
                    Type = item.ID2DBType;
3509
                    break;
3510
                }
3511
            }
3512
            return result;
3513
        }
3514

    
3515
        public string GetToData(ref string ToType, ref Item item)
3516
        {
3517
            string result = string.Empty;
3518
            Status = string.Empty;
3519

    
3520
            if (IsKeyword)
3521
                IsKeyword = false;
3522

    
3523
            item = Groups.Last().Items.Last();
3524

    
3525
            if (EndType == PSNType.Header)
3526
                result = "ENDOFHEADER";
3527
            else if (EndType == PSNType.Branch)
3528
            {
3529
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3530
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3531
                    result = item.Relations.Last().Item.LineNumber.Name;
3532
                else
3533
                {
3534
                    IsValid = "Error";                    
3535
                    result = "Empty LineNumber";
3536
                }
3537

    
3538
                if(item.MissingLineNumber2)
3539
                    Status += ", Missing LineNumber_2";
3540
                //if (item.MissingLineNumber1)
3541
                //{
3542
                //    Status += ", Missing LineNumber_1";
3543
                //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3544

    
3545
                //}
3546
            }
3547
            else if (EndType == PSNType.Equipment)
3548
            {
3549
                if (Groups.Last().Items.Last().Equipment != null)
3550
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3551

    
3552
                DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.Last().Items.Last().UID)).FirstOrDefault();
3553

    
3554
                if (drNozzle != null)
3555
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3556
            }
3557
            else
3558
            {
3559
                IsValid = "Error";
3560
                item = Groups.Last().Items.Last();
3561
                if (item.ItemType == ItemType.Symbol)
3562
                {
3563
                    string keyword = string.Empty;
3564
                    keyword = GetToKeywordData(ref ToType, item);
3565

    
3566
                    if (string.IsNullOrEmpty(keyword))
3567
                    {
3568
                        if (item.ID2DBType.Contains("OPC's"))
3569
                            Status += ", OPC Disconnected";
3570
                        else
3571
                            Status += ", Missing ItemTag or Description";
3572

    
3573
                        result = item.ID2DBName;
3574
                    }
3575
                    else
3576
                    {
3577
                        result = keyword;
3578
                        IsValid = string.Empty;
3579
                        IsKeyword = true;
3580
                    }
3581

    
3582
                }
3583
                else if (item.ItemType == ItemType.Line)
3584
                {
3585
                    if (item.MissingLineNumber1)
3586
                    {
3587
                        IsValid = "Error";
3588
                        Status += ", Missing LineNumber_1";
3589
                        result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3590
                    }
3591
                    else
3592
                        result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3593
                }
3594
                else
3595
                    result = "Unknown";
3596

    
3597

    
3598
            }
3599

    
3600

    
3601

    
3602
            return result;
3603
        }
3604

    
3605
        public string GetPBSData()
3606
        {
3607
            string result = string.Empty;
3608
            List<string> PBSList = new List<string>();
3609
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3610
            {
3611
                string attrValue = Settings.Default.PBSSettingValue;
3612

    
3613
                foreach (Group group in Groups)
3614
                {
3615
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3616
                    foreach (LineNumber lineNumber in lineNumbers)
3617
                    {
3618
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3619
                        if (attribute != null)
3620
                        {
3621
                            string value = attribute.Value;
3622
                            if (!PBSList.Contains(value))
3623
                                PBSList.Add(value);
3624
                        }
3625
                    }
3626
                }
3627
            }
3628
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3629
            {
3630
                string attrValue = Settings.Default.PBSSettingValue;
3631

    
3632
                foreach (Group group in Groups)
3633
                {
3634
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3635
                    foreach (Item item in items)
3636
                    {
3637
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3638
                        if (!PBSList.Contains(value))
3639
                            PBSList.Add(value);
3640
                    }
3641
                }
3642
            }
3643
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3644
            {
3645
                string attrValue = Settings.Default.PBSSettingValue;
3646

    
3647
                foreach (Group group in Groups)
3648
                {
3649
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3650
                    foreach (Document document in documents)
3651
                    {
3652
                        string name = document.DrawingName;
3653

    
3654
                        int startIndex = Settings.Default.PBSSettingStartValue;
3655
                        int endIndex = Settings.Default.PBSSettingEndValue;
3656

    
3657
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3658
                        if (!PBSList.Contains(subStr))
3659
                            PBSList.Add(subStr);
3660
                    }
3661
                }
3662
            }
3663
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3664
            {
3665
                foreach (Group group in Groups)
3666
                {
3667
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3668
                    foreach (Document document in documents)
3669
                    {
3670
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
3671
                        foreach (TextInfo textInfo in textInfos)
3672
                        {
3673
                            if (!PBSList.Contains(textInfo.Value))
3674
                                PBSList.Add(textInfo.Value);
3675
                        }
3676
                    }
3677
                }
3678
            }
3679

    
3680
            foreach (var item in PBSList)
3681
            {
3682
                if (string.IsNullOrEmpty(result))
3683
                    result = item;
3684
                else
3685
                    result += ", " + item;
3686
            }
3687
            return result;
3688
        }
3689
    }
3690
}
클립보드 이미지 추가 (최대 크기: 500 MB)