프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ dd27861e

이력 | 보기 | 이력해설 | 다운로드 (177 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 = 'P1'");
671
                foreach (DataRow dataRow in airFinCoolerRows)
672
                {
673
                    afcTagNum++;
674
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
675
                    foreach (DataRow dr in pathItemRows)
676
                    {
677
                        dr["EqpGroupTag"] = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));
678
                    }
679
                }
680
                
681
                foreach (DataRow dataRow in airFinCoolerRows)
682
                {
683
                    
684
                    string EGFlowDirection = string.Empty;
685
                    
686
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
687
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
688
                    {
689
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
690
                        {
691
                            EGFlowDirection = "O";
692
                        }
693
                    }
694
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
695
                    {
696
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
697
                        {
698
                            EGFlowDirection = "I";
699
                        }
700
                    }
701

    
702
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
703
                    string AFCTag = pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");
704
                    List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).ToList();
705
                    //ViewPipeSystemNetwork_OID
706
                    string MainLineTag = "";
707
                    if (dataRow["Type"].ToString() == "E2E")
708
                    {
709
                        MainLineTag = "M";
710
                         dataRow["AFC"] = "P3";
711
                    }
712
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
713
                    {
714
                        int bCount = 0;
715
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
716
                        {
717
                            if (viewOID == dataRow["OID"].ToString())
718
                                continue;
719

    
720
                            DataRow dr = PipeSystemNetwork.Select(string.Format("OID = '{0}'", viewOID)).First();
721
                            if (dr.Field<string>("AFC") != "P1")
722
                            {
723
                                if (lstViewPipeSystemNetwork_OID.Where(x => x.Equals(viewOID)).Count() == 1)
724
                                {
725
                                    MainLineTag = "M";
726
                                    dataRow["AFC"] = "P3";
727
                                }
728
                                else if(lstViewPipeSystemNetwork_OID.Where(x => x.Equals(viewOID)).Count() > 1)
729
                                {
730
                                    DataRow[] viewpipeSystem = PipeSystemNetwork.Select(string.Format("OID = '{0}'", viewOID));
731
                                    foreach (DataRow row in viewpipeSystem)
732
                                    {
733
                                        row["AFC"] = "P4";
734
                                    }
735

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

    
738
                                    if(viewpathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).Count() > 0)
739
                                        AFCTag = viewpathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");                                    
740

    
741
                                    foreach (DataRow viewdr in viewpathItemRows)
742
                                    {
743
                                       // viewdr["EqpGroupTag"] = AFCTag;
744
                                        viewdr["MainLineTag"] = "M";
745
                                    }
746
                                }
747
                            }
748
                        }                            
749
                    }
750

    
751
                    foreach (DataRow dr in pathItemRows)
752
                    {
753
                        dr["EqpGroupTag"] = AFCTag;// "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));  //ATG Sequence No Rule 여쭤봐야함.
754
                        dr["MainLineTag"] = MainLineTag; 
755
                        dr["EGFlowDirection"] = EGFlowDirection; 
756
                    }
757
                }
758
                
759
                foreach (DataRow dataRow in airFinCoolerRows)
760
                {
761
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = ''", dataRow["OID"].ToString()));
762
                    //ML이 공란인 PSN - P1이 있다면 해당 Pathitem에 P3인 psn이 있는지 확인 : 해당 값은 전부 돌린후 확인 가능하기 때문에 다시 조회
763
                    if (pathItemRows.Count() > 0)
764
                    {
765
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
766
                        List<string> lstpsn = new List<string>();
767
                        List<string> lstAll = new List<string>();
768
                        string EqpGroupTag = string.Empty;
769
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
770
                        {
771
                            if (dataRow["OID"].ToString() == viewOID)
772
                            {
773
                                //lstViewPipeSystemNetwork_OID.Remove(viewOID);
774
                                continue;
775
                            }
776
                            DataRow viewPSN = null;
777
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
778
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
779
                            
780
                            if (viewPSN != null)
781
                            {
782
                                EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
783
                                foreach (DataRow dr in pathItemRows)
784
                                {
785
                                    dr["EqpGroupTag"] = EqpGroupTag;
786

    
787
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
788
                                    {
789
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
790
                                        lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
791
                                    }
792
                                }
793
                            }
794
                            
795
                        }
796

    
797
                        while (lstpsn.Count() != 0)
798
                        {
799
                            int lstCount = lstpsn.Count;
800
                            for (int i = 0; i < lstpsn.Count(); i++) //string psn in lstpsn
801
                            {
802
                                
803
                                DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstpsn[i]));
804
                                foreach (DataRow dr in rule4pathItems)
805
                                {
806
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstAll.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
807
                                    {
808
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
809
                                        lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
810
                                    }
811

    
812
                                    if (dr["EqpGroupTag"].Equals(EqpGroupTag))
813
                                        continue;
814

    
815
                                    dr["EqpGroupTag"] = EqpGroupTag;                                  
816
                                }
817

    
818
                                lstpsn.Remove(lstpsn[i]);
819
                            }                        
820

    
821
                        }
822
                    }
823
                    
824
                }
825

    
826
                //DataRow[]  = PipeSystemNetwork.Select("AFC = 'P1'");
827
                foreach(DataRow dr in PipeSystemNetwork.Rows)
828
                {
829
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
830
                    if(pathItemRows.Count() > 0)
831
                    {
832
                        if(dr["Type"].ToString() == "HD2")
833
                        {
834
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
835
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
836
                            {                              
837
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
838
                                {
839
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
840
                                    {
841
                                        dataRow["EGTConnectedPoint"] = "1";
842
                                    }
843
                                }
844
                            }
845
                        }
846
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
847
                        {
848
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
849
                            string lastP1 = string.Empty;
850
                            foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
851
                            {
852
                                if (viewpsn == dr["OID"].ToString())
853
                                    continue;
854

    
855
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).Length == 0)
856
                                    continue;
857

    
858
                                DataRow rows = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).First();
859
                                if(rows != null)
860
                                {
861
                                    lastP1 = viewpsn;
862
                                }
863
                            }
864

    
865
                            if(!string.IsNullOrEmpty(lastP1))
866
                            {
867
                                bool bCheck = false;
868
                                foreach (DataRow dataRow in pathItemRows)
869
                                {
870
                                    if (bCheck)
871
                                        dataRow["EqpGroupTag"] = string.Empty;
872

    
873
                                    if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
874
                                    {
875
                                        bCheck = true;
876
                                        dataRow["EGTConnectedPoint"] = 1;
877
                                    }                       
878
                                }
879
                            }
880
                        }
881
                    }
882
                }
883

    
884
                //psn data 정리
885
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
886
                {
887
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
888
                    string EGTag = string.Empty;
889
                    string HasMLTags = "False";
890

    
891
                    foreach (DataRow dataRow in pathItemRows)
892
                    {
893
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
894
                            EGTag = dataRow.Field<string>("EqpGroupTag");
895

    
896
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
897
                            HasMLTags = "True";
898

    
899
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
900
                            break;
901
                    }
902

    
903
                    pipesystem["EGTag"] = EGTag;
904
                    pipesystem["HasMLTags"] = HasMLTags;
905
                }
906
            }
907
            catch (Exception ex)
908
            {
909
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
910
            }
911
            //}
912
        }
913

    
914
        private void UpdateValveGrouping()
