프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ e3562345

이력 | 보기 | 이력해설 | 다운로드 (168 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

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

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

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

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

    
53
        int tieInPointIndex = 1;
54

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

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

    
63
        ID2Info id2Info = ID2Info.GetInstance();
64

    
65

    
66

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

    
70
        public PSN()
71
        {
72

    
73
        }
74

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

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

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

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

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

    
207
        public void SetPSNData()
208
        {
209
            // Item들의 속성으로 Topology Data를 생성한다.
210
            // Topology Data는 Topology Rule Setting을 기준으로 생성한다.             
211
            SetTopologyData();
212
            // ID2의 OPC연결 Data 기반으로 Group(도면단위 PSN)을 연결한다.
213
            ConnectByOPC();
214
            // 실제 PSN 생성 로직
215
            // 연결된 Group을 하나의 PSN으로 만든다.
216
            SetPSNItem();
217
            // 생성된 PSN의 Type을 설정한다.
218
            SetPSNType();
219
            // ID2에는 Branch 정보가 없어서 Branch 정보를 생성한다.
220
            SetBranchInfo();
221
            // 생성된 Topology Data들을 정리하며 Main, Branch를 판단한다.
222
            SetTopology();
223
            // PSN이 Bypass인지 검사 
224
            SetPSNBypass();
225
            // Topology들에게 Index를 부여한다
226
            SetTopologyIndex();
227
            // Nozzle, Equipment의 정보를 저장
228
            SaveNozzleAndEquipment();
229
            // PSN의 정보를 저장
230
            SavePSNData();
231
            // Update Keyword
232
            UpdateKeywordForPSN();
233
            // Vent/Drain PSN 데이터 제거
234
            DeleteVentDrain();
235
            // Topology의 subtype을 update(bypass, Header, 등등) 
236
            UpdateSubType();
237
            // Update Error
238
            UpdateErrorForPSN();
239
            // Insert Tee
240
            InsertTeePSN();
241
            // 확도 계산
242
            UpdateAccuracy();
243
            // ValveGrouping
244
            UpdateValveGrouping();
245

    
246
            PathItemSorting();
247

    
248
            // AirFinCooler 
249
            UpdateAirFinCooler();
250

    
251
        }
252

    
253
        private void PathItemSorting()
254
        {
255
            try
256
            {
257
                DataTable dtPathItems = PathItems.Clone();
258
                DataTable dtPipeSystemNetwork = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
259

    
260
                foreach (DataRow drpipe in dtPipeSystemNetwork.Rows)
261
                {
262
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drpipe["OID"].ToString()));
263
                    DataTable dtSequenceItems = SequenceData.Clone();
264
                    foreach (DataRow drpath in pathItemRows)
265
                    {
266
                        DataRow sequenceRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", drpath.Field<string>("OID"))).First();
267

    
268
                        DataRow newRow = dtSequenceItems.NewRow();
269
                        foreach (DataColumn column in SequenceData.Columns)
270
                            if (dtSequenceItems.Columns[column.ColumnName] != null)
271
                                newRow[column.ColumnName] = sequenceRows[column.ColumnName];
272

    
273
                        dtSequenceItems.Rows.Add(newRow);
274
                    }
275

    
276
                    foreach (DataRow sqrow in dtSequenceItems.Select().OrderBy(x => Convert.ToInt32(x.Field<string>("SERIALNUMBER"))))
277
                    {
278
                        DataRow newRow = dtPathItems.NewRow();
279
                        DataRow row = PathItems.Select(string.Format("OID = '{0}'", sqrow["PathItem_OID"])).First();
280

    
281
                        foreach (DataColumn column in PathItems.Columns)
282
                            if (dtPathItems.Columns[column.ColumnName] != null)
283
                                newRow[column.ColumnName] = row[column.ColumnName];
284

    
285
                        dtPathItems.Rows.Add(newRow);
286
                    }
287
                }
288

    
289
                PathItems.Clear();
290
                PathItems = dtPathItems.Copy();
291
            }
292
            catch (Exception ex)
293
            {
294
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
295
            }
296
        }
297
        
298
        private void UpdateAirFinCooler()
299
        {
300
            try
301
            {
302
                int afcTagNum = 0;
303
                int pumpTagNum = 0;
304
                #region EquipmentAirFinCooler Info
305
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
306
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
307
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
308
                {
309
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
310
                    {
311
                        Type = row["Type"].ToString(),
312
                        Name = row["Name"].ToString()
313
                    });
314
                }
315
                #endregion
316

    
317
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC = 'P1'");
318
                DataRow[] pumpRows = PipeSystemNetwork.Select("PUMP = 'PUMP'");
319
                // 1, 2번
320
                foreach (DataRow dataRow in pumpRows) 
321
                {
322
                    pumpTagNum++;
323

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

    
326
                    string eqTag = string.Empty;
327
                    string EGFlowDirection = string.Empty;
328
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
329
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
330
                    {
331
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
332
                        {
333
                            eqTag = PSNItem.Groups.First().Items.First().Equipment.ItemTag;
334
                            EGFlowDirection = "O";
335
                        }                        
336
                    } 
337
                    else if(PSNItem.Groups.Last().Items.Last().Equipment != null)
338
                    {
339
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
340
                        {
341
                            eqTag = PSNItem.Groups.Last().Items.Last().Equipment.ItemTag;
342
                            EGFlowDirection = "I";
343
                        }
344
                    }
345

    
346
                    if(!string.IsNullOrEmpty(eqTag))
347
                    {
348
                        foreach (DataRow dr in pathItemRows)
349
                        {
350
                            dr["EqpGroupTag"] = eqTag;
351
                            dr["EGFlowDirection"] = EGFlowDirection;
352
                        }
353
                    }
354
                }
355

    
356
                // 3, 4번
357
                foreach (DataRow dataRow in pumpRows) 
358
                {
359

    
360
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
361
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
362
                    string EGFlowDirection = string.Empty;
363

    
364
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
365
                    {
366
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
367
                        {
368
                            EGFlowDirection = "O";
369
                        }
370
                    }
371
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
372
                    {
373
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
374
                        {
375
                            EGFlowDirection = "I";
376
                        }
377
                    }
378

    
379

    
380
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
381

    
382
                    foreach (DataRow dr in pathItemRows)
383
                    {
384
                        if(dr.Field<string>("ViewPipeSystemNetwork_OID") != dataRow["OID"].ToString())
385
                        {
386
                            string viewEGFlowDirection = string.Empty;
387
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
388
                            {
389
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));                               
390

    
391
                                if (viewPSNItem.Groups.First().Items.First().Equipment != null)
392
                                {
393
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
394
                                    {
395
                                        viewEGFlowDirection = "O";
396
                                    }
397
                                }
398
                                else if (viewPSNItem.Groups.Last().Items.Last().Equipment != null)
399
                                {
400
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
401
                                    {
402
                                        viewEGFlowDirection = "I";
403
                                    }
404
                                }
405

    
406
                                if (EGFlowDirection.Equals(viewEGFlowDirection) && !lstViewPipeSystemNetwork_OID.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
407
                                    lstViewPipeSystemNetwork_OID.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
408
                            }
409
                            else
410
                            {
411
                            }
412
                        }
413
                    }
414

    
415
                    string selectViewOID = string.Empty;
416

    
417
                    if (EGFlowDirection == "O") //From 이면 시작점에서 제일 먼 값
418
                    {
419
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
420
                        {
421
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
422
                            {                                
423
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
424
                            }
425
                        }
426
                    }
427
                    else if (EGFlowDirection == "I") //To 이면 시작점에서 제일 가까운 값
428
                    {
429
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
430
                        {
431
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
432
                            {
433
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
434
                                break;
435
                            }
436
                        }
437
                    }
438

    
439
                    if (!string.IsNullOrEmpty(selectViewOID)) //selectViewOID 가 있으면
440
                    {              
441
                        string EqpGroupTag = string.Empty;                       
442

    
443
                        if((EGFlowDirection == "O" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.Last().Field<string>("ViewPipeSystemNetwork_OID"))) ||
444
                            (EGFlowDirection == "I" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID"))))
445
                        { 
446
                            DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID")));
447

    
448
                            foreach (DataRow row in viewpathItemRows)
449
                            {
450
                                if (!string.IsNullOrEmpty(row.Field<string>("EqpGroupTag")))
451
                                {
452
                                    EqpGroupTag = row.Field<string>("EqpGroupTag");
453
                                    break;
454
                                }
455
                            }
456

    
457
                            foreach (DataRow dr in pathItemRows)
458
                            {
459
                                dr["EqpGroupTag"] = EqpGroupTag;
460
                            }
461

    
462
                        }
463
                        else
464
                        {
465
                            bool bCheck = false;
466
                            if (EGFlowDirection == "I") //To 일때
467
                            {
468
                                foreach (DataRow dr in pathItemRows)
469
                                {
470
                                    if (selectViewOID == dr["OID"].ToString())
471
                                    {
472
                                        dr["EGTConnectedPoint"] = "1";
473
                                        bCheck = true;
474
                                    }
475

    
476
                                    if (!bCheck)
477
                                    {
478
                                        dr["EqpGroupTag"] = string.Empty;
479
                                        dr["MainLineTag"] = string.Empty;
480
                                        dr["EGTConnectedPoint"] = "0";
481
                                        dr["EGFlowDirection"] = string.Empty;
482
                                    }
483
                                    else
484
                                    {
485
                                        dr["MainLineTag"] = "M";
486
                                    }
487
                                    
488
                                }
489

    
490
                            }
491
                            else if (EGFlowDirection == "O") //From 일 때
492
                            {
493
                                foreach (DataRow dr in pathItemRows)
494
                                {
495
                                    if (bCheck)
496
                                    {
497
                                        
498
                                        dr["EqpGroupTag"] = string.Empty;
499
                                        dr["MainLineTag"] = string.Empty;
500
                                        dr["EGTConnectedPoint"] = "0";
501
                                        dr["EGFlowDirection"] = string.Empty;
502
                                    }
503
                                    else
504
                                    {
505
                                        dr["MainLineTag"] = "M";
506
                                    }
507

    
508
                                    if (selectViewOID == dr["OID"].ToString())
509
                                    {
510
                                        dr["EGTConnectedPoint"] = "1";
511
                                        bCheck = true;
512
                                    }
513
                                }
514
                            }
515
                        }
516
                    }
517
                    else
518
                    {
519
                        foreach (DataRow dr in pathItemRows)
520
                        {
521
                            dr["EqpGroupTag"] = string.Empty;
522
                            dr["EGFlowDirection"] = string.Empty;
523
                        }
524
                    }
525
                }
526
                                
527
                // 5번
528
                foreach (DataRow dataRow in pumpRows)
529
                {
530
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
531

    
532
                    bool bCheck = false;
533
                    string EqpGroupTag = string.Empty;
534

    
535
                    string EGFlowDirection = string.Empty;                   
536

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

    
539
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
540
                    {
541
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
542
                        {
543
                            EGFlowDirection = "O";
544
                        }
545
                    }
546
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
547
                    {
548
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
549
                        {
550
                            EGFlowDirection = "I";
551
                        }
552
                    }
553

    
554
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
555
                    List<string> lstEqTagRows = new List<string>();
556
                    if (EGFlowDirection.Equals("I"))
557
                    {
558
                        foreach (DataRow dr in pathItemRows)
559
                        {                            
560
                            if (!string.IsNullOrEmpty(dr.Field<string>("MainLineTag")) && dr.Field<string>("MainLineTag").Equals("M") && !string.IsNullOrEmpty(dr.Field<string>("EqpGroupTag")))
561
                            {
562
                                bCheck = true;
563
                                EqpGroupTag = dr.Field<string>("EqpGroupTag");
564
                                if(!lstEqTagRows.Contains(EqpGroupTag))
565
                                    lstEqTagRows.Add(EqpGroupTag);
566

    
567
                                if(dataRow["OID"].ToString() != dr.Field<string>("ViewPipeSystemNetwork_OID"))
568
                                {
569
                                    PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));
570
                                    if (viewPSNItem.Groups.Last().Items.Last().Equipment == null)
571
                                        continue;
572

    
573
                                    if (!lstEqTagRows.Contains(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag))
574
                                        lstEqTagRows.Add(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag);
575
                                }
576
                                
577
                            }
578

    
579
                        }
580
                        if(bCheck)
581
                        {
582
                            foreach (DataRow row in pumpRows)
583
                            {
584
                                if (row.Field<string>("OID").Equals(dataRow["OID"].ToString()))
585
                                    continue;
586

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

    
589
                                if (viewPSNItem.Groups.First().Items.First().Equipment == null)
590
                                    continue;
591
                                
592
                                if (lstEqTagRows.Contains(viewPSNItem.Groups.First().Items.First().Equipment.ItemTag) && !lstViewPipeSystemNetwork_OID.Contains(row.Field<string>("OID")))
593
                                    lstViewPipeSystemNetwork_OID.Add(row.Field<string>("OID"));
594
                            }
595

    
596
                                
597

    
598
                            if (lstViewPipeSystemNetwork_OID.Count() > 0)
599
                            {
600
                                foreach (string viewPipesystem in lstViewPipeSystemNetwork_OID)
601
                                {
602
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewPipesystem));
603
                                    foreach (DataRow viewdr in viewpathItemRows)
604
                                    {
605
                                        if (!string.IsNullOrEmpty(viewdr["EqpGroupTag"].ToString()))
606
                                            viewdr["EqpGroupTag"] = EqpGroupTag;
607
                                    }
608
                                }
609
                            }