915
        {
916
            try
917
            {
918
                #region ValveGrouping Info
919
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
920
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
921
                foreach (DataRow row in dtValveGroupung.Rows)
922
                {
923
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
924
                    {
925
                        OID = row["OID"].ToString(),
926
                        GroupType = row["GroupType"].ToString(),
927
                        TagIdentifier = row["TagIdentifier"].ToString(),
928
                        AttributeName = row["AttributeName"].ToString(),
929
                        SppidSymbolName = row["SppidSymbolName"].ToString()
930
                    });
931
                }
932
                #endregion
933

    
934

    
935
                int vgTagNum = 1;
936
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
937
                foreach (DataRow drPathitem in tagpathItemRows)
938
                {
939
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
940
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
941
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
942
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
943
                        continue;
944
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
945
                    List<Item> valveGroupingItem = new List<Item>();
946
                    int bCnt = 0;
947

    
948
                    //bool bCheck = false;
949
                    if (drPathitem["PipeSystemNetwork_OID"].ToString().Contains("901"))
950
                    {
951

    
952
                    }
953
                    List<DataRow> lstitem = new List<DataRow>();
954
                    foreach (DataRow dr in pathItemRows)
955
                    {
956
                        //if (!string.IsNullOrEmpty(dr["GROUPTAG"].ToString()))
957
                        //    break;
958

    
959
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
960
                        {
961
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
962
                            if (dr["GROUPTAG"].ToString() == "Scope Break")
963
                            {
964
                                dr["GROUPTAG"] = string.Empty;
965
                                keyValuePairs.Add(bCnt, lstitem.ToList());
966
                                bCnt++;
967
                                lstitem.Clear();
968
                                //break;
969
                            }
970
                            else
971
                            {
972
                                if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
973
                                {
974
                                    // bCheck = true;
975
                                    if (lstitem.ToList().Where(x => !string.IsNullOrEmpty(x.Field<string>("GROUPTAG"))).Count() > 0)
976
                                    {
977
                                        lstitem.Add(dr);
978
                                        keyValuePairs.Add(bCnt, lstitem.ToList());
979
                                        lstitem.Clear();
980
                                    }
981
                                    else
982
                                    {
983
                                        keyValuePairs.Add(bCnt, lstitem.ToList());
984
                                        lstitem.Clear();
985
                                        lstitem.Add(dr);
986
                                    }
987
                                    bCnt++;
988

    
989
                                }
990
                                else
991
                                    lstitem.Add(dr);
992
                            }
993

    
994
                        }
995
                        else
996
                            lstitem.Add(dr);
997
                    }
998

    
999
                    if (lstitem.Count > 0)
1000
                    {
1001
                        keyValuePairs.Add(bCnt, lstitem);
1002
                        //bCnt++;
1003
                    }
1004

    
1005
                    if (keyValuePairs.Count() == 0)
1006
                        continue;
1007

    
1008
                    string VGTag = string.Empty;
1009
                    if (valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
1010
                    {
1011
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1012
                        vgTagNum++;
1013
                    }
1014
                    else
1015
                    {
1016
                        if(string.IsNullOrEmpty(valvetag[1]))
1017
                            VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1018
                        else
1019
                            VGTag = valveitem.TagIdentifier + "-" + valvetag[1] + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1020

    
1021
                        vgTagNum++;
1022
                    }
1023

    
1024
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
1025
                    {
1026
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
1027
                        {
1028
                            foreach (DataRow dr in keyValuePair.Value)
1029
                            {
1030
                                dr["GROUPTAG"] = VGTag;
1031

    
1032
                                if(!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1033
                                {
1034
                                    if(TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1035
                                    {
1036
                                        DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1037
                                        foreach(DataRow path in rows)
1038
                                        {
1039
                                            DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1040
                                            if (topology.Field<string>("SubType").Equals("Bypass"))
1041
                                            {
1042
                                                DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1043
                                                foreach(DataRow pathitem in drPathItem)
1044
                                                {
1045
                                                    pathitem["GROUPTAG"] = VGTag;
1046
                                                }
1047
                                            }
1048
                                        }
1049
                                    }
1050
                                    
1051

    
1052
                                    //ViewPipeSystemNetwork_OID
1053
                                    //DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
1054
                                }
1055
                            }
1056
                        }
1057
                    }
1058

    
1059
                    if(valveitem.GroupType.Contains("PSV"))
1060
                    {
1061
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1062
                        foreach (DataRow row in psnRows)
1063
                            row["Pocket"] = "Yes";
1064
                    }                    
1065
                }
1066

    
1067

    
1068
            }
1069
            catch (Exception ex)
1070
            {
1071
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1072
            }
1073
            //}
1074
        }
1075

    
1076
        private void SetTopologyData()
1077
        {
1078
            // 13번 excel
1079
            foreach (Group group in groups)
1080
            {
1081
                LineNumber prevLineNumber = null;
1082
                for (int i = 0; i < group.Items.Count; i++)
1083
                {
1084
                    Item item = group.Items[i];
1085
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1086
                    if (lineNumber == null)
1087
                    {
1088
                        if (prevLineNumber != null)
1089
                        {
1090
                            if (!prevLineNumber.IsCopy)
1091
                            {
1092
                                prevLineNumber = prevLineNumber.Copy();
1093
                                item.Document.LineNumbers.Add(prevLineNumber);
1094
                                item.MissingLineNumber1 = true;
1095
                            }
1096
                            item.Owner = prevLineNumber.UID;
1097
                        }
1098
                    }
1099
                    else
1100
                        prevLineNumber = lineNumber;
1101
                }
1102

    
1103
                prevLineNumber = null;
1104
                for (int i = group.Items.Count - 1; i > -1; i--)
1105
                {
1106
                    Item item = group.Items[i];
1107
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1108
                    if (lineNumber == null)
1109
                    {
1110
                        if (prevLineNumber != null)
1111
                        {
1112
                            if (!prevLineNumber.IsCopy)
1113
                            {
1114
                                prevLineNumber = prevLineNumber.Copy();
1115
                                item.Document.LineNumbers.Add(prevLineNumber);
1116
                                item.MissingLineNumber1 = true;
1117
                            }
1118

    
1119
                            item.Owner = prevLineNumber.UID;
1120
                        }
1121
                    }
1122
                    else
1123
                        prevLineNumber = lineNumber;
1124
                }
1125

    
1126
                if (prevLineNumber == null)
1127
                {
1128
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1129
                    Random random = new Random();
1130
                    int index = random.Next(lineNumbers.Count - 1);
1131

    
1132
                    // Copy
1133
                    LineNumber cLineNumber = lineNumbers[index].Copy();
1134
                    group.Document.LineNumbers.Add(cLineNumber);
1135

    
1136
                    foreach (Item item in group.Items)
1137
                    {
1138
                        item.Owner = cLineNumber.UID;
1139
                        item.MissingLineNumber2 = true;
1140
                    }
1141
                }
1142
            }
1143

    
1144
            foreach (Document document in Documents)
1145
            {
1146
                foreach (Item item in document.Items)
1147
                {
1148
                    item.TopologyData = string.Empty;
1149
                    item.PSNPipeLineID = string.Empty;
1150
                    List<string> pipeLineID = new List<string>();
1151
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1152
                    if (lineNumber != null)
1153
                    {
1154
                        item.LineNumber = lineNumber;
1155

    
1156
                        foreach (DataRow row in topologyRuleDT.Rows)
1157
                        {
1158
                            string uid = row["UID"].ToString();
1159
                            //if (uid == "-")
1160
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1161
                            if (uid != "-")
1162
                            {
1163
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1164

    
1165
                                Attribute attribute = lineNumber.Attributes.Find(x => x.DisplayName == uid);
1166
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1167
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1168
                            }
1169
                        }
1170

    
1171
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1172
                        {
1173
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1174
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1175
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1176
                                                                 //else
1177
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1178
                        }
1179

    
1180
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1181
                        item.TopologyData = string.Join("-", pipeLineID);
1182

    
1183
                    }
1184
                    else
1185
                    {
1186
                        item.TopologyData = "Empty LineNumber";
1187
                        item.LineNumber = new LineNumber();
1188
                    }
1189
                }
1190
            }
1191

    
1192
            int emptyIndex = 1;
1193
            foreach (Group group in groups)
1194
            {
1195
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1196
                if (groupItems.Count > 0)
1197
                {
1198
                    foreach (var item in groupItems)
1199
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1200
                    emptyIndex++;
1201
                }
1202
            }
1203

    
1204
        }
1205

    
1206
        private void ConnectByOPC()
1207
        {
1208
            try
1209
            {
1210
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1211
                {
1212
                    Item opcItem = group.Items.Last();
1213
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1214
                    if (fromRows.Length.Equals(1))
1215
                    {
1216
                        DataRow opcRow = fromRows.First();
1217
                        string toDrawing = opcRow["ToDrawing"].ToString();
1218
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
1219

    
1220
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1221
                        if (toDocument != null)
1222
                        {
1223
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1224
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1225
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1226
                            if (toRows.Length > 1)
1227
                            {
1228
                                //throw new Exception("OPC error(multi connect)");
1229
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1230
                                return;
1231
                            }
1232
                            group.EndGroup = toGroup;
1233
                            toGroup.StartGroup = group;
1234
                        }
1235
                    }
1236
                }
1237
            }
1238
            catch (Exception ex)
1239
            {
1240
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1241
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1242
            }
1243
        }
1244

    
1245
        private void SetPSNItem()
1246
        {
1247
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1248
            foreach (Group group in groups)
1249
                groupDic.Add(group, Guid.NewGuid().ToString());
1250

    
1251
            foreach (Group group in groups)
1252
            {
1253
                string groupKey = groupDic[group];
1254
                if (group.StartGroup != null)
1255
                {
1256
                    string otherKey = groupDic[group.StartGroup];
1257
                    ChangeGroupID(otherKey, groupKey);
1258
                }
1259
            }
1260

    
1261
            // PSN 정리
1262
            foreach (var item in groupDic)
1263
            {
1264
                Group group = item.Key;
1265
                string uid = item.Value;
1266
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1267
                if (PSNItem == null)
1268
                {
1269
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1270
                    PSNItems.Add(PSNItem);
1271
                }
1272
                PSNItem.Groups.Add(group);
1273
                foreach (Item groupItem in group.Items)
1274
                    groupItem.PSNItem = PSNItem;
1275
            }
1276

    
1277
            // Sort PSN
1278
            foreach (PSNItem PSNItem in PSNItems)
1279
            {
1280
                List<Group> _groups = new List<Group>();
1281

    
1282
                Stack<Group> stacks = new Stack<Group>();
1283
                stacks.Push(PSNItem.Groups.First());
1284
                while (stacks.Count > 0)
1285
                {
1286
                    Group stack = stacks.Pop();
1287
                    if (_groups.Contains(stack))
1288
                        continue;
1289

    
1290
                    if (_groups.Count == 0)
1291
                        _groups.Add(stack);
1292
                    else
1293
                    {
1294
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1295
                        {
1296
                            int index = _groups.IndexOf(stack.StartGroup);
1297
                            _groups.Insert(index + 1, stack);
1298
                        }
1299
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1300
                        {
1301
                            int index = _groups.IndexOf(stack.EndGroup);
1302
                            _groups.Insert(index, stack);
1303
                        }
1304
                    }
1305

    
1306
                    if (stack.StartGroup != null)
1307
                        stacks.Push(stack.StartGroup);
1308
                    if (stack.EndGroup != null)
1309
                        stacks.Push(stack.EndGroup);
1310
                }
1311

    
1312
                PSNItem.Groups.Clear();
1313
                PSNItem.Groups.AddRange(_groups);
1314
            }
1315

    
1316
            void ChangeGroupID(string from, string to)
1317
            {
1318
                if (from.Equals(to))
1319
                    return;
1320

    
1321
                List<Group> changeItems = new List<Group>();
1322
                foreach (var _item in groupDic)
1323
                    if (_item.Value.Equals(from))
1324
                        changeItems.Add(_item.Key);
1325
                foreach (var _item in changeItems)
1326
                    groupDic[_item] = to;
1327
            }
1328
        }
1329

    
1330
        private void SetPSNType()
1331
        {
1332
            foreach (PSNItem PSNItem in PSNItems)
1333
            {
1334
                Group firstGroup = PSNItem.Groups.First();
1335
                Group lastGroup = PSNItem.Groups.Last();
1336

    
1337
                Item firstItem = firstGroup.Items.First();
1338
                Item lastItem = lastGroup.Items.Last();
1339

    
1340
                PSNItem.StartType = GetPSNType(firstItem, true);
1341
                PSNItem.EndType = GetPSNType(lastItem, false);
1342

    
1343
            }
1344

    
1345
            PSNType GetPSNType(Item item, bool bFirst = true)
1346
            {
1347
                PSNType type = PSNType.None;
1348

    
1349
                if (item.ItemType == ItemType.Line)
1350
                {
1351
                    Group group = groups.Find(x => x.Items.Contains(item));
1352
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1353
                    {
1354
                        Item connItem = item.Relations[0].Item;
1355
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1356
                            type = PSNType.Branch;
1357
                        else if (connItem.ItemType == ItemType.Symbol)
1358
                            type = PSNType.Symbol;
1359
                    }
1360
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1361
                    {
1362
                        Item connItem = item.Relations[1].Item;
1363
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1364
                            type = PSNType.Branch;
1365
                        else if (connItem.ItemType == ItemType.Symbol)
1366
                            type = PSNType.Symbol;
1367
                    }
1368
                }
1369
                else if (item.ItemType == ItemType.Symbol)
1370
                {
1371
                    if (item.SubItemType == SubItemType.Nozzle)
1372
                        type = PSNType.Equipment;
1373
                    else if (item.SubItemType == SubItemType.Header)
1374
                        type = PSNType.Header;
1375
                    else if (item.SubItemType == SubItemType.OPC)
1376
                        type = PSNType.OPC;
1377
                }
1378

    
1379
                return type;
1380
            }
1381
        }
1382

    
1383
        private void SetBranchInfo()
1384
        {
1385
            foreach (Document document in Documents)
1386
            {
1387
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1388
                foreach (Item line in lines)
1389
                {
1390
                    double[] point = line.Relations[0].Point;
1391
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1392
                    connLines.Sort(SortBranchLine);
1393
                    line.BranchItems.AddRange(connLines);
1394

    
1395
                    int SortBranchLine(Item a, Item b)
1396
                    {
1397
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1398
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1399

    
1400
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1401
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1402

    
1403
                        // 내림차순
1404
                        return distanceA.CompareTo(distanceB);
1405
                    }
1406
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1407
                    {
1408
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1409
                    }
1410
                }
1411
            }
1412
        }
1413

    
1414
        private void SetTopology()
1415
        {
1416
            try
1417
            {
1418
                #region 기본 topology 정리
1419
                foreach (PSNItem PSNItem in PSNItems)
1420
                {
1421
                    Topology topology = null;
1422
                    foreach (Group group in PSNItem.Groups)
1423
                    {
1424
                        foreach (Item item in group.Items)
1425
                        {
1426
                            if (string.IsNullOrEmpty(item.TopologyData))
1427
                                topology = null;
1428
                            else
1429
                            {
1430
                                if (topology == null)
1431
                                {
1432
                                    topology = new Topology()
1433
                                    {
1434
                                        ID = item.TopologyData
1435
                                    };
1436
                                    Topologies.Add(topology);
1437

    
1438
                                    if (!PSNItem.Topologies.Contains(topology))
1439
                                        PSNItem.Topologies.Add(topology);
1440
                                }
1441
                                else
1442
                                {
1443
                                    if (topology.ID != item.TopologyData)
1444
                                    {
1445
                                        topology = new Topology()
1446
                                        {
1447
                                            ID = item.TopologyData
1448
                                        };
1449
                                        Topologies.Add(topology);
1450

    
1451
                                        if (!PSNItem.Topologies.Contains(topology))
1452
                                            PSNItem.Topologies.Add(topology);
1453
                                    }
1454
                                }
1455

    
1456
                                item.Topology = topology;
1457
                                topology.Items.Add(item);
1458
                            }
1459
                        }
1460
                    }
1461
                }
1462
                #endregion
1463

    
1464
                #region Type
1465
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1466
                foreach (string id in ids)
1467
                {
1468
                    try
1469
                    {
1470

    
1471

    
1472
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1473

    
1474
                        // Main
1475
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1476
                        foreach (Topology topology in mainTopologies)
1477
                            topology.Type = "M";
1478

    
1479
                        // Branch
1480
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1481
                        foreach (Topology topology in branchToplogies)
1482
                            topology.Type = "B";
1483
                    }
1484
                    catch (Exception ex)
1485
                    {
1486
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1487
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1488
                    }
1489
                }
1490
                #endregion
1491
            }
1492
            catch (Exception ex)
1493
            {
1494
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1495
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1496
            }
1497

    
1498
        }
1499

    
1500
        private void SetTopologyIndex()
1501
        {
1502
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1503
            foreach (string id in ids)
1504
            {
1505
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1506

    
1507
                // Main
1508
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1509
                foreach (Topology topology in mainTopologies)
1510
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1511

    
1512
                // Branch
1513
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1514
                foreach (Topology topology in branchToplogies)
1515
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1516
            }
1517
        }
1518

    
1519
        private void SetPSNBypass()
1520
        {
1521
            foreach (PSNItem PSNItem in PSNItems)
1522
                PSNItem.IsBypass = IsBypass(PSNItem);
1523
        }
1524

    
1525
        private List<Topology> FindMainTopology(List<Topology> data)
1526
        {
1527
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1528
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1529
            //2021.11.17 안쓰네 JY
1530
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1531

    
1532
            List<Topology> main = new List<Topology>();
1533
            main.AddRange(data);
1534
            //
1535
            main = GetNozzleTopology(data);
1536
            if (main.Count == 1)
1537
                return main;
1538
            else
1539
            {
1540
                if (main.Count > 0)
1541
                    main = GetPMCTopology(main);
1542
                else
1543
                    main = GetPMCTopology(data);
1544

    
1545
                if (main.Count == 1)
1546
                    return main;
1547
                else
1548
                {
1549
                    if (main.Count > 0)
1550
                        main = GetDiaTopology(main);
1551
                    else
1552
                        main = GetDiaTopology(data);
1553

    
1554

    
1555
                    if (main.Count == 1)
1556
                        return main;
1557
                    else
1558
                    {
1559
                        if (main.Count > 0)
1560
                            main = GetItemTopology(main);
1561
                        else
1562
                            main = GetItemTopology(data);
1563
                    }
1564
                }
1565
            }
1566

    
1567
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1568
            {
1569
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1570
            }
1571

    
1572
            List<Topology> GetPMCTopology(List<Topology> topologies)
1573
            {
1574
                List<Topology> result = new List<Topology>();
1575
                foreach (DataRow row in PMCDT.Rows)
1576
                {
1577
                    string value = row["CODE"].ToString();
1578
                    foreach (Topology topology in topologies)
1579
                    {
1580
                        foreach (Item item in topology.Items)
1581
                        {
1582
                            if (item.LineNumber == null)
1583
                                continue;
1584
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1585
                            if (attribute != null && value == attribute.Value)
1586
                            {
1587
                                result.Add(topology);
1588
                                break;
1589
                            }
1590
                        }
1591
                    }
1592

    
1593
                    if (result.Count > 0)
1594
                        break;
1595
                }
1596

    
1597
                return result;
1598
            }
1599

    
1600
            List<Topology> GetDiaTopology(List<Topology> topologies)
1601
            {
1602
                List<Topology> result = new List<Topology>();
1603
                foreach (DataRow row in nominalDiameterDT.Rows)
1604
                {
1605
                    string inchValue = row["InchStr"].ToString();
1606
                    string metricValue = row["MetricStr"].ToString();
1607
                    foreach (Topology topology in topologies)
1608
                    {
1609
                        foreach (Item item in topology.Items)
1610
                        {
1611
                            if (item.LineNumber == null)
1612
                                continue;
1613
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1614
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1615
                            {
1616
                                result.Add(topology);
1617
                                break;
1618
                            }
1619
                        }
1620
                    }
1621

    
1622
                    if (result.Count > 0)
1623
                        break;
1624
                }
1625

    
1626
                return result;
1627
            }
1628

    
1629
            List<Topology> GetItemTopology(List<Topology> topologies)
1630
            {
1631
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1632
            }
1633

    
1634
            return main;
1635
        }
1636

    
1637
        private DataTable GetOPCInfo()
1638
        {
1639
            DataTable opc = DB.SelectOPCRelations();
1640
            DataTable drawing = DB.AllDrawings();
1641

    
1642
            DataTable dt = new DataTable();
1643
            dt.Columns.Add("FromDrawing", typeof(string));
1644
            dt.Columns.Add("FromDrawingUID", typeof(string));
1645
            dt.Columns.Add("FromOPCUID", typeof(string));
1646
            dt.Columns.Add("ToDrawing", typeof(string));
1647
            dt.Columns.Add("ToDrawingUID", typeof(string));
1648
            dt.Columns.Add("ToOPCUID", typeof(string));
1649
            foreach (DataRow row in opc.Rows)
1650
            {
1651
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1652
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1653
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1654
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1655
                if (!string.IsNullOrEmpty(toOPCUID))
1656
                {
1657
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
1658
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
1659
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
1660
                    {
1661
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
1662
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
1663

    
1664
                        DataRow newRow = dt.NewRow();
1665
                        newRow["FromDrawing"] = fromDrawingName;
1666
                        newRow["FromDrawingUID"] = fromDrawingUID;
1667
                        newRow["FromOPCUID"] = fromOPCUID;
1668
                        newRow["ToDrawing"] = toDrawingName;
1669
                        newRow["ToDrawingUID"] = toDrawingUID;
1670
                        newRow["ToOPCUID"] = toOPCUID;
1671

    
1672
                        dt.Rows.Add(newRow);
1673
                    }
1674
                }
1675
            }
1676

    
1677
            return dt;
1678
        }
1679

    
1680
        private DataTable GetTopologyRule()
1681
        {
1682
            DataTable dt = DB.SelectTopologyRule();
1683

    
1684
            return dt;
1685
        }
1686

    
1687
        private bool IsConnected(Item item1, Item item2)
1688
        {
1689
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
1690
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
1691
                return true;
1692
            else
1693
                return false;
1694
        }
1695

    
1696
        private void SaveNozzleAndEquipment()
1697
        {
1698
            List<Item> nozzles = new List<Item>();
1699
            List<Equipment> equipments = new List<Equipment>();
1700
            foreach (Document document in Documents)
1701
            {
1702
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1703
                equipments.AddRange(document.Equipments);
1704
            }
1705

    
1706

    
1707
            DataTable nozzleDT = new DataTable();
1708
            nozzleDT.Columns.Add("OID", typeof(string));
1709
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1710
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1711
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1712
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1713
            nozzleDT.Columns.Add("FLUID", typeof(string));
1714
            nozzleDT.Columns.Add("NPD", typeof(string));
1715
            nozzleDT.Columns.Add("PMC", typeof(string));
1716
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1717
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1718

    
1719
            foreach (Item item in nozzles)
1720
            {
1721
                DataRow row = nozzleDT.NewRow();
1722
                row["OID"] = item.UID;
1723

    
1724
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
1725
                if (relation != null)
1726
                {
1727
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
1728
                    equipment.Nozzles.Add(item);
1729
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
1730
                    row["Equipment_OID"] = equipment.UID;
1731
                    item.Equipment = equipment;
1732
                }
1733
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
1734
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
1735
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
1736
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
1737
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1738
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
1739
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1740
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
1741

    
1742
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1743
                if (angle >= Math.PI * 2)
1744
                    angle = angle - Math.PI * 2;
1745
                row["ROTATION"] = angle.ToString();
1746

    
1747
                if (item.Topology.Items.First().Equals(item))
1748
                    row["FlowDirection"] = "Outlet";
1749
                else if (item.Topology.Items.Last().Equals(item))
1750
                    row["FlowDirection"] = "Inlet";
1751
                else
1752
                    row["FlowDirection"] = string.Empty;
1753

    
1754
                nozzleDT.Rows.Add(row);
1755
            }
1756

    
1757
            DataTable equipDT = new DataTable();
1758
            equipDT.Columns.Add("OID", typeof(string));
1759
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1760
            equipDT.Columns.Add("XCOORDS", typeof(string));
1761
            equipDT.Columns.Add("YCOORDS", typeof(string));
1762

    
1763
            foreach (Equipment equipment in equipments)
1764
            {
1765
                DataRow row = equipDT.NewRow();
1766
                row["OID"] = equipment.UID;
1767
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
1768
                {
1769
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
1770
                    if (attribute != null)
1771
                        equipment.ItemTag = attribute.Value;
1772
                }
1773
                else
1774
                    equipment.ItemTag = equipment.Name;
1775

    
1776
                row["ITEMTAG"] = equipment.ItemTag;
1777
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
1778
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
1779

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

    
1783
                equipDT.Rows.Add(row);
1784
            }
1785

    
1786
            Equipment = equipDT;
1787
            Nozzle = nozzleDT;
1788
        }
1789

    
1790
        private void SavePSNData()
1791
        {
1792
            try
1793
            {
1794
                DataTable pathItemsDT = new DataTable();
1795
                pathItemsDT.Columns.Add("OID", typeof(string));
1796
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
1797
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
1798
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
1799
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
1800
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
1801
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
1802
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
1803
                pathItemsDT.Columns.Add("Class", typeof(string));
1804
                pathItemsDT.Columns.Add("SubClass", typeof(string));
1805
                pathItemsDT.Columns.Add("TYPE", typeof(string));
1806
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
1807
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
1808
                pathItemsDT.Columns.Add("NPD", typeof(string));
1809
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
1810
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
1811
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
1812
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
1813
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
1814
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
1815
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
1816
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
1817

    
1818
                DataTable sequenceDataDT = new DataTable();
1819
                sequenceDataDT.Columns.Add("OID", typeof(string));
1820
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
1821
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
1822
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1823

    
1824
                DataTable pipeSystemNetworkDT = new DataTable();
1825
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
1826
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
1827
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
1828
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
1829
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
1830
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
1831
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1832
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
1833
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
1834
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
1835
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
1836
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
1837
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
1838
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
1839
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
1840
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
1841
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
1842
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
1843
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
1844

    
1845
                DataTable topologySetDT = new DataTable();
1846
                topologySetDT.Columns.Add("OID", typeof(string));
1847
                topologySetDT.Columns.Add("Type", typeof(string));
1848
                topologySetDT.Columns.Add("SubType", typeof(string));
1849
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
1850
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
1851
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
1852
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
1853

    
1854
                DataTable pipelineDT = new DataTable();
1855
                pipelineDT.Columns.Add("OID", typeof(string));
1856
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
1857
                pipelineDT.Columns.Add("FLUID", typeof(string));
1858
                pipelineDT.Columns.Add("PMC", typeof(string));
1859
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
1860
                pipelineDT.Columns.Add("INSULATION", typeof(string));
1861
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
1862
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
1863
                pipelineDT.Columns.Add("Unit", typeof(string));
1864

    
1865
                DataTable pipesystemDT = new DataTable();
1866
                pipesystemDT.Columns.Add("OID", typeof(string));
1867
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
1868
                pipesystemDT.Columns.Add("FLUID", typeof(string));
1869
                pipesystemDT.Columns.Add("PMC", typeof(string));
1870
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
1871
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
1872

    
1873
                // Set Vent/Drain Info
1874
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1875
                DataTable dt = DB.SelectVentDrainSetting();
1876
                foreach (DataRow row in dt.Rows)
1877
                {
1878
                    string groupID = row["GROUP_ID"].ToString();
1879
                    string desc = row["DESCRIPTION"].ToString();
1880
                    int index = Convert.ToInt32(row["INDEX"]);
1881
                    string name = row["NAME"].ToString();
1882

    
1883
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1884
                    if (ventDrainInfo == null)
1885
                    {
1886
                        ventDrainInfo = new VentDrainInfo(groupID);
1887
                        ventDrainInfo.Description = desc;
1888
                        VentDrainInfos.Add(ventDrainInfo);
1889
                    }
1890

    
1891
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1892
                    {
1893
                        Index = index,
1894
                        Name = name
1895
                    });
1896
                }
1897
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1898
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
1899

    
1900
                #region Keyword Info
1901
                KeywordInfo KeywordInfos = new KeywordInfo();
1902
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1903
                foreach (DataRow row in dtKeyword.Rows)
1904
                {
1905
                    int index = Convert.ToInt32(row["INDEX"]);
1906
                    string name = row["NAME"].ToString();
1907
                    string keyword = row["KEYWORD"].ToString();
1908

    
1909
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1910
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1911
                    {
1912
                        Index = index,
1913
                        Name = name,
1914
                        Keyword = keyword
1915
                    });
1916
                }
1917
                #endregion
1918

    
1919
                #region ValveGrouping Info
1920
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1921
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1922
                foreach (DataRow row in dtValveGroupung.Rows)
1923
                {
1924
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1925
                    {
1926
                        OID = row["OID"].ToString(),
1927
                        GroupType = row["GroupType"].ToString(),
1928
                        TagIdentifier = row["TagIdentifier"].ToString(),
1929
                        AttributeName = row["AttributeName"].ToString(),
1930
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1931
                    });
1932
                }
1933
                #endregion
1934

    
1935
                #region EquipmentNoPocket Info
1936
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
1937
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
1938
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
1939
                {
1940
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
1941
                    {
1942
                        Index = Convert.ToInt32(row["INDEX"]),
1943
                        Type = row["TYPE"].ToString(),
1944
                        Name = row["NAME"].ToString()
1945
                    });
1946
                }
1947
                #endregion
1948

    
1949
                #region EquipmentAirFinCooler Info
1950
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
1951
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
1952
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
1953
                {
1954
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
1955
                    {
1956
                        Type = row["Type"].ToString(),
1957
                        Name = row["Name"].ToString()
1958
                    });
1959
                }
1960
                #endregion
1961

    
1962
                // key = 미입력 branch
1963
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1964
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1965
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
1966
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
1967
                foreach (PSNItem PSNItem in PSNItems)
1968
                {
1969
                    try
1970
                    {
1971
                        int psnOrder = 0;
1972
                        int index = 0;
1973
                        bool bPSNStart = true;
1974
                        string sPSNData = string.Empty;
1975
                        bool bVentDrain = false;
1976

    
1977
                        List<Group> Groups = PSNItem.Groups;
1978
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
1979
                        List<Item> valveGroupingItem = new List<Item>();
1980

    
1981
                        //VentDrain 검사
1982
                        if (PSNItem.Groups.Count.Equals(1))
1983
                        {
1984
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1985
                            for (int g = 0; g < Groups.Count; g++)
1986
                            {
1987
                                Group group = Groups[g];
1988
                                for (int i = 0; i < group.Items.Count; i++)
1989
                                {
1990
                                    Item item = group.Items[i];
1991
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1992
                                    {
1993
                                        if (endInfos.Contains(ventDrainInfo))
1994
                                            continue;
1995

    
1996
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1997
                                        {
1998
                                            endInfos.Add(ventDrainInfo);
1999
                                            continue;
2000
                                        }
2001

    
2002
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
2003
                                        {
2004
                                            bVentDrain = true;
2005
                                            break;
2006
                                        }
2007
                                    }
2008

    
2009
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
2010
                                        break;
2011
                                }
2012

    
2013
                                if (!bVentDrain)
2014
                                {
2015
                                    endInfos = new List<VentDrainInfo>();
2016
                                    for (int i = 0; i < group.Items.Count; i++)
2017
                                    {
2018
                                        Item item = group.Items[group.Items.Count - i - 1];
2019
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2020
                                        {
2021
                                            if (endInfos.Contains(ventDrainInfo))
2022
                                                continue;
2023

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

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

    
2037
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
2038
                                            break;
2039
                                    }
2040
                                }
2041
                            }
2042
                        }
2043

    
2044
                        try
2045
                        {
2046
                            foreach (Group group in PSNItem.Groups)
2047
                            {
2048
                                foreach (Item item in group.Items)
2049
                                {
2050
                                    string VgTag = string.Empty;
2051
                                    
2052
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
2053
                                    {
2054
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
2055
                                        string value = string.Empty;
2056

    
2057
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
2058
                                            value = "NoSelection";
2059
                                        else
2060
                                        {
2061
                                            if(item.Attributes.Find(x => x.Name == valveitem.AttributeName) == null)
2062
                                                value = "NoSelection";
2063
                                            else
2064
                                                value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
2065
                                        }
2066

    
2067
                                        if (valveitem.GroupType == "Scope Break")
2068
                                            VgTag = "Scope Break";
2069
                                        else
2070
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
2071

    
2072
                                    }
2073

    
2074
                                    string PathitemUID = string.Empty;
2075
                                    if (item.BranchItems.Count == 0)
2076
                                    {
2077
                                        PathitemUID = item.UID;
2078
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2079
                                        CreateSequenceDataDataRow(PathitemUID);
2080
                                        index++;
2081
                                    }
2082
                                    else
2083
                                    {
2084
                                        PathitemUID = item.UID + "_L1";
2085
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2086
                                        CreateSequenceDataDataRow(PathitemUID);
2087
                                        index++;
2088
                                        for (int i = 0; i < item.BranchItems.Count; i++)
2089
                                        {
2090
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
2091
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
2092
                                            index++;
2093

    
2094
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
2095
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
2096
                                            index++;
2097

    
2098
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
2099
                                                startBranchDic.Add(item.BranchItems[i], item);
2100
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
2101
                                                endBranchDic.Add(item.BranchItems[i], item);
2102
                                        }
2103
                                    }
2104

    
2105
                                    if (bPSNStart)
2106
                                    {
2107
                                        CreatePipeSystemNetworkDataRow();
2108
                                        sPSNData = item.TopologyData;
2109
                                        psnOrder++;
2110
                                        bPSNStart = false;
2111
                                    }
2112
                                    else
2113
                                    {
2114
                                        if (item.TopologyData != sPSNData)
2115
                                        {
2116
                                            CreatePipeSystemNetworkDataRow();
2117
                                            sPSNData = item.TopologyData;
2118
                                            psnOrder++;
2119
                                        }
2120
                                    }
2121

    
2122
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
2123
                                    {
2124
                                        DataRow newRow = pathItemsDT.NewRow();
2125

    
2126
                                        if (itemType == "Nozzles")
2127
                                        {
2128
                                            newRow["Equipment_OID"] = item.Equipment != null ? item.Equipment.UID : "";
2129
                                        }
2130

    
2131
                                        newRow["OID"] = itemOID;
2132
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2133
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
2134
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2135
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2136
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
2137
                                        newRow["ITEMTAG"] = GetItemTag(item);
2138
                                        newRow["Class"] = GetClass(item, itemOID);
2139
                                        string subClass = GetSubClass(item, itemOID);
2140
                                        newRow["SubClass"] = subClass;
2141

    
2142
                                        if (item.ItemType == ItemType.Symbol)
2143
                                            newRow["TYPE"] = item.ID2DBName;
2144
                                        else if (item.ItemType == ItemType.Line)
2145
                                            newRow["TYPE"] = item.ID2DBType;
2146
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2147

    
2148
                                        // NPD
2149
                                        if (item.LineNumber != null)
2150
                                        {
2151
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2152
                                            if (attribute != null)
2153
                                                newRow["NPD"] = attribute.Value;
2154
                                        }
2155
                                        else
2156
                                            newRow["NPD"] = null;
2157

    
2158
                                        newRow["GROUPTAG"] = GROUPTAG;
2159
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2160
                                        if (branchItem == null)
2161
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2162
                                        else
2163
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2164

    
2165
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2166
                                        newRow["EGTConnectedPoint"] = 0;
2167
                                        pathItemsDT.Rows.Add(newRow);
2168
                                    }
2169

    
2170

    
2171
                                    void CreateSequenceDataDataRow(string itemOID)
2172
                                    {
2173
                                        DataRow newRow = sequenceDataDT.NewRow();
2174
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2175
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2176
                                        newRow["PathItem_OID"] = itemOID;
2177
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2178

    
2179
                                        sequenceDataDT.Rows.Add(newRow);
2180
                                    }
2181

    
2182
                                    void CreatePipeSystemNetworkDataRow()
2183
                                    {
2184
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2185
                                        string FluidCode = string.Empty;
2186
                                        if (lineNumber != null)
2187
                                        {
2188
                                            List<Attribute> att = lineNumber.Attributes;
2189
                                            if (att != null)
2190
                                            {
2191
                                                List<string> oid = new List<string>();
2192
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2193
                                                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;
2194
                                                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;
2195
                                                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;
2196
                                                //InsulationPurpose
2197
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2198
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2199

    
2200
                                                string PipeSystem_OID = string.Join("-", oid);
2201

    
2202
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2203
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2204

    
2205
                                                string OID = string.Join("-", oid);
2206
                                                string FluidCodeGL = string.Empty;
2207
                                                string PMCGL = string.Empty;
2208

    
2209

    
2210
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2211
                                                {
2212
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2213
                                                    newPipelineRow["OID"] = OID;
2214
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2215
                                                    newPipelineRow["FLUID"] = FluidCode;
2216
                                                    newPipelineRow["PMC"] = PMC;
2217
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2218
                                                    newPipelineRow["INSULATION"] = INSULATION;
2219
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2220
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2221
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2222
                                                    pipelineDT.Rows.Add(newPipelineRow);
2223
                                                }
2224

    
2225
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2226
                                                {
2227
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2228
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2229
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2230
                                                    newPipesystemRow["FLUID"] = FluidCode;
2231
                                                    newPipesystemRow["PMC"] = PMC;
2232
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2233
                                                    string GroundLevel = string.Empty;
2234
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2235
                                                    {
2236
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2237
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2238
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2239
                                                            GroundLevel = "AG";
2240
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2241
                                                            GroundLevel = "UG";
2242
                                                        else
2243
                                                            GroundLevel = "AG_UG";
2244
                                                    }
2245
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2246

    
2247
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2248
                                                }
2249
                                            }
2250
                                        }
2251

    
2252
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2253
                                        newRow["OID"] = PSNItem.PSN_OID();
2254

    
2255
                                        newRow["OrderNumber"] = psnOrder;
2256
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2257
                                        PSNItem.KeywordInfos = KeywordInfos;
2258
                                        PSNItem.Nozzle = Nozzle;
2259

    
2260
                                        string FromType = string.Empty;
2261
                                        Item From_item = new Item();
2262

    
2263
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
2264
                                        string status = string.Empty;
2265
                                        if (psnOrder == 0)
2266
                                        {
2267
                                            status = PSNItem.Status;
2268
                                        }
2269

    
2270
                                        if (PSNItem.IsKeyword)
2271
                                        {
2272
                                            PSNItem.StartType = PSNType.Equipment;
2273
                                        }
2274
                                        string ToType = string.Empty;
2275
                                        Item To_item = new Item();
2276
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
2277
                                        if (PSNItem.IsKeyword)
2278
                                        {
2279
                                            PSNItem.EndType = PSNType.Equipment;
2280
                                        }
2281

    
2282
                                        //if (Groups.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
2283
                                        //{
2284
                                        if (!string.IsNullOrEmpty(PSNItem.Status))
2285
                                            status += PSNItem.Status;
2286
                                        //}
2287

    
2288
                                        newRow["FROM_DATA"] = FROM_DATA;
2289
                                        newRow["TO_DATA"] = TO_DATA;
2290
                                        //if(TO_DATA.Contains("Free Vent W-Screen") || TO_DATA.Contains("Empty LineNumber") || FROM_DATA.Contains("Empty LineNumber"))
2291
                                        //{
2292

    
2293
                                        //}
2294
                                        newRow["Type"] = PSNItem.GetPSNType();
2295

    
2296
                                        if (psnOrder > 0)
2297
                                        {
2298
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2299
                                            if (!string.IsNullOrEmpty(PSNItem.Status))
2300
                                            {//status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2301
                                                if (dr["Status"].ToString().Contains(PSNItem.Status))
2302
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
2303
                                                else if (dr["Status"].ToString().Contains(PSNItem.Status.Remove(0, 2)))
2304
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
2305

    
2306
                                            }
2307

    
2308
                                            if (dr != null)
2309
                                            {
2310
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2311
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2312
                                                newRow["Type"] = dr.Field<string>("Type");
2313
                                            }
2314
                                        }
2315

    
2316
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2317
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
2318
                                        {
2319
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
2320
                                            int cnt = matches.Count;
2321
                                            if (cnt > 1)
2322
                                                status.Replace(", Missing LineNumber_1", string.Empty);
2323
                                        }
2324
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2325
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
2326

    
2327

    
2328
                                        newRow["IsValid"] = PSNItem.IsValid;
2329
                                        newRow["Status"] = status;
2330
                                        newRow["PBS"] = PSNItem.GetPBSData();
2331

    
2332
                                        List<string> drawingNames = new List<string>();
2333
                                        foreach (Group _group in PSNItem.Groups)
2334
                                        {
2335
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2336
                                            {
2337
                                                if (drawingNames.Count == 0)
2338
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2339
                                                else
2340
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2341
                                                drawingNames.Add(_group.Document.DrawingName);
2342
                                            }
2343
                                        }
2344

    
2345
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2346
                                        if (bVentDrain)
2347
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2348
                                        else
2349
                                            newRow["IncludingVirtualData"] = "No";
2350
                                        //    return;
2351
                                        //newRow["IncludingVirtualData"] = "No";
2352
                                        newRow["PSNAccuracy"] = "100";
2353

    
2354
                                        string Pocket = "No";
2355
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2356
                                        if (Condition.Equals("Flare"))
2357
                                            Pocket = "Yes";
2358

    
2359
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null) 
2360
                                        {
2361
                                          //  string itemName = From_item.Name;
2362
                                            Equipment Equipment = From_item.Equipment;
2363
                                      
2364
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2365
                                          
2366

    
2367
                                            if (nopocket != null)
2368
                                            {
2369
                                                DataRow bNozzle = null;
2370
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2371
                                                {
2372
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2373
                                                    if (drNozzle != null)
2374
                                                    {
2375
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2376
                                                        {
2377
                                                            bNozzle = drNozzle;
2378
                                                        }
2379

    
2380
                                                        if (bNozzle == null)
2381
                                                        {
2382
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2383

    
2384
                                                            if (drNozzle != null)
2385
                                                            {
2386
                                                                bNozzle = drNozzle;
2387
                                                                foreach (DataRow it in nozzleRows)
2388
                                                                {
2389
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2390
                                                                    {
2391
                                                                        bNozzle = null;
2392
                                                                        break;
2393
                                                                    }
2394
                                                                }
2395
                                                            }
2396
                                                        }
2397
                                                    }
2398

    
2399
                                                    if (bNozzle != null)
2400
                                                        Pocket = "Yes";
2401
                                                }
2402
                                                else
2403
                                                    Pocket = "Yes";
2404
                                            }
2405
                                        }
2406
                                        
2407
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null) //To는 전체
2408
                                        {
2409
                                           // string itemName = To_item.Name;
2410
                                            Equipment Equipment = To_item.Equipment;
2411
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2412
                                            if (nopocket != null)
2413
                                            {
2414
                                                DataRow bNozzle = null;
2415
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2416
                                                {
2417
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2418
                                                    if(drNozzle != null)
2419
                                                    {
2420
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2421
                                                        {
2422
                                                            bNozzle = drNozzle;
2423
                                                        }
2424

    
2425
                                                        if (bNozzle == null)
2426
                                                        {
2427
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2428

    
2429
                                                            if (drNozzle != null)
2430
                                                            {
2431
                                                                bNozzle = drNozzle;
2432
                                                                foreach (DataRow it in nozzleRows)
2433
                                                                {
2434
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2435
                                                                    {
2436
                                                                        bNozzle = null;
2437
                                                                        break;
2438
                                                                    }
2439
                                                                }
2440
                                                            }
2441
                                                        }
2442
                                                    }                                                   
2443

    
2444
                                                    if (bNozzle != null)
2445
                                                        Pocket = "Yes";
2446
                                                }
2447
                                                else
2448
                                                    Pocket = "Yes";
2449
                                            }
2450
                                        }
2451
                                        
2452
                                        newRow["Pocket"] = Pocket;
2453
                                        string AFC = "P2";
2454
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2455
                                        {
2456
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2457
                                                AFC = "P1";
2458
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2459
                                                newRow["PUMP"] = "PUMP";
2460
                                        }
2461

    
2462
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2463
                                        {
2464
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2465
                                                AFC = "P1";
2466
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2467
                                                newRow["PUMP"] = "PUMP";
2468
                                        }
2469

    
2470
                                        newRow["AFC"] = AFC;
2471

    
2472
                                        newRow["EGTag"] = string.Empty;
2473
                                        newRow["HasMLTags"] = "False";
2474
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2475
                                    }
2476
                                }
2477

    
2478
                            }
2479
                        
2480

    
2481
                        }
2482
                        catch (Exception ex)
2483
                        {
2484
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2485
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2486
                        }
2487

    
2488
                        //TopologySet 관련
2489
                        foreach (Topology topology in PSNItem.Topologies)
2490
                        {
2491
                            DataRow newRow = topologySetDT.NewRow();
2492
                            newRow["OID"] = topology.FullName;
2493
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
2494
                            if (bVentDrain)
2495
                                newRow["SubType"] = "Vent_Drain";
2496
                            else
2497
                                newRow["SubType"] = null;
2498
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
2499
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
2500
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
2501
                            newRow["TailItemSPID"] = topology.Items.First().UID;
2502
                            topologySetDT.Rows.Add(newRow);
2503
                        }
2504

    
2505
                    }