610
                        }                        
611
                    }                   
612
                }
613
                
614
                foreach (DataRow dataRow in airFinCoolerRows)
615
                {
616
                    afcTagNum++;
617
                    string EGFlowDirection = string.Empty;
618

    
619
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
620
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
621
                    {
622
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
623
                        {
624
                            EGFlowDirection = "O";
625
                        }
626
                    }
627
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
628
                    {
629
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
630
                        {
631
                            EGFlowDirection = "I";
632
                        }
633
                    }
634

    
635
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
636
                    List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
637
                    //ViewPipeSystemNetwork_OID
638
                    string MainLineTag = "";
639
                    if (dataRow["Type"].ToString() == "E2E")
640
                    {
641
                        MainLineTag = "M";
642
                         dataRow["AFC"] = "P3";
643
                    }
644
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
645
                    {
646
                        int bCount = 0;
647
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
648
                        {
649
                            if (viewOID == dataRow["OID"].ToString())
650
                                continue;
651

    
652
                            DataRow dr = PipeSystemNetwork.Select(string.Format("OID = '{0}'", viewOID)).First();
653
                            if (dr.Field<string>("AFC") != "P1")
654
                            {
655
                                bCount++;
656
                                string[] arr = dr.Field<string>("AFC").Split('_');
657
                                if (arr.Length == 1)
658
                                    dr["AFC"] = arr[0] + "_1";
659
                                else
660
                                {
661
                                    dr["AFC"] = arr[0] + "_" + Convert.ToInt32(arr[1]) + 1;
662
                                    afcTagNum++;
663
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID));
664
                                    foreach (DataRow viewdr in viewpathItemRows)
665
                                    {
666
                                        viewdr["EqpGroupTag"] = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));  //ATG Sequence No Rule 여쭤봐야함.
667
                                        viewdr["MainLineTag"] = "M";
668
                                    }
669
                                }
670

    
671
                            }
672
                        }
673
                        
674
                        if(bCount == 1)
675
                        {
676
                            MainLineTag = "M";
677
                           // dataRow["AFC"] = "P3";
678
                        }
679
                            
680
                    }
681

    
682
                    foreach (DataRow dr in pathItemRows)
683
                    {
684
                        dr["EqpGroupTag"] = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));  //ATG Sequence No Rule 여쭤봐야함.
685
                        dr["MainLineTag"] = MainLineTag; 
686
                        dr["EGFlowDirection"] = EGFlowDirection; 
687
                    }
688
                }
689
                
690
                foreach (DataRow dataRow in airFinCoolerRows)
691
                {
692
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = ''", dataRow["OID"].ToString()));
693
                    //ML이 공란인 PSN - P1이 있다면 해당 Pathitem에 P3인 psn이 있는지 확인 : 해당 값은 전부 돌린후 확인 가능하기 때문에 다시 조회
694
                    if (pathItemRows.Count() > 0)
695
                    {
696
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
697
                        List<string> lstpsn = new List<string>();
698
                        string EqpGroupTag = string.Empty;
699
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
700
                        {
701
                            if (dataRow["OID"].ToString() == viewOID)
702
                            {
703
                                //lstViewPipeSystemNetwork_OID.Remove(viewOID);
704
                                continue;
705
                            }
706
                            DataRow viewPSN = null;
707
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
708
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
709
                            
710
                            if (viewPSN != null)
711
                            {
712
                                EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
713
                                foreach (DataRow dr in pathItemRows)
714
                                {
715
                                    dr["EqpGroupTag"] = EqpGroupTag;
716

    
717
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains("ViewPipeSystemNetwork_OID"))
718
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
719
                                }
720
                            }
721
                            
722
                        }
723

    
724
                        while(lstpsn.Count() != 0)
725
                        {
726
                            foreach(string psn in lstpsn)
727
                            {
728
                                DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", psn));
729
                                foreach (DataRow dr in rule4pathItems)
730
                                {
731
                                    dr["EqpGroupTag"] = EqpGroupTag;
732

    
733
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains("ViewPipeSystemNetwork_OID"))
734
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
735
                                }
736

    
737
                                lstpsn.Remove(psn);
738
                            }                        
739

    
740
                        }
741
                    }
742
                    
743
                }
744

    
745
                //DataRow[]  = PipeSystemNetwork.Select("AFC = 'P1'");
746
                foreach(DataRow dr in PipeSystemNetwork.Rows)
747
                {
748
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
749
                    if(pathItemRows.Count() > 0)
750
                    {
751
                        if(dr["Type"].ToString() == "HD2")
752
                        {
753
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
754
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
755
                            {                              
756
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
757
                                {
758
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
759
                                    {
760
                                        dataRow["EGTConnectedPoint"] = "1";
761
                                    }
762
                                }
763
                            }
764
                        }
765
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
766
                        {
767
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
768
                            string lastP1 = string.Empty;
769
                            foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
770
                            {
771
                                if (viewpsn == dr["OID"].ToString())
772
                                    continue;
773

    
774
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).Length == 0)
775
                                    continue;
776

    
777
                                DataRow rows = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).First();
778
                                if(rows != null)
779
                                {
780
                                    lastP1 = viewpsn;
781
                                }
782
                            }
783

    
784
                            if(!string.IsNullOrEmpty(lastP1))
785
                            {
786
                                bool bCheck = false;
787
                                foreach (DataRow dataRow in pathItemRows)
788
                                {
789
                                    if (bCheck)
790
                                        dataRow["EqpGroupTag"] = string.Empty;
791

    
792
                                    if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
793
                                    {
794
                                        bCheck = true;
795
                                        dataRow["EGTConnectedPoint"] = 1;
796
                                    }                       
797
                                }
798
                            }
799
                        }
800
                    }
801
                }
802

    
803
                //psn data 정리
804
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
805
                {
806
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
807
                    string EGTag = string.Empty;
808
                    string HasMLTags = "False";
809

    
810
                    foreach (DataRow dataRow in pathItemRows)
811
                    {
812
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
813
                            EGTag = dataRow.Field<string>("EqpGroupTag");
814

    
815
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
816
                            HasMLTags = "True";
817

    
818
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
819
                            break;
820
                    }
821

    
822
                    pipesystem["EGTag"] = EGTag;
823
                    pipesystem["HasMLTags"] = HasMLTags;
824
                }
825
            }
826
            catch (Exception ex)
827
            {
828
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
829
            }
830
            //}
831
        }
832

    
833
        private void UpdateValveGrouping()
834
        {
835
            try
836
            {
837
                #region ValveGrouping Info
838
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
839
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
840
                foreach (DataRow row in dtValveGroupung.Rows)
841
                {
842
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
843
                    {
844
                        OID = row["OID"].ToString(),
845
                        GroupType = row["GroupType"].ToString(),
846
                        TagIdentifier = row["TagIdentifier"].ToString(),
847
                        AttributeName = row["AttributeName"].ToString(),
848
                        SppidSymbolName = row["SppidSymbolName"].ToString()
849
                    });
850
                }
851
                #endregion
852

    
853

    
854
                int vgTagNum = 1;
855
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
856
                foreach (DataRow drPathitem in tagpathItemRows)
857
                {
858
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
859
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
860
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
861
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
862
                        continue;
863
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
864
                    List<Item> valveGroupingItem = new List<Item>();
865
                    int bCnt = 0;
866

    
867
                    //bool bCheck = false;
868
                    List<DataRow> lstitem = new List<DataRow>();
869
                    foreach (DataRow dr in pathItemRows)
870
                    {
871
                        //if (!string.IsNullOrEmpty(dr["GROUPTAG"].ToString()))
872
                        //    break;
873

    
874
                       if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
875
                        {
876
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
877
                            if (dr["GROUPTAG"].ToString() == "Scope Break")
878
                            {
879
                                dr["GROUPTAG"] = string.Empty;
880
                                break;
881
                            }
882

    
883
                            if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
884
                            {
885
                               // bCheck = true;
886
                                lstitem.Add(dr);
887
                                keyValuePairs.Add(bCnt, lstitem.ToList());
888
                                bCnt++;
889
                                lstitem.Clear();
890
                            }
891
                            else
892
                                lstitem.Add(dr);
893
                        }
894
                        else
895
                            lstitem.Add(dr);
896
                    }
897

    
898
                    if (lstitem.Count > 0)
899
                    {
900
                        keyValuePairs.Add(bCnt, lstitem);
901
                        //bCnt++;
902
                    }
903

    
904
                    if (keyValuePairs.Count() == 0)
905
                        continue;
906

    
907
                    string VGTag = string.Empty;
908
                    if (valveitem.AttributeName == "NoSelection")
909
                    {
910
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
911
                        vgTagNum++;
912
                    }
913
                    else
914
                    {
915
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
916
                    }
917

    
918
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
919
                    {
920
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
921
                        {
922
                            foreach (DataRow dr in keyValuePair.Value)
923
                            {
924
                                dr["GROUPTAG"] = VGTag;
925
                            }
926
                        }
927
                    }
928

    
929
                    if(valveitem.GroupType.Contains("PSV"))
930
                    {
931
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
932
                        foreach (DataRow row in psnRows)
933
                            row["Pocket"] = "Yes";
934
                    }                    
935
                }
936

    
937

    
938
            }
939
            catch (Exception ex)
940
            {
941
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
942
            }
943
            //}
944
        }
945

    
946
        private void SetTopologyData()