2506
                    catch (Exception ee)
2507
                    {
2508

    
2509
                    }
2510
                }
2511

    
2512

    
2513
                foreach (var item in startBranchDic)
2514
                {
2515
                    string uid = item.Key.UID;
2516
                    string topologyName = item.Value.Topology.FullName;
2517
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2518

    
2519
                    if (rows.Length == 1)
2520
                    {
2521
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2522
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2523
                    }
2524
                    else if (rows.Length > 1)
2525
                    {
2526
                        DataRow targetRow = null;
2527
                        int index = int.MaxValue;
2528
                        foreach (DataRow row in rows)
2529
                        {
2530
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2531
                            if (split.StartsWith("L"))
2532
                            {
2533
                                int num = Convert.ToInt32(split.Remove(0, 1));
2534
                                if (index > num)
2535
                                {
2536
                                    index = num;
2537
                                    targetRow = row;
2538
                                }
2539
                            }
2540
                        }
2541

    
2542
                        if (targetRow != null)
2543
                        {
2544
                            targetRow["BranchTopologySet_OID"] = topologyName;
2545
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2546
                        }
2547
                    }
2548
                }
2549

    
2550
                foreach (var item in endBranchDic)
2551
                {
2552
                    string uid = item.Key.UID;
2553
                    string topologyName = item.Value.Topology.FullName;
2554
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2555
                    if (rows.Length == 1)
2556
                    {
2557
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2558
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2559
                    }
2560
                    else if (rows.Length > 1)
2561
                    {
2562
                        DataRow targetRow = null;
2563
                        int index = int.MinValue;
2564
                        foreach (DataRow row in rows)
2565
                        {
2566
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2567
                            if (split.StartsWith("L"))
2568
                            {
2569
                                int num = Convert.ToInt32(split.Remove(0, 1));
2570
                                if (index < num)
2571
                                {
2572
                                    index = num;
2573
                                    targetRow = row;
2574
                                }
2575
                            }
2576
                        }
2577

    
2578
                        if (targetRow != null)
2579
                        {
2580
                            targetRow["BranchTopologySet_OID"] = topologyName;
2581
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2582
                        }
2583
                    }
2584
                }