947
        {
948
            // 13번 excel
949
            foreach (Group group in groups)
950
            {
951
                LineNumber prevLineNumber = null;
952
                for (int i = 0; i < group.Items.Count; i++)
953
                {
954
                    Item item = group.Items[i];
955
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
956
                    if (lineNumber == null)
957
                    {
958
                        if (prevLineNumber != null)
959
                        {
960
                            if (!prevLineNumber.IsCopy)
961
                            {
962
                                prevLineNumber = prevLineNumber.Copy();
963
                                item.Document.LineNumbers.Add(prevLineNumber);
964
                                item.MissingLineNumber1 = true;
965
                            }
966
                            item.Owner = prevLineNumber.UID;
967
                        }
968
                    }
969
                    else
970
                        prevLineNumber = lineNumber;
971
                }
972

    
973
                prevLineNumber = null;
974
                for (int i = group.Items.Count - 1; i > -1; i--)
975
                {
976
                    Item item = group.Items[i];
977
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
978
                    if (lineNumber == null)
979
                    {
980
                        if (prevLineNumber != null)
981
                        {
982
                            if (!prevLineNumber.IsCopy)
983
                            {
984
                                prevLineNumber = prevLineNumber.Copy();
985
                                item.Document.LineNumbers.Add(prevLineNumber);
986
                                item.MissingLineNumber1 = true;
987
                            }
988

    
989
                            item.Owner = prevLineNumber.UID;
990
                        }
991
                    }
992
                    else
993
                        prevLineNumber = lineNumber;
994
                }
995

    
996
                if (prevLineNumber == null)
997
                {
998
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
999
                    Random random = new Random();
1000
                    int index = random.Next(lineNumbers.Count - 1);
1001

    
1002
                    // Copy
1003
                    LineNumber cLineNumber = lineNumbers[index].Copy();
1004
                    group.Document.LineNumbers.Add(cLineNumber);
1005

    
1006
                    foreach (Item item in group.Items)
1007
                    {
1008
                        item.Owner = cLineNumber.UID;
1009
                        item.MissingLineNumber2 = true;
1010
                    }
1011
                }
1012
            }
1013

    
1014
            foreach (Document document in Documents)
1015
            {
1016
                foreach (Item item in document.Items)
1017
                {
1018
                    item.TopologyData = string.Empty;
1019
                    item.PSNPipeLineID = string.Empty;
1020
                    List<string> pipeLineID = new List<string>();
1021
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1022
                    if (lineNumber != null)
1023
                    {
1024
                        item.LineNumber = lineNumber;
1025

    
1026
                        foreach (DataRow row in topologyRuleDT.Rows)
1027
                        {
1028
                            string uid = row["UID"].ToString();
1029
                            //if (uid == "-")
1030
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1031
                            if (uid != "-")
1032
                            {
1033
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1034

    
1035
                                Attribute attribute = lineNumber.Attributes.Find(x => x.Name == uid);
1036
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1037
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1038
                            }
1039
                        }
1040

    
1041
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1042
                        {
1043
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1044
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1045
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1046
                                                                 //else
1047
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1048
                        }
1049

    
1050
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1051
                        item.TopologyData = string.Join("-", pipeLineID);
1052

    
1053
                    }
1054
                    else
1055
                    {
1056
                        item.TopologyData = "Empty LineNumber";
1057
                        item.LineNumber = new LineNumber();
1058
                    }
1059
                }
1060
            }
1061

    
1062
            int emptyIndex = 1;
1063
            foreach (Group group in groups)
1064
            {
1065
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1066
                if (groupItems.Count > 0)
1067
                {
1068
                    foreach (var item in groupItems)
1069
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1070
                    emptyIndex++;
1071
                }
1072
            }
1073

    
1074
        }
1075

    
1076
        private void ConnectByOPC()
1077
        {
1078
            try
1079
            {
1080
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1081
                {
1082
                    Item opcItem = group.Items.Last();
1083
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1084
                    if (fromRows.Length.Equals(1))
1085
                    {
1086
                        DataRow opcRow = fromRows.First();
1087
                        string toDrawing = opcRow["ToDrawing"].ToString();
1088
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
1089

    
1090
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1091
                        if (toDocument != null)
1092
                        {
1093
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1094
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1095
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1096
                            if (toRows.Length > 1)
1097
                            {
1098
                                //throw new Exception("OPC error(multi connect)");
1099
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1100
                                return;
1101
                            }
1102
                            group.EndGroup = toGroup;
1103
                            toGroup.StartGroup = group;
1104
                        }
1105
                    }
1106
                }
1107
            }
1108
            catch (Exception ex)
1109
            {
1110
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1111
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1112
            }
1113
        }
1114

    
1115
        private void SetPSNItem()
1116
        {
1117
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1118
            foreach (Group group in groups)
1119
                groupDic.Add(group, Guid.NewGuid().ToString());
1120

    
1121
            foreach (Group group in groups)
1122
            {
1123
                string groupKey = groupDic[group];
1124
                if (group.StartGroup != null)
1125
                {
1126
                    string otherKey = groupDic[group.StartGroup];
1127
                    ChangeGroupID(otherKey, groupKey);
1128
                }
1129
            }
1130

    
1131
            // PSN 정리
1132
            foreach (var item in groupDic)
1133
            {
1134
                Group group = item.Key;
1135
                string uid = item.Value;
1136
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1137
                if (PSNItem == null)
1138
                {
1139
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1140
                    PSNItems.Add(PSNItem);
1141
                }
1142
                PSNItem.Groups.Add(group);
1143
                foreach (Item groupItem in group.Items)
1144
                    groupItem.PSNItem = PSNItem;
1145
            }
1146

    
1147
            // Sort PSN
1148
            foreach (PSNItem PSNItem in PSNItems)
1149
            {
1150
                List<Group> _groups = new List<Group>();
1151

    
1152
                Stack<Group> stacks = new Stack<Group>();
1153
                stacks.Push(PSNItem.Groups.First());
1154
                while (stacks.Count > 0)
1155
                {
1156
                    Group stack = stacks.Pop();
1157
                    if (_groups.Contains(stack))
1158
                        continue;
1159

    
1160
                    if (_groups.Count == 0)
1161
                        _groups.Add(stack);
1162
                    else
1163
                    {
1164
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1165
                        {
1166
                            int index = _groups.IndexOf(stack.StartGroup);
1167
                            _groups.Insert(index + 1, stack);
1168
                        }
1169
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1170
                        {
1171
                            int index = _groups.IndexOf(stack.EndGroup);
1172
                            _groups.Insert(index, stack);
1173
                        }
1174
                    }
1175

    
1176
                    if (stack.StartGroup != null)
1177
                        stacks.Push(stack.StartGroup);
1178
                    if (stack.EndGroup != null)
1179
                        stacks.Push(stack.EndGroup);
1180
                }
1181

    
1182
                PSNItem.Groups.Clear();
1183
                PSNItem.Groups.AddRange(_groups);
1184
            }
1185

    
1186
            void ChangeGroupID(string from, string to)
1187
            {
1188
                if (from.Equals(to))
1189
                    return;
1190

    
1191
                List<Group> changeItems = new List<Group>();
1192
                foreach (var _item in groupDic)
1193
                    if (_item.Value.Equals(from))
1194
                        changeItems.Add(_item.Key);
1195
                foreach (var _item in changeItems)
1196
                    groupDic[_item] = to;
1197
            }
1198
        }
1199

    
1200
        private void SetPSNType()
1201
        {
1202
            foreach (PSNItem PSNItem in PSNItems)
1203
            {
1204
                Group firstGroup = PSNItem.Groups.First();
1205
                Group lastGroup = PSNItem.Groups.Last();
1206

    
1207
                Item firstItem = firstGroup.Items.First();
1208
                Item lastItem = lastGroup.Items.Last();
1209

    
1210
                PSNItem.StartType = GetPSNType(firstItem, true);
1211
                PSNItem.EndType = GetPSNType(lastItem, false);
1212
            }
1213

    
1214
            PSNType GetPSNType(Item item, bool bFirst = true)
1215
            {
1216
                PSNType type = PSNType.None;
1217

    
1218
                if (item.ItemType == ItemType.Line)
1219
                {
1220
                    Group group = groups.Find(x => x.Items.Contains(item));
1221
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1222
                    {
1223
                        Item connItem = item.Relations[0].Item;
1224
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1225
                            type = PSNType.Branch;
1226
                        else if (connItem.ItemType == ItemType.Symbol)
1227
                            type = PSNType.Symbol;
1228
                    }
1229
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1230
                    {
1231
                        Item connItem = item.Relations[1].Item;
1232
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1233
                            type = PSNType.Branch;
1234
                        else if (connItem.ItemType == ItemType.Symbol)
1235
                            type = PSNType.Symbol;
1236
                    }
1237
                }
1238
                else if (item.ItemType == ItemType.Symbol)
1239
                {
1240
                    if (item.SubItemType == SubItemType.Nozzle)
1241
                        type = PSNType.Equipment;
1242
                    else if (item.SubItemType == SubItemType.Header)
1243
                        type = PSNType.Header;
1244
                    else if (item.SubItemType == SubItemType.OPC)
1245
                        type = PSNType.OPC;
1246
                }
1247

    
1248
                return type;
1249
            }
1250
        }
1251

    
1252
        private void SetBranchInfo()
1253
        {
1254
            foreach (Document document in Documents)
1255
            {
1256
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1257
                foreach (Item line in lines)
1258
                {
1259
                    double[] point = line.Relations[0].Point;
1260
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1261
                    connLines.Sort(SortBranchLine);
1262
                    line.BranchItems.AddRange(connLines);
1263

    
1264
                    int SortBranchLine(Item a, Item b)
1265
                    {
1266
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1267
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1268

    
1269
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1270
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1271

    
1272
                        // 내림차순
1273
                        return distanceA.CompareTo(distanceB);
1274
                    }
1275
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1276
                    {
1277
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1278
                    }
1279
                }
1280
            }
1281
        }
1282

    
1283
        private void SetTopology()
1284
        {
1285
            try
1286
            {
1287
                #region 기본 topology 정리
1288
                foreach (PSNItem PSNItem in PSNItems)
1289
                {
1290
                    Topology topology = null;
1291
                    foreach (Group group in PSNItem.Groups)
1292
                    {
1293
                        foreach (Item item in group.Items)
1294
                        {
1295
                            if (string.IsNullOrEmpty(item.TopologyData))
1296
                                topology = null;
1297
                            else
1298
                            {
1299
                                if (topology == null)
1300
                                {
1301
                                    topology = new Topology()
1302
                                    {
1303
                                        ID = item.TopologyData
1304
                                    };
1305
                                    Topologies.Add(topology);
1306

    
1307
                                    if (!PSNItem.Topologies.Contains(topology))
1308
                                        PSNItem.Topologies.Add(topology);
1309
                                }
1310
                                else
1311
                                {
1312
                                    if (topology.ID != item.TopologyData)
1313
                                    {
1314
                                        topology = new Topology()
1315
                                        {
1316
                                            ID = item.TopologyData
1317
                                        };
1318
                                        Topologies.Add(topology);
1319

    
1320
                                        if (!PSNItem.Topologies.Contains(topology))
1321
                                            PSNItem.Topologies.Add(topology);
1322
                                    }
1323
                                }
1324

    
1325
                                item.Topology = topology;
1326
                                topology.Items.Add(item);
1327
                            }
1328
                        }
1329
                    }
1330
                }
1331
                #endregion
1332

    
1333
                #region Type
1334
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1335
                foreach (string id in ids)
1336
                {
1337
                    try
1338
                    {
1339

    
1340

    
1341
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1342

    
1343
                        // Main
1344
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1345
                        foreach (Topology topology in mainTopologies)
1346
                            topology.Type = "M";
1347

    
1348
                        // Branch
1349
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1350
                        foreach (Topology topology in branchToplogies)
1351
                            topology.Type = "B";
1352
                    }
1353
                    catch (Exception ex)
1354
                    {
1355
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1356
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1357
                    }
1358
                }
1359
                #endregion
1360
            }
1361
            catch (Exception ex)
1362
            {
1363
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1364
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1365
            }
1366

    
1367
        }
1368

    
1369
        private void SetTopologyIndex()
1370
        {
1371
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1372
            foreach (string id in ids)
1373
            {
1374
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1375

    
1376
                // Main
1377
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1378
                foreach (Topology topology in mainTopologies)
1379
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1380

    
1381
                // Branch
1382
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1383
                foreach (Topology topology in branchToplogies)
1384
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1385
            }
1386
        }
1387

    
1388
        private void SetPSNBypass()
1389
        {
1390
            foreach (PSNItem PSNItem in PSNItems)
1391
                PSNItem.IsBypass = IsBypass(PSNItem);
1392
        }
1393

    
1394
        private List<Topology> FindMainTopology(List<Topology> data)
1395
        {
1396
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1397
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1398
            //2021.11.17 안쓰네 JY
1399
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1400

    
1401
            List<Topology> main = new List<Topology>();
1402
            main.AddRange(data);
1403
            //
1404
            main = GetNozzleTopology(data);
1405
            if (main.Count == 1)
1406
                return main;
1407
            else
1408
            {
1409
                if (main.Count > 0)
1410
                    main = GetPMCTopology(main);
1411
                else
1412
                    main = GetPMCTopology(data);
1413

    
1414
                if (main.Count == 1)
1415
                    return main;
1416
                else
1417
                {
1418
                    if (main.Count > 0)
1419
                        main = GetDiaTopology(main);
1420
                    else
1421
                        main = GetDiaTopology(data);
1422

    
1423

    
1424
                    if (main.Count == 1)
1425
                        return main;
1426
                    else
1427
                    {
1428
                        if (main.Count > 0)
1429
                            main = GetItemTopology(main);
1430
                        else
1431
                            main = GetItemTopology(data);
1432
                    }
1433
                }
1434
            }
1435

    
1436
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1437
            {
1438
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1439
            }
1440

    
1441
            List<Topology> GetPMCTopology(List<Topology> topologies)
1442
            {
1443
                List<Topology> result = new List<Topology>();
1444
                foreach (DataRow row in PMCDT.Rows)
1445
                {
1446
                    string value = row["CODE"].ToString();
1447
                    foreach (Topology topology in topologies)
1448
                    {
1449
                        foreach (Item item in topology.Items)
1450
                        {
1451
                            if (item.LineNumber == null)
1452
                                continue;
1453
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1454
                            if (attribute != null && value == attribute.Value)
1455
                            {
1456
                                result.Add(topology);
1457
                                break;
1458
                            }
1459
                        }
1460
                    }
1461

    
1462
                    if (result.Count > 0)
1463
                        break;
1464
                }
1465

    
1466
                return result;
1467
            }
1468

    
1469
            List<Topology> GetDiaTopology(List<Topology> topologies)
1470
            {
1471
                List<Topology> result = new List<Topology>();
1472
                foreach (DataRow row in nominalDiameterDT.Rows)
1473
                {
1474
                    string inchValue = row["InchStr"].ToString();
1475
                    string metricValue = row["MetricStr"].ToString();
1476
                    foreach (Topology topology in topologies)
1477
                    {
1478
                        foreach (Item item in topology.Items)
1479
                        {
1480
                            if (item.LineNumber == null)
1481
                                continue;
1482
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1483
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1484
                            {
1485
                                result.Add(topology);
1486
                                break;
1487
                            }
1488
                        }
1489
                    }
1490

    
1491
                    if (result.Count > 0)
1492
                        break;
1493
                }
1494

    
1495
                return result;
1496
            }
1497

    
1498
            List<Topology> GetItemTopology(List<Topology> topologies)
1499
            {
1500
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1501
            }
1502

    
1503
            return main;
1504
        }
1505

    
1506
        private DataTable GetOPCInfo()
1507
        {
1508
            DataTable opc = DB.SelectOPCRelations();
1509
            DataTable drawing = DB.AllDrawings();
1510

    
1511
            DataTable dt = new DataTable();
1512
            dt.Columns.Add("FromDrawing", typeof(string));
1513
            dt.Columns.Add("FromDrawingUID", typeof(string));
1514
            dt.Columns.Add("FromOPCUID", typeof(string));
1515
            dt.Columns.Add("ToDrawing", typeof(string));
1516
            dt.Columns.Add("ToDrawingUID", typeof(string));
1517
            dt.Columns.Add("ToOPCUID", typeof(string));
1518
            foreach (DataRow row in opc.Rows)
1519
            {
1520
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1521
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1522
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1523
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1524
                if (!string.IsNullOrEmpty(toOPCUID))
1525
                {
1526
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
1527
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
1528
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
1529
                    {
1530
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
1531
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
1532

    
1533
                        DataRow newRow = dt.NewRow();
1534
                        newRow["FromDrawing"] = fromDrawingName;
1535
                        newRow["FromDrawingUID"] = fromDrawingUID;
1536
                        newRow["FromOPCUID"] = fromOPCUID;
1537
                        newRow["ToDrawing"] = toDrawingName;
1538
                        newRow["ToDrawingUID"] = toDrawingUID;
1539
                        newRow["ToOPCUID"] = toOPCUID;
1540

    
1541
                        dt.Rows.Add(newRow);
1542
                    }
1543
                }
1544
            }
1545

    
1546
            return dt;
1547
        }
1548

    
1549
        private DataTable GetTopologyRule()
1550
        {
1551
            DataTable dt = DB.SelectTopologyRule();
1552

    
1553
            return dt;
1554
        }
1555

    
1556
        private bool IsConnected(Item item1, Item item2)
1557
        {
1558
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
1559
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
1560
                return true;
1561
            else
1562
                return false;
1563
        }
1564

    
1565
        private void SaveNozzleAndEquipment()
1566
        {
1567
            List<Item> nozzles = new List<Item>();
1568
            List<Equipment> equipments = new List<Equipment>();
1569
            foreach (Document document in Documents)
1570
            {
1571
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1572
                equipments.AddRange(document.Equipments);
1573
            }
1574

    
1575

    
1576
            DataTable nozzleDT = new DataTable();
1577
            nozzleDT.Columns.Add("OID", typeof(string));
1578
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1579
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1580
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1581
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1582
            nozzleDT.Columns.Add("FLUID", typeof(string));
1583
            nozzleDT.Columns.Add("NPD", typeof(string));
1584
            nozzleDT.Columns.Add("PMC", typeof(string));
1585
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1586
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1587

    
1588
            foreach (Item item in nozzles)
1589
            {
1590
                DataRow row = nozzleDT.NewRow();
1591
                row["OID"] = item.UID;
1592

    
1593
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
1594
                if (relation != null)
1595
                {
1596
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
1597
                    equipment.Nozzles.Add(item);
1598
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
1599
                    row["Equipment_OID"] = equipment.UID;
1600
                    item.Equipment = equipment;
1601
                }
1602
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
1603
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
1604
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
1605
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
1606
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1607
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
1608
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1609
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
1610

    
1611
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1612
                if (angle >= Math.PI * 2)
1613
                    angle = angle - Math.PI * 2;
1614
                row["ROTATION"] = angle.ToString();
1615

    
1616
                if (item.Topology.Items.First().Equals(item))
1617
                    row["FlowDirection"] = "Outlet";
1618
                else if (item.Topology.Items.Last().Equals(item))
1619
                    row["FlowDirection"] = "Inlet";
1620
                else
1621
                    row["FlowDirection"] = string.Empty;
1622

    
1623
                nozzleDT.Rows.Add(row);
1624
            }
1625

    
1626
            DataTable equipDT = new DataTable();
1627
            equipDT.Columns.Add("OID", typeof(string));
1628
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1629
            equipDT.Columns.Add("XCOORDS", typeof(string));
1630
            equipDT.Columns.Add("YCOORDS", typeof(string));
1631

    
1632
            foreach (Equipment equipment in equipments)
1633
            {
1634
                DataRow row = equipDT.NewRow();
1635
                row["OID"] = equipment.UID;
1636
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
1637
                {
1638
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
1639
                    if (attribute != null)
1640
                        equipment.ItemTag = attribute.Value;
1641
                }
1642
                else
1643
                    equipment.ItemTag = equipment.Name;
1644

    
1645
                row["ITEMTAG"] = equipment.ItemTag;
1646
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
1647
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
1648

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

    
1652
                equipDT.Rows.Add(row);
1653
            }
1654

    
1655
            Equipment = equipDT;
1656
            Nozzle = nozzleDT;
1657
        }
1658

    
1659
        private void SavePSNData()
1660
        {
1661
            try
1662
            {
1663
                DataTable pathItemsDT = new DataTable();
1664
                pathItemsDT.Columns.Add("OID", typeof(string));
1665
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
1666
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
1667
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
1668
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
1669
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
1670
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
1671
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
1672
                pathItemsDT.Columns.Add("Class", typeof(string));
1673
                pathItemsDT.Columns.Add("SubClass", typeof(string));
1674
                pathItemsDT.Columns.Add("TYPE", typeof(string));
1675
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
1676
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
1677
                pathItemsDT.Columns.Add("NPD", typeof(string));
1678
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
1679
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
1680
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
1681
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
1682
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
1683
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
1684
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
1685
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
1686

    
1687
                DataTable sequenceDataDT = new DataTable();
1688
                sequenceDataDT.Columns.Add("OID", typeof(string));
1689
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
1690
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
1691
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1692

    
1693
                DataTable pipeSystemNetworkDT = new DataTable();
1694
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
1695
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
1696
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
1697
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
1698
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
1699
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
1700
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1701
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
1702
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
1703
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
1704
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
1705
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
1706
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
1707
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
1708
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
1709
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
1710
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
1711
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
1712
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
1713

    
1714
                DataTable topologySetDT = new DataTable();
1715
                topologySetDT.Columns.Add("OID", typeof(string));
1716
                topologySetDT.Columns.Add("Type", typeof(string));
1717
                topologySetDT.Columns.Add("SubType", typeof(string));
1718
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
1719
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
1720
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
1721
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
1722

    
1723
                DataTable pipelineDT = new DataTable();
1724
                pipelineDT.Columns.Add("OID", typeof(string));
1725
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
1726
                pipelineDT.Columns.Add("FLUID", typeof(string));
1727
                pipelineDT.Columns.Add("PMC", typeof(string));
1728
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
1729
                pipelineDT.Columns.Add("INSULATION", typeof(string));
1730
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
1731
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
1732
                pipelineDT.Columns.Add("Unit", typeof(string));
1733

    
1734
                DataTable pipesystemDT = new DataTable();
1735
                pipesystemDT.Columns.Add("OID", typeof(string));
1736
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
1737
                pipesystemDT.Columns.Add("FLUID", typeof(string));
1738
                pipesystemDT.Columns.Add("PMC", typeof(string));
1739
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
1740
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
1741

    
1742
                // Set Vent/Drain Info
1743
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1744
                DataTable dt = DB.SelectVentDrainSetting();
1745
                foreach (DataRow row in dt.Rows)
1746
                {
1747
                    string groupID = row["GROUP_ID"].ToString();
1748
                    string desc = row["DESCRIPTION"].ToString();
1749
                    int index = Convert.ToInt32(row["INDEX"]);
1750
                    string name = row["NAME"].ToString();
1751

    
1752
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1753
                    if (ventDrainInfo == null)
1754
                    {
1755
                        ventDrainInfo = new VentDrainInfo(groupID);
1756
                        ventDrainInfo.Description = desc;
1757
                        VentDrainInfos.Add(ventDrainInfo);
1758
                    }
1759

    
1760
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1761
                    {
1762
                        Index = index,
1763
                        Name = name
1764
                    });
1765
                }
1766
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1767
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
1768

    
1769
                #region Keyword Info
1770
                KeywordInfo KeywordInfos = new KeywordInfo();
1771
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1772
                foreach (DataRow row in dtKeyword.Rows)
1773
                {
1774
                    int index = Convert.ToInt32(row["INDEX"]);
1775
                    string name = row["NAME"].ToString();
1776
                    string keyword = row["KEYWORD"].ToString();
1777

    
1778
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1779
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1780
                    {
1781
                        Index = index,
1782
                        Name = name,
1783
                        Keyword = keyword
1784
                    });
1785
                }
1786
                #endregion
1787

    
1788
                #region ValveGrouping Info
1789
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1790
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1791
                foreach (DataRow row in dtValveGroupung.Rows)