2585

    
2586
                PathItems = pathItemsDT;
2587
                SequenceData = sequenceDataDT;
2588
                PipeSystemNetwork = pipeSystemNetworkDT;
2589
                TopologySet = topologySetDT;
2590
                PipeLine = pipelineDT;
2591
                PipeSystem = pipesystemDT;
2592
            }
2593
            catch (Exception ex)
2594
            {
2595
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2596
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2597
            }
2598
        }
2599

    
2600
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2601
        {
2602
            foreach (double lacc in lstAcc)
2603
            {
2604
                acc *= lacc;
2605
            }
2606
            return acc;
2607
        }
2608

    
2609
        private void UpdateSubType()
2610
        {
2611
            try
2612
            {
2613
                foreach (PSNItem PSNItem in PSNItems)
2614
                {
2615
                    if (PSNItem.IsBypass)
2616
                    {
2617
                        foreach (Topology topology in PSNItem.Topologies)
2618
                        {
2619
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2620
                            if (rows.Length.Equals(1))
2621
                                rows.First()["SubType"] = "Bypass";
2622
                        }
2623
                    }
2624

    
2625
                    if (PSNItem.StartType == PSNType.Header)
2626
                    {
2627
                        Topology topology = PSNItem.Topologies.First();
2628
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2629
                        if (rows.Length.Equals(1))
2630
                            rows.First()["SubType"] = "Header";
2631
                    }
2632
                    else if (PSNItem.EndType == PSNType.Header)
2633
                    {
2634
                        Topology topology = PSNItem.Topologies.Last();
2635
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2636
                        if (rows.Length.Equals(1))
2637
                            rows.First()["SubType"] = "Header";
2638
                    }
2639
                }
2640

    
2641

    
2642
                foreach (Topology topology in Topologies)
2643
                {
2644
                    try
2645
                    {
2646
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2647

    
2648
                        if (rows.Count() > 0)
2649
                        {
2650
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2651
                            {
2652
                                if (topology.Items == null)
2653
                                    continue;
2654

    
2655
                                Item firstItem = topology.Items.First();
2656
                                Item lastItem = topology.Items.Last();
2657

    
2658
                                List<Relation> relations = new List<Relation>();
2659

    
2660
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2661
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2662

    
2663
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2664
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2665

    
2666
                                if (relations.Count > 0)
2667
                                    rows.First()["SubType"] = "OtherSystem";
2668
                            }
2669
                        }
2670
                    }
2671
                    catch (Exception ex)
2672
                    {
2673

    
2674
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2675
                    }
2676
                }
2677

    
2678
                foreach (DataRow row in TopologySet.Rows)
2679
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
2680
                        row["SubType"] = "Normal";
2681
            }
2682
            catch (Exception ex)
2683
            {
2684
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2685
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2686
            }
2687
        }