1792
                {
1793
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1794
                    {
1795
                        OID = row["OID"].ToString(),
1796
                        GroupType = row["GroupType"].ToString(),
1797
                        TagIdentifier = row["TagIdentifier"].ToString(),
1798
                        AttributeName = row["AttributeName"].ToString(),
1799
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1800
                    });
1801
                }
1802
                #endregion
1803

    
1804
                #region EquipmentNoPocket Info
1805
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
1806
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
1807
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
1808
                {
1809
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
1810
                    {
1811
                        Index = Convert.ToInt32(row["INDEX"]),
1812
                        Type = row["TYPE"].ToString(),
1813
                        Name = row["NAME"].ToString()
1814
                    });
1815
                }
1816
                #endregion
1817

    
1818
                #region EquipmentAirFinCooler Info
1819
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
1820
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
1821
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
1822
                {
1823
                    //pump type도 마찬가지?
1824
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
1825
                    {
1826
                        Type = row["Type"].ToString(),
1827
                        Name = row["Name"].ToString()
1828
                    });
1829
                }
1830
                #endregion
1831

    
1832
                // key = 미입력 branch
1833
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1834
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1835
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
1836
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
1837
                foreach (PSNItem PSNItem in PSNItems)
1838
                {
1839
                    try
1840
                    {
1841
                        int psnOrder = 0;
1842
                        int index = 0;
1843
                        bool bPSNStart = true;
1844
                        string sPSNData = string.Empty;
1845
                        bool bVentDrain = false;
1846

    
1847
                        List<Group> Groups = PSNItem.Groups;
1848
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
1849
                        List<Item> valveGroupingItem = new List<Item>();
1850

    
1851
                        //VentDrain 검사
1852
                        if (PSNItem.Groups.Count.Equals(1))
1853
                        {
1854
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1855
                            for (int g = 0; g < Groups.Count; g++)
1856
                            {
1857
                                Group group = Groups[g];
1858
                                for (int i = 0; i < group.Items.Count; i++)
1859
                                {
1860
                                    Item item = group.Items[i];
1861
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1862
                                    {
1863
                                        if (endInfos.Contains(ventDrainInfo))
1864
                                            continue;
1865

    
1866
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1867
                                        {
1868
                                            endInfos.Add(ventDrainInfo);
1869
                                            continue;
1870
                                        }
1871

    
1872
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1873
                                        {
1874
                                            bVentDrain = true;
1875
                                            break;
1876
                                        }
1877
                                    }
1878

    
1879
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1880
                                        break;
1881
                                }
1882

    
1883
                                if (!bVentDrain)
1884
                                {
1885
                                    endInfos = new List<VentDrainInfo>();
1886
                                    for (int i = 0; i < group.Items.Count; i++)
1887
                                    {
1888
                                        Item item = group.Items[group.Items.Count - i - 1];
1889
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1890
                                        {
1891
                                            if (endInfos.Contains(ventDrainInfo))
1892
                                                continue;
1893

    
1894
                                            if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1895
                                            {
1896
                                                endInfos.Add(ventDrainInfo);
1897
                                                continue;
1898
                                            }
1899

    
1900
                                            if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1901
                                            {
1902
                                                bVentDrain = true;
1903
                                                break;
1904
                                            }
1905
                                        }
1906

    
1907
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1908
                                            break;
1909
                                    }
1910
                                }
1911
                            }
1912
                        }
1913

    
1914
                        try
1915
                        {
1916
                            foreach (Group group in PSNItem.Groups)
1917
                            {
1918
                                foreach (Item item in group.Items)
1919
                                {
1920
                                    string VgTag = string.Empty;
1921
                                    
1922
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
1923
                                    {
1924
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
1925
                                        string value = string.Empty;
1926

    
1927
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection")
1928
                                            value = "NoSelection";
1929
                                        else
1930
                                            value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
1931

    
1932
                                        if (valveitem.GroupType == "Scope Break")
1933
                                            VgTag = "Scope Break";
1934
                                        else
1935
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
1936

    
1937
                                    }
1938

    
1939
                                    string PathitemUID = string.Empty;
1940
                                    if (item.BranchItems.Count == 0)
1941
                                    {
1942
                                        PathitemUID = item.UID;
1943
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1944
                                        CreateSequenceDataDataRow(PathitemUID);
1945
                                        index++;
1946
                                    }
1947
                                    else
1948
                                    {
1949
                                        PathitemUID = item.UID + "_L1";
1950
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1951
                                        CreateSequenceDataDataRow(PathitemUID);
1952
                                        index++;
1953
                                        for (int i = 0; i < item.BranchItems.Count; i++)
1954
                                        {
1955
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1956
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1957
                                            index++;
1958

    
1959
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1960
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1961
                                            index++;
1962

    
1963
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1964
                                                startBranchDic.Add(item.BranchItems[i], item);
1965
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1966
                                                endBranchDic.Add(item.BranchItems[i], item);
1967
                                        }
1968
                                    }
1969

    
1970
                                    if (bPSNStart)
1971
                                    {
1972
                                        CreatePipeSystemNetworkDataRow();
1973
                                        sPSNData = item.TopologyData;
1974
                                        psnOrder++;
1975
                                        bPSNStart = false;
1976
                                    }
1977
                                    else
1978
                                    {
1979
                                        if (item.TopologyData != sPSNData)
1980
                                        {
1981
                                            CreatePipeSystemNetworkDataRow();
1982
                                            sPSNData = item.TopologyData;
1983
                                            psnOrder++;
1984
                                        }
1985
                                    }
1986

    
1987
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
1988
                                    {
1989
                                        DataRow newRow = pathItemsDT.NewRow();
1990

    
1991
                                        if (itemType == "Nozzles")
1992
                                        {
1993
                                            newRow["Equipment_OID"] = item.Equipment.UID;
1994
                                        }
1995

    
1996
                                        newRow["OID"] = itemOID;
1997
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1998
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
1999
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2000
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2001
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
2002
                                        newRow["ITEMTAG"] = GetItemTag(item);
2003
                                        newRow["Class"] = GetClass(item, itemOID);
2004
                                        string subClass = GetSubClass(item, itemOID);
2005
                                        newRow["SubClass"] = subClass;
2006

    
2007
                                        if (item.ItemType == ItemType.Symbol)
2008
                                            newRow["TYPE"] = item.ID2DBName;
2009
                                        else if (item.ItemType == ItemType.Line)
2010
                                            newRow["TYPE"] = item.ID2DBType;
2011
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2012

    
2013
                                        // NPD
2014
                                        if (item.LineNumber != null)
2015
                                        {
2016
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2017
                                            if (attribute != null)
2018
                                                newRow["NPD"] = attribute.Value;
2019
                                        }
2020
                                        else
2021
                                            newRow["NPD"] = null;
2022

    
2023
                                        newRow["GROUPTAG"] = GROUPTAG;
2024
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2025
                                        if (branchItem == null)
2026
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2027
                                        else
2028
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2029

    
2030
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2031
                                        newRow["EGTConnectedPoint"] = 0;
2032
                                        pathItemsDT.Rows.Add(newRow);
2033
                                    }
2034

    
2035

    
2036
                                    void CreateSequenceDataDataRow(string itemOID)
2037
                                    {
2038
                                        DataRow newRow = sequenceDataDT.NewRow();
2039
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2040
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2041
                                        newRow["PathItem_OID"] = itemOID;
2042
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2043

    
2044
                                        sequenceDataDT.Rows.Add(newRow);
2045
                                    }
2046

    
2047
                                    void CreatePipeSystemNetworkDataRow()
2048
                                    {
2049
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2050
                                        string FluidCode = string.Empty;
2051
                                        if (lineNumber != null)
2052
                                        {
2053
                                            List<Attribute> att = lineNumber.Attributes;
2054
                                            if (att != null)
2055
                                            {
2056
                                                List<string> oid = new List<string>();
2057
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2058
                                                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;
2059
                                                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;
2060
                                                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;
2061
                                                //InsulationPurpose
2062
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2063
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2064

    
2065
                                                string PipeSystem_OID = string.Join("-", oid);
2066

    
2067
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2068
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2069

    
2070
                                                string OID = string.Join("-", oid);
2071
                                                string FluidCodeGL = string.Empty;
2072
                                                string PMCGL = string.Empty;
2073

    
2074

    
2075
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2076
                                                {
2077
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2078
                                                    newPipelineRow["OID"] = OID;
2079
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2080
                                                    newPipelineRow["FLUID"] = FluidCode;
2081
                                                    newPipelineRow["PMC"] = PMC;
2082
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2083
                                                    newPipelineRow["INSULATION"] = INSULATION;
2084
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2085
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2086
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2087
                                                    pipelineDT.Rows.Add(newPipelineRow);
2088
                                                }
2089

    
2090
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2091
                                                {
2092
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2093
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2094
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2095
                                                    newPipesystemRow["FLUID"] = FluidCode;
2096
                                                    newPipesystemRow["PMC"] = PMC;
2097
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2098
                                                    string GroundLevel = string.Empty;
2099
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2100
                                                    {
2101
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2102
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2103
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2104
                                                            GroundLevel = "AG";
2105
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2106
                                                            GroundLevel = "UG";
2107
                                                        else
2108
                                                            GroundLevel = "AG_UG";
2109
                                                    }
2110
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2111

    
2112
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2113
                                                }
2114
                                            }
2115
                                        }
2116

    
2117
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2118
                                        newRow["OID"] = PSNItem.PSN_OID();
2119

    
2120
                                        newRow["OrderNumber"] = psnOrder;
2121
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2122
                                        PSNItem.KeywordInfos = KeywordInfos;
2123
                                        PSNItem.Nozzle = Nozzle;
2124

    
2125
                                        string FromType = string.Empty;
2126
                                        Item From_item = new Item();
2127

    
2128
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
2129
                                        string status = string.Empty;
2130
                                        if (psnOrder == 0)
2131
                                        {
2132
                                            status = PSNItem.Status;
2133
                                        }
2134

    
2135
                                        if (PSNItem.IsKeyword)
2136
                                        {
2137
                                            PSNItem.StartType = PSNType.Equipment;
2138
                                        }
2139
                                        string ToType = string.Empty;
2140
                                        Item To_item = new Item();
2141
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
2142
                                        if (PSNItem.IsKeyword)
2143
                                        {
2144
                                            PSNItem.EndType = PSNType.Equipment;
2145
                                        }
2146

    
2147
                                        //if (Groups.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
2148
                                        //{
2149
                                        if (!string.IsNullOrEmpty(PSNItem.Status))
2150
                                            status += PSNItem.Status;
2151
                                        //}
2152

    
2153
                                        newRow["FROM_DATA"] = FROM_DATA;
2154
                                        newRow["TO_DATA"] = TO_DATA;
2155
                                        newRow["Type"] = PSNItem.GetPSNType();
2156

    
2157
                                        if (psnOrder > 0)
2158
                                        {
2159
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2160
                                            if (!string.IsNullOrEmpty(PSNItem.Status))
2161
                                            {//status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2162
                                                if (dr["Status"].ToString().Contains(PSNItem.Status))
2163
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
2164
                                                else if (dr["Status"].ToString().Contains(PSNItem.Status.Remove(0, 2)))
2165
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
2166

    
2167
                                            }
2168

    
2169
                                            if (dr != null)
2170
                                            {
2171
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2172
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2173
                                                newRow["Type"] = dr.Field<string>("Type");
2174
                                            }
2175
                                        }
2176

    
2177
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2178
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
2179
                                        {
2180
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
2181
                                            int cnt = matches.Count;
2182
                                            if (cnt > 1)
2183
                                                status.Replace(", Missing LineNumber_1", string.Empty);
2184
                                        }
2185
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2186
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
2187

    
2188

    
2189
                                        newRow["IsValid"] = PSNItem.IsValid;
2190
                                        newRow["Status"] = status;
2191
                                        newRow["PBS"] = PSNItem.GetPBSData();
2192

    
2193
                                        List<string> drawingNames = new List<string>();
2194
                                        foreach (Group _group in PSNItem.Groups)
2195
                                        {
2196
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2197
                                            {
2198
                                                if (drawingNames.Count == 0)
2199
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2200
                                                else
2201
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2202
                                                drawingNames.Add(_group.Document.DrawingName);
2203
                                            }
2204
                                        }
2205

    
2206
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2207
                                        if (bVentDrain)
2208
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2209
                                        else
2210
                                            newRow["IncludingVirtualData"] = "No";
2211
                                        //    return;
2212
                                        //newRow["IncludingVirtualData"] = "No";
2213
                                        newRow["PSNAccuracy"] = "100";
2214

    
2215
                                        string Pocket = "No";
2216
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2217
                                        if (Condition.Equals("Flare"))
2218
                                            Pocket = "Yes";
2219

    
2220
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment) 
2221
                                        {
2222
                                          //  string itemName = From_item.Name;
2223
                                            Equipment Equipment = From_item.Equipment;
2224
                                      
2225
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2226
                                          
2227

    
2228
                                            if (nopocket != null)
2229
                                            {
2230
                                                DataRow bNozzle = null;
2231
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2232
                                                {
2233
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2234
                                                    if (drNozzle != null)
2235
                                                    {
2236
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2237
                                                        {
2238
                                                            bNozzle = drNozzle;
2239
                                                        }
2240

    
2241
                                                        if (bNozzle == null)
2242
                                                        {
2243
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2244

    
2245
                                                            if (drNozzle != null)
2246
                                                            {
2247
                                                                bNozzle = drNozzle;
2248
                                                                foreach (DataRow it in nozzleRows)
2249
                                                                {
2250
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2251
                                                                    {
2252
                                                                        bNozzle = null;
2253
                                                                        break;
2254
                                                                    }
2255
                                                                }
2256
                                                            }
2257
                                                        }
2258
                                                    }
2259

    
2260
                                                    if (bNozzle != null)
2261
                                                        Pocket = "Yes";
2262
                                                }
2263
                                                else
2264
                                                    Pocket = "Yes";
2265
                                            }
2266
                                        }
2267
                                        
2268
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment) //To는 전체
2269
                                        {
2270
                                           // string itemName = To_item.Name;
2271
                                            Equipment Equipment = To_item.Equipment;
2272
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2273
                                            if (nopocket != null)
2274
                                            {
2275
                                                DataRow bNozzle = null;
2276
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2277
                                                {
2278
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2279
                                                    if(drNozzle != null)
2280
                                                    {
2281
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2282
                                                        {
2283
                                                            bNozzle = drNozzle;
2284
                                                        }
2285

    
2286
                                                        if (bNozzle == null)
2287
                                                        {
2288
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2289

    
2290
                                                            if (drNozzle != null)
2291
                                                            {
2292
                                                                bNozzle = drNozzle;
2293
                                                                foreach (DataRow it in nozzleRows)
2294
                                                                {
2295
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2296
                                                                    {
2297
                                                                        bNozzle = null;
2298
                                                                        break;
2299
                                                                    }
2300
                                                                }
2301
                                                            }
2302
                                                        }
2303
                                                    }                                                   
2304

    
2305
                                                    if (bNozzle != null)
2306
                                                        Pocket = "Yes";
2307
                                                }
2308
                                                else
2309
                                                    Pocket = "Yes";
2310
                                            }
2311
                                        }
2312
                                        
2313
                                        newRow["Pocket"] = Pocket;
2314
                                        string AFC = "P2";
2315
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2316
                                        {
2317
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2318
                                                AFC = "P1";
2319
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2320
                                                newRow["PUMP"] = "PUMP";
2321
                                        }
2322

    
2323
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2324
                                        {
2325
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2326
                                                AFC = "P1";
2327
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2328
                                                newRow["PUMP"] = "PUMP";
2329
                                        }
2330

    
2331
                                        newRow["AFC"] = AFC;
2332

    
2333
                                        newRow["EGTag"] = string.Empty;
2334
                                        newRow["HasMLTags"] = "False";
2335
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2336
                                    }
2337
                                }
2338

    
2339
                            }
2340
                        
2341

    
2342
                        }
2343
                        catch (Exception ex)
2344
                        {
2345
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2346
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2347
                        }
2348

    
2349
                        //TopologySet 관련
2350
                        foreach (Topology topology in PSNItem.Topologies)
2351
                        {
2352
                            DataRow newRow = topologySetDT.NewRow();
2353
                            newRow["OID"] = topology.FullName;
2354
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
2355
                            if (bVentDrain)
2356
                                newRow["SubType"] = "Vent_Drain";
2357
                            else
2358
                                newRow["SubType"] = null;
2359
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
2360
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
2361
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
2362
                            newRow["TailItemSPID"] = topology.Items.First().UID;
2363
                            topologySetDT.Rows.Add(newRow);
2364
                        }
2365

    
2366
                    }
2367
                    catch (Exception ee)
2368
                    {
2369

    
2370
                    }
2371
                }
2372

    
2373

    
2374
                foreach (var item in startBranchDic)
2375
                {
2376
                    string uid = item.Key.UID;
2377
                    string topologyName = item.Value.Topology.FullName;
2378
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2379

    
2380
                    if (rows.Length == 1)
2381
                    {
2382
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2383
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2384
                    }
2385
                    else if (rows.Length > 1)
2386
                    {
2387
                        DataRow targetRow = null;
2388
                        int index = int.MaxValue;
2389
                        foreach (DataRow row in rows)
2390
                        {
2391
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2392
                            if (split.StartsWith("L"))
2393
                            {
2394
                                int num = Convert.ToInt32(split.Remove(0, 1));
2395
                                if (index > num)
2396
                                {
2397
                                    index = num;
2398
                                    targetRow = row;
2399
                                }
2400
                            }
2401
                        }
2402

    
2403
                        if (targetRow != null)
2404
                        {
2405
                            targetRow["BranchTopologySet_OID"] = topologyName;
2406
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2407
                        }
2408
                    }
2409
                }
2410

    
2411
                foreach (var item in endBranchDic)
2412
                {
2413
                    string uid = item.Key.UID;
2414
                    string topologyName = item.Value.Topology.FullName;
2415
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2416
                    if (rows.Length == 1)
2417
                    {
2418
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2419
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2420
                    }
2421
                    else if (rows.Length > 1)
2422
                    {
2423
                        DataRow targetRow = null;
2424
                        int index = int.MinValue;
2425
                        foreach (DataRow row in rows)
2426
                        {
2427
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2428
                            if (split.StartsWith("L"))
2429
                            {
2430
                                int num = Convert.ToInt32(split.Remove(0, 1));
2431
                                if (index < num)
2432
                                {
2433
                                    index = num;
2434
                                    targetRow = row;
2435
                                }
2436
                            }
2437
                        }
2438

    
2439
                        if (targetRow != null)
2440
                        {
2441
                            targetRow["BranchTopologySet_OID"] = topologyName;
2442
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2443
                        }
2444
                    }
2445
                }
2446

    
2447
                PathItems = pathItemsDT;
2448
                SequenceData = sequenceDataDT;
2449
                PipeSystemNetwork = pipeSystemNetworkDT;
2450
                TopologySet = topologySetDT;
2451
                PipeLine = pipelineDT;
2452
                PipeSystem = pipesystemDT;
2453
            }
2454
            catch (Exception ex)
2455
            {
2456
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2457
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2458
            }
2459
        }
2460

    
2461
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2462
        {
2463
            foreach (double lacc in lstAcc)
2464
            {
2465
                acc *= lacc;
2466
            }
2467
            return acc;
2468
        }
2469

    
2470
        private void UpdateSubType()
2471
        {
2472
            try
2473
            {
2474
                foreach (PSNItem PSNItem in PSNItems)
2475
                {
2476
                    if (PSNItem.IsBypass)
2477
                    {
2478
                        foreach (Topology topology in PSNItem.Topologies)
2479
                        {
2480
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2481
                            if (rows.Length.Equals(1))
2482
                                rows.First()["SubType"] = "Bypass";
2483
                        }
2484
                    }
2485

    
2486
                    if (PSNItem.StartType == PSNType.Header)
2487
                    {
2488
                        Topology topology = PSNItem.Topologies.First();
2489
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2490
                        if (rows.Length.Equals(1))
2491
                            rows.First()["SubType"] = "Header";
2492
                    }
2493
                    else if (PSNItem.EndType == PSNType.Header)
2494
                    {
2495
                        Topology topology = PSNItem.Topologies.Last();
2496
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2497
                        if (rows.Length.Equals(1))
2498
                            rows.First()["SubType"] = "Header";
2499
                    }
2500
                }
2501

    
2502

    
2503
                foreach (Topology topology in Topologies)
2504
                {
2505
                    try
2506
                    {
2507
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2508

    
2509
                        if (rows.Count() > 0)
2510
                        {
2511
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2512
                            {
2513
                                if (topology.Items == null)
2514
                                    continue;
2515

    
2516
                                Item firstItem = topology.Items.First();
2517
                                Item lastItem = topology.Items.Last();
2518

    
2519
                                List<Relation> relations = new List<Relation>();
2520

    
2521
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2522
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2523

    
2524
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2525
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2526

    
2527
                                if (relations.Count > 0)
2528
                                    rows.First()["SubType"] = "OtherSystem";
2529
                            }
2530
                        }
2531
                    }
2532
                    catch (Exception ex)
2533
                    {
2534

    
2535
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2536
                    }
2537
                }
2538

    
2539
                foreach (DataRow row in TopologySet.Rows)
2540
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
2541
                        row["SubType"] = "Normal";
2542
            }
2543
            catch (Exception ex)
2544
            {
2545
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2546
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2547
            }
2548
        }
2549

    
2550
        private bool IsBypass(PSNItem PSNItem)
2551
        {
2552
            bool bResult = false;
2553

    
2554
            if (PSNItem.GetPSNType() == "B2B")
2555
            {
2556
                Group firstGroup = PSNItem.Groups.First();
2557
                Group lastGroup = PSNItem.Groups.Last();
2558
                Item firstItem = firstGroup.Items.First();
2559
                Item lastItem = lastGroup.Items.Last();
2560

    
2561
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
2562
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
2563

    
2564
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
2565
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
2566
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
2567
                    bResult = true;
2568
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
2569
                    bResult = true;
2570
            }
2571

    
2572
            Item GetConnectedItemByPSN(Item item)
2573
            {
2574
                Item result = null;
2575

    
2576
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
2577
                if (relation != null)
2578
                    result = relation.Item;
2579

    
2580

    
2581
                return result;
2582
            }
2583

    
2584
            return bResult;
2585
        }
2586

    
2587
        private void DeleteVentDrain()
2588
        {
2589
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
2590

    
2591
            foreach (DataRow dataRow in ventdrainRows)
2592
            {
2593
                dataRow.Delete();
2594
            }
2595
        }
2596

    
2597
        private void UpdateAccuracy()