2688

    
2689
        private bool IsBypass(PSNItem PSNItem)
2690
        {
2691
            bool bResult = false;
2692

    
2693
            if (PSNItem.GetPSNType() == "B2B")
2694
            {
2695
                Group firstGroup = PSNItem.Groups.First();
2696
                Group lastGroup = PSNItem.Groups.Last();
2697
                Item firstItem = firstGroup.Items.First();
2698
                Item lastItem = lastGroup.Items.Last();
2699

    
2700
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
2701
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
2702

    
2703
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
2704
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
2705
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
2706
                    bResult = true;
2707
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
2708
                    bResult = true;
2709
            }
2710

    
2711
            Item GetConnectedItemByPSN(Item item)
2712
            {
2713
                Item result = null;
2714

    
2715
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
2716
                if (relation != null)
2717
                    result = relation.Item;
2718

    
2719

    
2720
                return result;
2721
            }
2722

    
2723
            return bResult;
2724
        }
2725

    
2726
        private void DeleteVentDrain()
2727
        {
2728
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
2729

    
2730
            foreach (DataRow dataRow in ventdrainRows)
2731
            {
2732
                dataRow.Delete();
2733
            }
2734
        }
2735

    
2736
        private void UpdateAccuracy()
2737
        {
2738
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
2739
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
2740
            List<double> lstAcc = null;
2741
            string Status = string.Empty;
2742

    
2743
            foreach (DataRow dataRow in statusRows)
2744
            {
2745
                lstAcc = new List<double>();
2746
                Status = dataRow.Field<string>("Status");
2747
                if (!string.IsNullOrEmpty(Status))
2748
                {
2749
                    string[] arrStatus = Status.Split(',');
2750
                    foreach (string arrstr in arrStatus)
2751
                    {
2752
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
2753
                            lstAcc.Add(0.75);
2754

    
2755
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2756
                            lstAcc.Add(0.7);
2757

    
2758
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2759
                            lstAcc.Add(0.5);
2760

    
2761
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2762
                            lstAcc.Add(0.65);
2763

    
2764
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2765
                            lstAcc.Add(0.6);
2766
                    }
2767
                }
2768

    
2769
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
2770
                if (PSNAccuracy == "100")
2771
                    PSNAccuracy = "1";
2772

    
2773
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
2774
                //if (PSNAccuracy != "100")
2775
                //{
2776
                //    //dataRow["IncludingVirtualData"] = "No";
2777
                dataRow["PSNAccuracy"] = PSNAccuracy;
2778
                //}
2779
            }
2780
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
2781
            foreach (DataRow dr in dt.Rows)
2782
            {
2783
                string oid = dr.Field<string>("OID");
2784
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
2785
                double totalDdr = 0;
2786
                foreach (DataRow ddr in select)
2787
                {
2788
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
2789
                    if (acc == 100) acc = 1;
2790
                    if (totalDdr == 0) totalDdr = acc;
2791
                    else totalDdr *= acc;
2792
                }
2793

    
2794
                totalDdr *= 100;
2795

    
2796
                if (totalDdr != 100)
2797
                {
2798
                    foreach (DataRow ddr in select)
2799
                    {
2800
                        ddr["IncludingVirtualData"] = "Yes";
2801
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2802
                    }
2803
                }
2804
                else
2805
                {
2806
                    foreach (DataRow ddr in select)
2807
                    {
2808
                        ddr["IncludingVirtualData"] = "No";
2809
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2810
                    }
2811
                }
2812
            }
2813

    
2814
        }
2815

    
2816
        private void UpdateKeywordForPSN()
2817
        {
2818
            #region Keyword Info
2819
            KeywordInfo KeywordInfos = new KeywordInfo();
2820
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2821
            foreach (DataRow row in dtKeyword.Rows)
2822
            {
2823
                int index = Convert.ToInt32(row["INDEX"]);
2824
                string name = row["NAME"].ToString();
2825
                string keyword = row["KEYWORD"].ToString();
2826

    
2827
                //KeywordInfo keywordInfo = new KeywordInfo();   
2828
                KeywordInfos.KeywordItems.Add(new KeywordItem()
2829
                {
2830
                    Index = index,
2831
                    Name = name,
2832
                    Keyword = keyword
2833
                });
2834
            }
2835
            #endregion
2836

    
2837
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
2838
            foreach (DataRow dataRow in endofHeaderRows)
2839
            {
2840
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2841

    
2842
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
2843
                {
2844
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2845
                    DataRow dr = pathItemRows.First();
2846
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
2847
                    dr["TYPE"] = "End";
2848
                    dr["ITEMTAG"] = "ENDOFHEADER";
2849
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2850
                }
2851

    
2852
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
2853
                {
2854
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2855
                    DataRow dr = pathItemRows.Last();
2856
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
2857
                    dr["TYPE"] = "End";
2858
                    dr["ITEMTAG"] = "ENDOFHEADER";
2859
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2860
                }
2861
            }
2862

    
2863
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2864
            {
2865
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
2866
                foreach (DataRow dataRow in keywordRows)
2867
                {
2868
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2869

    
2870
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
2871
                    {
2872
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2873

    
2874
                        //
2875
                        //if(.)
2876
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
2877
                        {
2878
                            DataRow dr = pathItemRows.First();
2879
                            //dr["CLASS"] = ""; //Type
2880
                            dr["TYPE"] = "End";
2881
                            dr["ITEMTAG"] = keyitem.Keyword;
2882
                            dr["DESCRIPTION"] = keyitem.Keyword;
2883
                        }
2884

    
2885
                    }
2886

    
2887
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
2888
                    {
2889
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2890

    
2891
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
2892
                        {
2893
                            DataRow dr = pathItemRows.Last();
2894
                            //dr["CLASS"] = ""; //Type
2895
                            dr["TYPE"] = "End";
2896
                            dr["ITEMTAG"] = keyitem.Keyword;
2897
                            dr["DESCRIPTION"] = keyitem.Keyword;
2898
                            //dr.Field<string>("Type")
2899
                        }
2900

    
2901
                    }
2902
                }
2903
            }
2904
        }
2905

    
2906
        private void UpdateErrorForPSN()
2907
        {
2908
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
2909
            foreach (DataRow dataRow in errorRows)
2910
            {
2911
                try
2912
                {
2913
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2914
                   
2915
                    bool change = false;
2916
                    bool bCheck = false;
2917
                    if (!PSNItem.EnableType(PSNItem.StartType))
2918
                    {
2919
                        change = true;
2920
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2921
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2922

    
2923
                        Item item = PSNItem.Groups.First().Items.First();
2924
                        try
2925
                        {
2926
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2927

    
2928
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2929
                            {
2930
                                loopRow["FROM_DATA"] = FROM_DATA;
2931
                                if (item.ItemType == ItemType.Line)
2932
                                {
2933
                                    if (loopRow.Field<string>("OrderNumber") == "0")
2934
                                    {
2935
                                        string status = loopRow.Field<string>("Status");
2936
                                        //string isvali
2937
                                        if (string.IsNullOrEmpty(status))
2938
                                            status = "Line Disconnected";
2939
                                        else if (!status.Contains("Line Disconnected"))
2940
                                            status += ", Line Disconnected";
2941
                                        loopRow["Status"] = status;
2942
                                        if (!string.IsNullOrEmpty(status))
2943
                                            loopRow["IsValid"] = "Error";
2944
                                    }
2945
                                }
2946
                            }
2947

    
2948
                            tieInPointIndex++;
2949

    
2950
                            if (item.ItemType == ItemType.Line)
2951
                            {
2952
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);                                
2953
                            }
2954
                            else
2955
                            {
2956
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
2957
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2958

    
2959
                                bCheck = true;
2960
                            }
2961

    
2962
                            PSNItem.StartType = PSNType.Equipment;
2963
                        }
2964
                        catch (Exception ex)
2965
                        {
2966
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2967
                            return;
2968
                        }
2969
                    }
2970

    
2971
                    if (!PSNItem.EnableType(PSNItem.EndType))
2972
                    {                        
2973
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2974
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
2975
                        DataRow dr = pathItemRows.Last();
2976
                        if (change)
2977
                        {
2978
                            if(bCheck)
2979
                                dr = pathItemRows[pathItemRows.Count() - 3];
2980
                            else
2981
                            {
2982
                                dr = pathItemRows[pathItemRows.Count() - 2];
2983
                            }
2984
                        }
2985

    
2986
                        change = true;
2987
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2988

    
2989
                        Item item = PSNItem.Groups.Last().Items.Last();
2990
                        try
2991
                        {
2992
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2993

    
2994
                           
2995
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2996
                            {
2997
                                loopRow["TO_DATA"] = TO_DATA;
2998
                                if (item.ItemType == ItemType.Line)
2999
                                {
3000
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
3001
                                    {
3002
                                        string status = loopRow.Field<string>("Status");
3003
                                        if (string.IsNullOrEmpty(status))
3004
                                            status = "Line Disconnected";
3005
                                        else if (!status.Contains("Line Disconnected"))
3006
                                            status += ", Line Disconnected";
3007
                                        loopRow["Status"] = status;
3008
                                        if (!string.IsNullOrEmpty(status))
3009
                                            loopRow["IsValid"] = "Error";
3010
                                    }
3011
                                }
3012
                            }                            
3013

    
3014
                            tieInPointIndex++;
3015

    
3016
                            if (item.ItemType == ItemType.Line)
3017
                            {
3018
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3019
                            }
3020
                            else
3021
                            {
3022
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3023
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
3024
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
3025
                            }
3026

    
3027
                            PSNItem.EndType = PSNType.Equipment;
3028
                        }
3029
                        catch (Exception ex)
3030
                        {
3031
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3032
                            return;
3033
                        }
3034
                    }
3035

    
3036
                    dataRow["Type"] = PSNItem.GetPSNType();
3037
                    if (change)
3038
                    {
3039
                        int rowIndex = 0;
3040
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3041
                        {
3042
                            DataRow row = PathItems.Rows[i];
3043
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
3044
                                continue;
3045
                            string sequenceData = row["SequenceData_OID"].ToString();
3046
                            string[] split = sequenceData.Split(new char[] { '_' });
3047

    
3048
                            StringBuilder sb = new StringBuilder();
3049
                            for (int j = 0; j < split.Length - 1; j++)
3050
                                sb.Append(split[j] + "_");
3051
                            sb.Append(rowIndex++);
3052
                            row["SequenceData_OID"] = sb.ToString();
3053

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

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

    
3059
                            if (seqItemRows == null)
3060
                            {
3061
                                DataRow newRow = SequenceData.NewRow();
3062
                                newRow["OID"] = sb.ToString();
3063
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3064
                                newRow["PathItem_OID"] = row["OID"];
3065
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3066
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3067
                            }
3068
                            else
3069
                            {
3070
                                seqItemRows["OID"] = sb.ToString();
3071
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3072
                                seqItemRows["PathItem_OID"] = row["OID"];
3073
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3074
                            }
3075
                        }
3076
                    }
3077

    
3078
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
3079
                    {
3080
                        DataRow newRow = PathItems.NewRow();
3081
                        newRow["OID"] = Guid.NewGuid().ToString();
3082
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3083
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3084
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3085
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3086
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
3087
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
3088
                        newRow["DESCRIPTION"] = DATA;
3089
                        newRow["Class"] = "End of line terminator";
3090
                        newRow["SubClass"] = "End of line terminator";
3091
                        newRow["TYPE"] = "End";
3092
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3093
                        newRow["NPD"] = itemRow["NPD"];
3094
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3095
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3096
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3097
                        newRow["EGTConnectedPoint"] = "0";
3098
                        return newRow;
3099
                    }
3100

    
3101
                    DataRow createLineRow(DataRow itemRow)
3102
                    {
3103
                        DataRow newRow = PathItems.NewRow();
3104
                        newRow["OID"] = Guid.NewGuid().ToString();
3105
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3106
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3107
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3108
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3109
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
3110
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3111
                        newRow["Class"] = itemRow["Class"];
3112
                        newRow["SubClass"] = itemRow["SubClass"];
3113
                        newRow["TYPE"] = itemRow["TYPE"];
3114
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3115
                        newRow["NPD"] = itemRow["NPD"];
3116
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3117
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3118
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3119
                        newRow["EGTConnectedPoint"] = "0";
3120
                        return newRow;
3121
                    }
3122
                }
3123
                catch (Exception ex)
3124
                {
3125

    
3126
                }
3127
            }
3128
        }
3129

    
3130
        private void InsertTeePSN()
3131
        {
3132
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
3133
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
3134
            bool change = false;
3135
            foreach (DataRow dataRow in branchRows)
3136
            {
3137
                try
3138
                {
3139
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3140
                    change = false;
3141

    
3142
                    if (PSNItem.StartType == PSNType.Branch)
3143
                    {
3144
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3145
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3146
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3147
                        try
3148
                        {
3149
                            if (Teeitem.ItemType == ItemType.Line)
3150
                            {
3151
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3152
                                {
3153
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3154
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3155
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3156
                                    change = true;
3157
                                }
3158

    
3159
                            }
3160
                        }
3161
                        catch (Exception ex)
3162
                        {
3163
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3164
                            return;
3165
                        }
3166
                    }
3167

    
3168
                    if (PSNItem.EndType == PSNType.Branch)
3169
                    {
3170
                        //change = true;
3171
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3172

    
3173
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3174

    
3175
                        DataRow dr = pathItemRows.Last();
3176
                        if (change)
3177
                            dr = pathItemRows[pathItemRows.Count() - 2];
3178

    
3179
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3180

    
3181
                        try
3182
                        {
3183
                            if (Teeitem.ItemType == ItemType.Line)
3184
                            {
3185
                                if (dr.Field<string>("SubClass") != "Tee")
3186
                                {
3187
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3188
                                    change = true;
3189
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3190
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3191
                                }
3192

    
3193
                            }
3194
                        }
3195
                        catch (Exception ex)
3196
                        {
3197
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3198
                            return;
3199
                        }
3200
                    }
3201

    
3202
                    if (change)
3203
                    {
3204
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3205
                        int rowIndex = 0;
3206
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3207
                        {
3208
                            DataRow row = PathItems.Rows[i];
3209
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3210
                                continue;
3211
                            string sequenceData = row["SequenceData_OID"].ToString();
3212
                            string[] split = sequenceData.Split(new char[] { '_' });
3213

    
3214
                            StringBuilder sb = new StringBuilder();
3215
                            for (int j = 0; j < split.Length - 1; j++)
3216
                                sb.Append(split[j] + "_");
3217
                            sb.Append(rowIndex++);
3218
                            row["SequenceData_OID"] = sb.ToString();
3219

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

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

    
3225
                            if (seqItemRows == null)
3226
                            {
3227
                                DataRow newRow = SequenceData.NewRow();
3228
                                newRow["OID"] = sb.ToString();
3229
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3230
                                newRow["PathItem_OID"] = row["OID"];
3231
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3232
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3233
                            }
3234
                            else
3235
                            {
3236
                                seqItemRows["OID"] = sb.ToString();
3237
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3238
                                seqItemRows["PathItem_OID"] = row["OID"];
3239
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3240
                            }
3241
                        }
3242
                    }
3243

    
3244
                    DataRow createTeeRow(DataRow itemRow)
3245
                    {
3246
                        DataRow newRow = PathItems.NewRow();
3247
                        newRow["OID"] = Guid.NewGuid().ToString();
3248
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3249
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3250
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3251
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3252
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3253
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3254
                        newRow["DESCRIPTION"] = "";
3255
                        newRow["Class"] = "Branch";
3256
                        newRow["SubClass"] = "Tee";
3257
                        newRow["TYPE"] = itemRow["TYPE"];
3258
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3259
                        newRow["NPD"] = itemRow["NPD"];
3260
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3261
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3262
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3263
                      
3264
                        newRow["EGTConnectedPoint"] = 0;
3265
                        return newRow;
3266
                    }
3267
                }
3268
                catch (Exception ex)
3269
                {
3270

    
3271
                }
3272
            }
3273
        }
3274
    }
3275

    
3276
    public class PSNItem