2598
        {
2599
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
2600
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
2601
            List<double> lstAcc = null;
2602
            string Status = string.Empty;
2603

    
2604
            foreach (DataRow dataRow in statusRows)
2605
            {
2606
                lstAcc = new List<double>();
2607
                Status = dataRow.Field<string>("Status");
2608
                if (!string.IsNullOrEmpty(Status))
2609
                {
2610
                    string[] arrStatus = Status.Split(',');
2611
                    foreach (string arrstr in arrStatus)
2612
                    {
2613
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
2614
                            lstAcc.Add(0.75);
2615

    
2616
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2617
                            lstAcc.Add(0.7);
2618

    
2619
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2620
                            lstAcc.Add(0.5);
2621

    
2622
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2623
                            lstAcc.Add(0.65);
2624

    
2625
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2626
                            lstAcc.Add(0.6);
2627
                    }
2628
                }
2629

    
2630
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
2631
                if (PSNAccuracy == "100")
2632
                    PSNAccuracy = "1";
2633

    
2634
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
2635
                //if (PSNAccuracy != "100")
2636
                //{
2637
                //    //dataRow["IncludingVirtualData"] = "No";
2638
                dataRow["PSNAccuracy"] = PSNAccuracy;
2639
                //}
2640
            }
2641
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
2642
            foreach (DataRow dr in dt.Rows)
2643
            {
2644
                string oid = dr.Field<string>("OID");
2645
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
2646
                double totalDdr = 0;
2647
                foreach (DataRow ddr in select)
2648
                {
2649
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
2650
                    if (acc == 100) acc = 1;
2651
                    if (totalDdr == 0) totalDdr = acc;
2652
                    else totalDdr *= acc;
2653
                }
2654

    
2655
                totalDdr *= 100;
2656

    
2657
                if (totalDdr != 100)
2658
                {
2659
                    foreach (DataRow ddr in select)
2660
                    {
2661
                        ddr["IncludingVirtualData"] = "Yes";
2662
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2663
                    }
2664
                }
2665
                else
2666
                {
2667
                    foreach (DataRow ddr in select)
2668
                    {
2669
                        ddr["IncludingVirtualData"] = "No";
2670
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2671
                    }
2672
                }
2673
            }
2674

    
2675
        }
2676

    
2677
        private void UpdateKeywordForPSN()
2678
        {
2679
            #region Keyword Info
2680
            KeywordInfo KeywordInfos = new KeywordInfo();
2681
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2682
            foreach (DataRow row in dtKeyword.Rows)
2683
            {
2684
                int index = Convert.ToInt32(row["INDEX"]);
2685
                string name = row["NAME"].ToString();
2686
                string keyword = row["KEYWORD"].ToString();
2687

    
2688
                //KeywordInfo keywordInfo = new KeywordInfo();   
2689
                KeywordInfos.KeywordItems.Add(new KeywordItem()
2690
                {
2691
                    Index = index,
2692
                    Name = name,
2693
                    Keyword = keyword
2694
                });
2695
            }
2696
            #endregion
2697

    
2698
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
2699
            foreach (DataRow dataRow in endofHeaderRows)
2700
            {
2701
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2702

    
2703
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
2704
                {
2705
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2706
                    DataRow dr = pathItemRows.First();
2707
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
2708
                    dr["TYPE"] = "End";
2709
                    dr["ITEMTAG"] = "ENDOFHEADER";
2710
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2711
                }
2712

    
2713
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
2714
                {
2715
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2716
                    DataRow dr = pathItemRows.Last();
2717
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
2718
                    dr["TYPE"] = "End";
2719
                    dr["ITEMTAG"] = "ENDOFHEADER";
2720
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2721
                }
2722
            }
2723

    
2724
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2725
            {
2726
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
2727
                foreach (DataRow dataRow in keywordRows)
2728
                {
2729
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2730

    
2731
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
2732
                    {
2733
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2734

    
2735
                        //
2736
                        //if(.)
2737
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
2738
                        {
2739
                            DataRow dr = pathItemRows.First();
2740
                            //dr["CLASS"] = ""; //Type
2741
                            dr["TYPE"] = "End";
2742
                            dr["ITEMTAG"] = keyitem.Keyword;
2743
                            dr["DESCRIPTION"] = keyitem.Keyword;
2744
                        }
2745

    
2746
                    }
2747

    
2748
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
2749
                    {
2750
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2751

    
2752
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
2753
                        {
2754
                            DataRow dr = pathItemRows.Last();
2755
                            //dr["CLASS"] = ""; //Type
2756
                            dr["TYPE"] = "End";
2757
                            dr["ITEMTAG"] = keyitem.Keyword;
2758
                            dr["DESCRIPTION"] = keyitem.Keyword;
2759
                            //dr.Field<string>("Type")
2760
                        }
2761

    
2762
                    }
2763
                }
2764
            }
2765
        }
2766

    
2767
        private void UpdateErrorForPSN()
2768
        {
2769
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
2770
            foreach (DataRow dataRow in errorRows)
2771
            {
2772
                try
2773
                {
2774
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2775
                    bool change = false;
2776
                    bool bCheck = false;
2777
                    int bCount = 0;
2778
                    if (!PSNItem.EnableType(PSNItem.StartType))
2779
                    {
2780
                        change = true;
2781
                        bCheck = change;
2782
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2783
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2784

    
2785
                        Item item = PSNItem.Groups.First().Items.First();
2786
                        try
2787
                        {
2788
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2789

    
2790
                            tieInPointIndex++;
2791

    
2792

    
2793
                            if (item.ItemType == ItemType.Line)
2794
                            {
2795
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2796
                                bCount = 2;
2797

    
2798
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2799
                                {
2800
                                    loopRow["FROM_DATA"] = FROM_DATA;
2801
                                    if (loopRow.Field<string>("OrderNumber") == "0")
2802
                                    {
2803
                                        string status = loopRow.Field<string>("Status");
2804
                                        //string isvali
2805
                                        if (string.IsNullOrEmpty(status))
2806
                                            status = "Line Disconnected";
2807
                                        else if (!status.Contains("Line Disconnected"))
2808
                                            status += ", Line Disconnected";
2809
                                        loopRow["Status"] = status;
2810
                                        if (!string.IsNullOrEmpty(status))
2811
                                            loopRow["IsValid"] = "Error";
2812
                                    }
2813
                                }
2814
                            }
2815
                            else
2816
                            {
2817
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
2818
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
2819

    
2820
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2821
                                   
2822
                                
2823
                                bCount = 3;
2824
                            }
2825

    
2826
                            PSNItem.StartType = PSNType.Equipment;
2827
                        }
2828
                        catch (Exception ex)
2829
                        {
2830
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2831
                            return;
2832
                        }
2833
                    }
2834

    
2835
                    if (!PSNItem.EnableType(PSNItem.EndType))
2836
                    {
2837
                        change = true;
2838
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2839
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
2840
                        DataRow dr = pathItemRows.Last();
2841
                        if (change)
2842
                            dr = pathItemRows[pathItemRows.Count() - bCount];
2843

    
2844
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2845

    
2846
                        Item item = PSNItem.Groups.Last().Items.Last();
2847
                        try
2848
                        {
2849
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2850

    
2851
                            if (item.ItemType == ItemType.Line)
2852
                            {
2853
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2854
                                {
2855
                                    loopRow["TO_DATA"] = TO_DATA;
2856
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
2857
                                    {
2858
                                        string status = loopRow.Field<string>("Status");
2859
                                        if (string.IsNullOrEmpty(status))
2860
                                            status = "Line Disconnected";
2861
                                        else if (!status.Contains("Line Disconnected"))
2862
                                            status += ", Line Disconnected";
2863
                                        loopRow["Status"] = status;
2864
                                        if (!string.IsNullOrEmpty(status))
2865
                                            loopRow["IsValid"] = "Error";
2866
                                    }
2867
                                }
2868
                            }
2869

    
2870
                            tieInPointIndex++;
2871

    
2872
                            if (item.ItemType == ItemType.Line)
2873
                            {
2874
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
2875
                            }
2876
                            else
2877
                            {
2878
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
2879
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
2880
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
2881
                            }
2882

    
2883
                            PSNItem.EndType = PSNType.Equipment;
2884
                        }
2885
                        catch (Exception ex)
2886
                        {
2887
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2888
                            return;
2889
                        }
2890
                    }
2891

    
2892
                    dataRow["Type"] = PSNItem.GetPSNType();
2893
                    if (change)
2894
                    {
2895
                        int rowIndex = 0;
2896
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2897
                        {
2898
                            DataRow row = PathItems.Rows[i];
2899
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
2900
                                continue;
2901
                            string sequenceData = row["SequenceData_OID"].ToString();
2902
                            string[] split = sequenceData.Split(new char[] { '_' });
2903

    
2904
                            StringBuilder sb = new StringBuilder();
2905
                            for (int j = 0; j < split.Length - 1; j++)
2906
                                sb.Append(split[j] + "_");
2907
                            sb.Append(rowIndex++);
2908
                            row["SequenceData_OID"] = sb.ToString();
2909

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

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

    
2915
                            if (seqItemRows == null)
2916
                            {
2917
                                DataRow newRow = SequenceData.NewRow();
2918
                                newRow["OID"] = sb.ToString();
2919
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2920
                                newRow["PathItem_OID"] = row["OID"];
2921
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2922
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2923
                            }
2924
                            else
2925
                            {
2926
                                seqItemRows["OID"] = sb.ToString();
2927
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2928
                                seqItemRows["PathItem_OID"] = row["OID"];
2929
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2930
                            }
2931
                        }
2932
                    }
2933

    
2934
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
2935
                    {
2936
                        DataRow newRow = PathItems.NewRow();
2937
                        newRow["OID"] = Guid.NewGuid().ToString();
2938
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2939
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2940
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2941
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2942
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
2943
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
2944
                        newRow["DESCRIPTION"] = DATA;
2945
                        newRow["Class"] = "End of line terminator";
2946
                        newRow["SubClass"] = "End of line terminator";
2947
                        newRow["TYPE"] = "End";
2948
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2949
                        newRow["NPD"] = itemRow["NPD"];
2950
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2951
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2952
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2953
                        newRow["EGTConnectedPoint"] = "0";
2954
                        return newRow;
2955
                    }
2956

    
2957
                    DataRow createLineRow(DataRow itemRow)
2958
                    {
2959
                        DataRow newRow = PathItems.NewRow();
2960
                        newRow["OID"] = Guid.NewGuid().ToString();
2961
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2962
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2963
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2964
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2965
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
2966
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2967
                        newRow["Class"] = itemRow["Class"];
2968
                        newRow["SubClass"] = itemRow["SubClass"];
2969
                        newRow["TYPE"] = itemRow["TYPE"];
2970
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2971
                        newRow["NPD"] = itemRow["NPD"];
2972
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2973
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2974
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2975
                        newRow["EGTConnectedPoint"] = "0";
2976
                        return newRow;
2977
                    }
2978
                }
2979
                catch (Exception ex)
2980
                {
2981

    
2982
                }
2983
            }
2984
        }
2985

    
2986
        private void InsertTeePSN()