3277
    {
3278
        public PSNItem(int count, int Revision)
3279
        {
3280
            Groups = new List<Group>();
3281
            Topologies = new List<Topology>();
3282

    
3283
            Index = count + 1;
3284
            this.Revision = Revision;
3285
        }
3286

    
3287
        private int Revision;
3288
        public string UID { get; set; }
3289
        public List<Group> Groups { get; set; }
3290
        public List<Topology> Topologies { get; set; }
3291
        public PSNType StartType { get; set; }
3292
        public PSNType EndType { get; set; }
3293
        public int Index { get; set; }
3294
        public string IsValid { get; set; }
3295
        public bool IsKeyword { get; set; }
3296
        public string Status { get; set; }
3297
        public string IncludingVirtualData { get; set; }
3298
        public string PSNAccuracy { get; set; }
3299
        public KeywordInfo KeywordInfos = new KeywordInfo();
3300
        public DataTable Nozzle = new DataTable();
3301

    
3302
        public string PSN_OID()
3303
        {
3304
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
3305
        }
3306

    
3307
        public string GetPSNType()
3308
        {
3309
            string result = string.Empty;
3310

    
3311
            if (EnableType(StartType) && EnableType(EndType))
3312
            {
3313
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
3314
                    result = "E2E";
3315
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
3316
                    result = "B2B";
3317
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
3318
                    result = "HD2";
3319

    
3320
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
3321
                    result = "E2B";
3322
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
3323
                    result = "B2E";
3324

    
3325
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
3326
                    result = "HDB";
3327
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
3328
                    result = "HDB";
3329

    
3330
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
3331
                    result = "HDE";
3332
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
3333
                    result = "HDE";
3334
                else
3335
                    result = "Error";
3336
            }
3337
            else
3338
                result = "Error";
3339

    
3340
            return result;
3341

    
3342

    
3343
        }
3344

    
3345
        public bool EnableType(PSNType type)
3346
        {
3347
            bool result = false;
3348

    
3349
            if (type == PSNType.Branch ||
3350
                type == PSNType.Equipment ||
3351
                type == PSNType.Header)
3352
            {
3353
                result = true;
3354
            }
3355

    
3356
            return result;
3357
        }
3358

    
3359
        public bool IsBypass { get; set; }
3360

    
3361
        public string GetFromData(ref string Type, ref Item item)
3362
        {
3363
            Status = string.Empty;
3364
            string result = string.Empty;
3365
            if (IsKeyword)
3366
                IsKeyword = false;
3367
            try
3368
            {
3369
                item = Groups.First().Items.First();
3370

    
3371
                if (StartType == PSNType.Header)
3372
                    result = "ENDOFHEADER";
3373
                else if (StartType == PSNType.Branch)
3374
                {
3375
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3376
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3377
                        result = item.Relations.First().Item.LineNumber.Name;
3378
                    else
3379
                    {
3380
                        IsValid = "Error";
3381
                        result = "Empty LineNumber";
3382
                    }
3383

    
3384
                    if (item.MissingLineNumber2)
3385
                        Status += ", Missing LineNumber_2";
3386

    
3387

    
3388
                    //if (item.MissingLineNumber1)
3389
                    //{
3390
                    //    Status += ", Missing LineNumber_1";
3391
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3392

    
3393
                    //}
3394
                }
3395
                else if (StartType == PSNType.Equipment)
3396
                {
3397
                    if (Groups.First().Items.First().Equipment != null)
3398
                        result = Groups.First().Items.First().Equipment.ItemTag;
3399
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
3400

    
3401
                    if (drNozzle != null)
3402
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3403
                }
3404
                else
3405
                {
3406
                    IsValid = "Error";
3407
                    item = Groups.First().Items.First();
3408
                    if (item.ItemType == ItemType.Symbol)
3409
                    {
3410

    
3411
                        string keyword = string.Empty;
3412
                        keyword = GetFromKeywordData(ref Type, item);
3413

    
3414
                        if (string.IsNullOrEmpty(keyword))
3415
                        {
3416
                            if (item.ID2DBType.Contains("OPC's"))
3417
                                Status += ", OPC Disconnected";
3418
                            else
3419
                                Status += ", Missing ItemTag or Description";
3420

    
3421
                            result = item.ID2DBName;
3422
                        }
3423
                        else
3424
                        {
3425
                            result = keyword;
3426
                            IsKeyword = true;
3427
                            IsValid = string.Empty;
3428
                        }
3429

    
3430
                    }
3431
                    else if (item.ItemType == ItemType.Line)
3432
                    {
3433

    
3434
                        if (item.MissingLineNumber1)
3435
                        {
3436
                            IsValid = "Error";
3437
                            Status += ", Missing LineNumber_1";
3438
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3439
                        }
3440
                        else
3441
                            result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3442
                    }
3443
                    else
3444
                        result = "Unknown";
3445

    
3446
                }
3447
            }
3448
            catch (Exception ex)
3449
            {
3450

    
3451
            }
3452

    
3453
            return result;
3454
        }
3455

    
3456
        public string GetFromKeywordData(ref string Type, Item item)
3457
        {
3458
            string result = string.Empty;
3459

    
3460
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3461
            {
3462
                if (keyitem.Name.Equals(item.Name))
3463
                {
3464
                    result = keyitem.Keyword;
3465
                    Type = item.ID2DBType;
3466
                    break;
3467
                }
3468
            }
3469

    
3470
            return result;
3471
        }
3472

    
3473
        public string GetToKeywordData(ref string Type, Item item)
3474
        {
3475
            string result = string.Empty;
3476

    
3477
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3478
            {
3479
                if (keyitem.Name.Equals(item.Name))
3480
                {
3481
                    result = keyitem.Keyword;
3482
                    Type = item.ID2DBType;
3483
                    break;
3484
                }
3485
            }
3486
            return result;
3487
        }
3488

    
3489
        public string GetToData(ref string ToType, ref Item item)
3490
        {
3491
            string result = string.Empty;
3492
            Status = string.Empty;
3493

    
3494
            if (IsKeyword)
3495
                IsKeyword = false;
3496

    
3497
            item = Groups.Last().Items.Last();
3498

    
3499
            if (EndType == PSNType.Header)
3500
                result = "ENDOFHEADER";
3501
            else if (EndType == PSNType.Branch)
3502
            {
3503
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3504
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3505
                    result = item.Relations.Last().Item.LineNumber.Name;
3506
                else
3507
                {
3508
                    IsValid = "Error";                    
3509
                    result = "Empty LineNumber";
3510
                }
3511

    
3512
                if(item.MissingLineNumber2)
3513
                    Status += ", Missing LineNumber_2";
3514
                //if (item.MissingLineNumber1)
3515
                //{
3516
                //    Status += ", Missing LineNumber_1";
3517
                //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3518

    
3519
                //}
3520
            }
3521
            else if (EndType == PSNType.Equipment)
3522
            {
3523
                if (Groups.Last().Items.Last().Equipment != null)
3524
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3525

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

    
3528
                if (drNozzle != null)
3529
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3530
            }
3531
            else
3532
            {
3533
                IsValid = "Error";
3534
                item = Groups.Last().Items.Last();
3535
                if (item.ItemType == ItemType.Symbol)
3536
                {
3537
                    string keyword = string.Empty;
3538
                    keyword = GetToKeywordData(ref ToType, item);
3539

    
3540
                    if (string.IsNullOrEmpty(keyword))
3541
                    {
3542
                        if (item.ID2DBType.Contains("OPC's"))
3543
                            Status += ", OPC Disconnected";
3544
                        else
3545
                            Status += ", Missing ItemTag or Description";
3546

    
3547
                        result = item.ID2DBName;
3548
                    }
3549
                    else
3550
                    {
3551
                        result = keyword;
3552
                        IsValid = string.Empty;
3553
                        IsKeyword = true;
3554
                    }
3555

    
3556
                }
3557
                else if (item.ItemType == ItemType.Line)
3558
                {
3559
                    if (item.MissingLineNumber1)
3560
                    {
3561
                        IsValid = "Error";
3562
                        Status += ", Missing LineNumber_1";
3563
                        result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3564
                    }
3565
                    else
3566
                        result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3567
                }
3568
                else
3569
                    result = "Unknown";
3570

    
3571

    
3572
            }
3573

    
3574

    
3575

    
3576
            return result;
3577
        }
3578

    
3579
        public string GetPBSData()
3580
        {
3581
            string result = string.Empty;
3582
            List<string> PBSList = new List<string>();
3583
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3584
            {
3585
                string attrValue = Settings.Default.PBSSettingValue;
3586

    
3587
                foreach (Group group in Groups)
3588
                {
3589
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3590
                    foreach (LineNumber lineNumber in lineNumbers)
3591
                    {
3592
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3593
                        if (attribute != null)
3594
                        {
3595
                            string value = attribute.Value;
3596
                            if (!PBSList.Contains(value))
3597
                                PBSList.Add(value);
3598
                        }
3599
                    }
3600
                }
3601
            }
3602
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3603
            {
3604
                string attrValue = Settings.Default.PBSSettingValue;
3605

    
3606
                foreach (Group group in Groups)
3607
                {
3608
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3609
                    foreach (Item item in items)
3610
                    {
3611
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3612
                        if (!PBSList.Contains(value))
3613
                            PBSList.Add(value);
3614
                    }
3615
                }
3616
            }
3617
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3618
            {
3619
                string attrValue = Settings.Default.PBSSettingValue;
3620

    
3621
                foreach (Group group in Groups)
3622
                {
3623
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3624
                    foreach (Document document in documents)
3625
                    {
3626
                        string name = document.DrawingName;
3627

    
3628
                        int startIndex = Settings.Default.PBSSettingStartValue;
3629
                        int endIndex = Settings.Default.PBSSettingEndValue;
3630

    
3631
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3632
                        if (!PBSList.Contains(subStr))
3633
                            PBSList.Add(subStr);
3634
                    }
3635
                }
3636
            }
3637
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3638
            {
3639
                foreach (Group group in Groups)
3640
                {
3641
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3642
                    foreach (Document document in documents)
3643
                    {
3644
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
3645
                        foreach (TextInfo textInfo in textInfos)
3646
                        {
3647
                            if (!PBSList.Contains(textInfo.Value))
3648
                                PBSList.Add(textInfo.Value);
3649
                        }
3650
                    }
3651
                }
3652
            }
3653

    
3654
            foreach (var item in PBSList)
3655
            {
3656
                if (string.IsNullOrEmpty(result))
3657
                    result = item;
3658
                else
3659
                    result += ", " + item;
3660
            }
3661
            return result;
3662
        }
3663
    }
3664
}
클립보드 이미지 추가 (최대 크기: 500 MB)