2987
        {
2988
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
2989
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
2990
            bool change = false;
2991
            foreach (DataRow dataRow in branchRows)
2992
            {
2993
                try
2994
                {
2995
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2996
                    change = false;
2997

    
2998
                    if (PSNItem.StartType == PSNType.Branch)
2999
                    {
3000
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3001
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3002
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3003
                        try
3004
                        {
3005
                            if (Teeitem.ItemType == ItemType.Line)
3006
                            {
3007
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3008
                                {
3009
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3010
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3011
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3012
                                    change = true;
3013
                                }
3014

    
3015
                            }
3016
                        }
3017
                        catch (Exception ex)
3018
                        {
3019
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3020
                            return;
3021
                        }
3022
                    }
3023

    
3024
                    if (PSNItem.EndType == PSNType.Branch)
3025
                    {
3026
                        //change = true;
3027
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3028

    
3029
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3030

    
3031
                        DataRow dr = pathItemRows.Last();
3032
                        if (change)
3033
                            dr = pathItemRows[pathItemRows.Count() - 2];
3034

    
3035
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3036

    
3037
                        try
3038
                        {
3039
                            if (Teeitem.ItemType == ItemType.Line)
3040
                            {
3041
                                if (dr.Field<string>("SubClass") != "Tee")
3042
                                {
3043
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3044
                                    change = true;
3045
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3046
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3047
                                }
3048

    
3049
                            }
3050
                        }
3051
                        catch (Exception ex)
3052
                        {
3053
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3054
                            return;
3055
                        }
3056
                    }
3057

    
3058
                    if (change)
3059
                    {
3060
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3061
                        int rowIndex = 0;
3062
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3063
                        {
3064
                            DataRow row = PathItems.Rows[i];
3065
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3066
                                continue;
3067
                            string sequenceData = row["SequenceData_OID"].ToString();
3068
                            string[] split = sequenceData.Split(new char[] { '_' });
3069

    
3070
                            StringBuilder sb = new StringBuilder();
3071
                            for (int j = 0; j < split.Length - 1; j++)
3072
                                sb.Append(split[j] + "_");
3073
                            sb.Append(rowIndex++);
3074
                            row["SequenceData_OID"] = sb.ToString();
3075

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

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

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

    
3100
                    DataRow createTeeRow(DataRow itemRow)
3101
                    {
3102
                        DataRow newRow = PathItems.NewRow();
3103
                        newRow["OID"] = Guid.NewGuid().ToString();
3104
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3105
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3106
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3107
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3108
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3109
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3110
                        newRow["DESCRIPTION"] = "";
3111
                        newRow["Class"] = "Branch";
3112
                        newRow["SubClass"] = "Tee";
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
                      
3120
                        newRow["EGTConnectedPoint"] = 0;
3121
                        return newRow;
3122
                    }
3123
                }
3124
                catch (Exception ex)
3125
                {
3126

    
3127
                }
3128
            }
3129
        }
3130
    }
3131

    
3132
    public class PSNItem
3133
    {
3134
        public PSNItem(int count, int Revision)
3135
        {
3136
            Groups = new List<Group>();
3137
            Topologies = new List<Topology>();
3138

    
3139
            Index = count + 1;
3140
            this.Revision = Revision;
3141
        }
3142

    
3143
        private int Revision;
3144
        public string UID { get; set; }
3145
        public List<Group> Groups { get; set; }
3146
        public List<Topology> Topologies { get; set; }
3147
        public PSNType StartType { get; set; }
3148
        public PSNType EndType { get; set; }
3149
        public int Index { get; set; }
3150
        public string IsValid { get; set; }
3151
        public bool IsKeyword { get; set; }
3152
        public string Status { get; set; }
3153
        public string IncludingVirtualData { get; set; }
3154
        public string PSNAccuracy { get; set; }
3155
        public KeywordInfo KeywordInfos = new KeywordInfo();
3156
        public DataTable Nozzle = new DataTable();
3157

    
3158
        public string PSN_OID()
3159
        {
3160
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
3161
        }
3162

    
3163
        public string GetPSNType()
3164
        {
3165
            string result = string.Empty;
3166

    
3167
            if (EnableType(StartType) && EnableType(EndType))
3168
            {
3169
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
3170
                    result = "E2E";
3171
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
3172
                    result = "B2B";
3173
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
3174
                    result = "HD2";
3175

    
3176
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
3177
                    result = "E2B";
3178
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
3179
                    result = "B2E";
3180

    
3181
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
3182
                    result = "HDB";
3183
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
3184
                    result = "HDB";
3185

    
3186
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
3187
                    result = "HDE";
3188
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
3189
                    result = "HDE";
3190
                else
3191
                    result = "Error";
3192
            }
3193
            else
3194
                result = "Error";
3195

    
3196
            return result;
3197

    
3198

    
3199
        }
3200

    
3201
        public bool EnableType(PSNType type)
3202
        {
3203
            bool result = false;
3204

    
3205
            if (type == PSNType.Branch ||
3206
                type == PSNType.Equipment ||
3207
                type == PSNType.Header)
3208
            {
3209
                result = true;
3210
            }
3211

    
3212
            return result;
3213
        }
3214

    
3215
        public bool IsBypass { get; set; }
3216

    
3217
        public string GetFromData(ref string Type, ref Item item)
3218
        {
3219
            Status = string.Empty;
3220
            string result = string.Empty;
3221
            if (IsKeyword)
3222
                IsKeyword = false;
3223
            try
3224
            {
3225
                item = Groups.First().Items.First();
3226

    
3227
                if (StartType == PSNType.Header)
3228
                    result = "ENDOFHEADER";
3229
                else if (StartType == PSNType.Branch)
3230
                {
3231
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3232
                    if (!item.MissingLineNumber2 && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3233
                        result = item.Relations.First().Item.LineNumber.Name;
3234
                    else
3235
                    {
3236
                        IsValid = "Error";
3237
                        Status += ", Missing LineNumber_2";
3238
                        result = "Empty LineNumber";
3239
                    }
3240

    
3241
                    //if (item.MissingLineNumber1)
3242
                    //{
3243
                    //    Status += ", Missing LineNumber_1";
3244
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3245

    
3246
                    //}
3247
                }
3248
                else if (StartType == PSNType.Equipment)
3249
                {
3250
                    if (Groups.First().Items.First().Equipment != null)
3251
                        result = Groups.First().Items.First().Equipment.ItemTag;
3252
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
3253

    
3254
                    if (drNozzle != null)
3255
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3256
                }
3257
                else
3258
                {
3259
                    IsValid = "Error";
3260
                    item = Groups.First().Items.First();
3261
                    if (item.ItemType == ItemType.Symbol)
3262
                    {
3263

    
3264
                        string keyword = string.Empty;
3265
                        keyword = GetFromKeywordData(ref Type, item);
3266

    
3267
                        if (string.IsNullOrEmpty(keyword))
3268
                        {
3269
                            if (item.ID2DBType.Contains("OPC's"))
3270
                                Status += ", OPC Disconnected";
3271
                            else
3272
                                Status += ", Missing ItemTag or Description";
3273

    
3274
                            result = item.ID2DBName;
3275
                        }
3276
                        else
3277
                        {
3278
                            result = keyword;
3279
                            IsKeyword = true;
3280
                            IsValid = string.Empty;
3281
                        }
3282

    
3283
                    }
3284
                    else if (item.ItemType == ItemType.Line)
3285
                    {
3286

    
3287
                        if (item.MissingLineNumber1)
3288
                        {
3289
                            IsValid = "Error";
3290
                            Status += ", Missing LineNumber_1";
3291
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3292
                        }
3293
                        else
3294
                            result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3295
                    }
3296
                    else
3297
                        result = "Unknown";
3298

    
3299
                }
3300
            }
3301
            catch (Exception ex)
3302
            {
3303

    
3304
            }
3305

    
3306
            return result;
3307
        }
3308

    
3309
        public string GetFromKeywordData(ref string Type, Item item)
3310
        {
3311
            string result = string.Empty;
3312

    
3313
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3314
            {
3315
                if (keyitem.Name.Equals(item.Name))
3316
                {
3317
                    result = keyitem.Keyword;
3318
                    Type = item.ID2DBType;
3319
                    break;
3320
                }
3321
            }
3322

    
3323
            return result;
3324
        }
3325

    
3326
        public string GetToKeywordData(ref string Type, Item item)
3327
        {
3328
            string result = string.Empty;
3329

    
3330
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3331
            {
3332
                if (keyitem.Name.Equals(item.Name))
3333
                {
3334
                    result = keyitem.Keyword;
3335
                    Type = item.ID2DBType;
3336
                    break;
3337
                }
3338
            }
3339
            return result;
3340
        }
3341

    
3342
        public string GetToData(ref string ToType, ref Item item)
3343
        {
3344
            string result = string.Empty;
3345
            Status = string.Empty;
3346

    
3347
            if (IsKeyword)
3348
                IsKeyword = false;
3349

    
3350
            item = Groups.Last().Items.Last();
3351

    
3352
            if (EndType == PSNType.Header)
3353
                result = "ENDOFHEADER";
3354
            else if (EndType == PSNType.Branch)
3355
            {
3356
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3357
                if (!item.MissingLineNumber2 && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3358
                    result = item.Relations.Last().Item.LineNumber.Name;
3359
                else
3360
                {
3361
                    IsValid = "Error";
3362
                    Status += ", Missing LineNumber_2";
3363
                    result = "Empty LineNumber";
3364
                }
3365

    
3366
                //if (item.MissingLineNumber1)
3367
                //{
3368
                //    Status += ", Missing LineNumber_1";
3369
                //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3370

    
3371
                //}
3372
            }
3373
            else if (EndType == PSNType.Equipment)
3374
            {
3375
                if (Groups.Last().Items.Last().Equipment != null)
3376
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3377

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

    
3380
                if (drNozzle != null)
3381
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3382
            }
3383
            else
3384
            {
3385
                IsValid = "Error";
3386
                item = Groups.Last().Items.Last();
3387
                if (item.ItemType == ItemType.Symbol)
3388
                {
3389
                    string keyword = string.Empty;
3390
                    keyword = GetToKeywordData(ref ToType, item);
3391

    
3392
                    if (string.IsNullOrEmpty(keyword))
3393
                    {
3394
                        if (item.ID2DBType.Contains("OPC's"))
3395
                            Status += ", OPC Disconnected";
3396
                        else
3397
                            Status += ", Missing ItemTag or Description";
3398

    
3399
                        result = item.ID2DBName;
3400
                    }
3401
                    else
3402
                    {
3403
                        result = keyword;
3404
                        IsValid = string.Empty;
3405
                        IsKeyword = true;
3406
                    }
3407

    
3408
                }
3409
                else if (item.ItemType == ItemType.Line)
3410
                {
3411
                    if (item.MissingLineNumber1)
3412
                    {
3413
                        IsValid = "Error";
3414
                        Status += ", Missing LineNumber_1";
3415
                        result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3416
                    }
3417
                    else
3418
                        result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3419
                }
3420
                else
3421
                    result = "Unknown";
3422

    
3423

    
3424
            }
3425

    
3426

    
3427

    
3428
            return result;
3429
        }
3430

    
3431
        public string GetPBSData()
3432
        {
3433
            string result = string.Empty;
3434
            List<string> PBSList = new List<string>();
3435
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3436
            {
3437
                string attrValue = Settings.Default.PBSSettingValue;
3438

    
3439
                foreach (Group group in Groups)
3440
                {
3441
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3442
                    foreach (LineNumber lineNumber in lineNumbers)
3443
                    {
3444
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3445
                        if (attribute != null)
3446
                        {
3447
                            string value = attribute.Value;
3448
                            if (!PBSList.Contains(value))
3449
                                PBSList.Add(value);
3450
                        }
3451
                    }
3452
                }
3453
            }
3454
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3455
            {
3456
                string attrValue = Settings.Default.PBSSettingValue;
3457

    
3458
                foreach (Group group in Groups)
3459
                {
3460
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3461
                    foreach (Item item in items)
3462
                    {
3463
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3464
                        if (!PBSList.Contains(value))
3465
                            PBSList.Add(value);
3466
                    }
3467
                }
3468
            }
3469
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3470
            {
3471
                string attrValue = Settings.Default.PBSSettingValue;
3472

    
3473
                foreach (Group group in Groups)
3474
                {
3475
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3476
                    foreach (Document document in documents)
3477
                    {
3478
                        string name = document.DrawingName;
3479

    
3480
                        int startIndex = Settings.Default.PBSSettingStartValue;
3481
                        int endIndex = Settings.Default.PBSSettingEndValue;
3482

    
3483
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3484
                        if (!PBSList.Contains(subStr))
3485
                            PBSList.Add(subStr);
3486
                    }
3487
                }
3488
            }
3489
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3490
            {
3491
                foreach (Group group in Groups)
3492
                {
3493
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3494
                    foreach (Document document in documents)
3495
                    {
3496
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
3497
                        foreach (TextInfo textInfo in textInfos)
3498
                        {
3499
                            if (!PBSList.Contains(textInfo.Value))
3500
                                PBSList.Add(textInfo.Value);
3501
                        }
3502
                    }
3503
                }
3504
            }
3505

    
3506
            foreach (var item in PBSList)
3507
            {
3508
                if (string.IsNullOrEmpty(result))
3509
                    result = item;
3510
                else
3511
                    result += ", " + item;
3512
            }
3513
            return result;
3514
        }
3515
    }
3516
}
클립보드 이미지 추가 (최대 크기: 500 MB)