프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ 528aa878

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

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

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

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

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

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

    
54
        int tieInPointIndex = 1;
55

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

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

    
64
        ID2Info id2Info = ID2Info.GetInstance();
65

    
66

    
67

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

    
71
        public PSN()
72
        {
73

    
74
        }
75

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

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

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

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

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

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

    
265
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  PathItemSorting ( 90 % )");
266
            PathItemSorting();
267

    
268
            // AirFinCooler 
269
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAirFinCooler ( 95 % )");
270
            UpdateAirFinCooler();
271

    
272
        }
273

    
274
        private void PathItemSorting()
275
        {
276
            try
277
            {
278
                DataTable dtPathItems = PathItems.Clone();
279
                DataTable dtPipeSystemNetwork = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
280

    
281
                foreach (DataRow drpipe in dtPipeSystemNetwork.Rows)
282
                {
283
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drpipe["OID"].ToString()));
284
                    DataTable dtSequenceItems = SequenceData.Clone();
285
                    foreach (DataRow drpath in pathItemRows)
286
                    {
287
                        DataRow sequenceRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", drpath.Field<string>("OID"))).First();
288

    
289
                        DataRow newRow = dtSequenceItems.NewRow();
290
                        foreach (DataColumn column in SequenceData.Columns)
291
                            if (dtSequenceItems.Columns[column.ColumnName] != null)
292
                                newRow[column.ColumnName] = sequenceRows[column.ColumnName];
293

    
294
                        dtSequenceItems.Rows.Add(newRow);
295
                    }
296

    
297
                    foreach (DataRow sqrow in dtSequenceItems.Select().OrderBy(x => Convert.ToInt32(x.Field<string>("SERIALNUMBER"))))
298
                    {
299
                        DataRow newRow = dtPathItems.NewRow();
300
                        DataRow row = PathItems.Select(string.Format("OID = '{0}'", sqrow["PathItem_OID"])).First();
301

    
302
                        foreach (DataColumn column in PathItems.Columns)
303
                            if (dtPathItems.Columns[column.ColumnName] != null)
304
                                newRow[column.ColumnName] = row[column.ColumnName];
305

    
306
                        dtPathItems.Rows.Add(newRow);
307
                    }
308
                }
309

    
310
                PathItems.Clear();
311
                PathItems = dtPathItems.Copy();
312
            }
313
            catch (Exception ex)
314
            {
315
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
316
            }
317
        }
318
        
319
        private void UpdateAirFinCooler()
320
        {
321
            try
322
            {
323
                int afcTagNum = 0;
324
                int pumpTagNum = 0;
325
                #region EquipmentAirFinCooler Info
326
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
327
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
328
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
329
                {
330
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
331
                    {
332
                        Type = row["Type"].ToString(),
333
                        Name = row["Name"].ToString()
334
                    });
335
                }
336
                #endregion
337

    
338
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC = 'P1'");
339
                DataRow[] pumpRows = PipeSystemNetwork.Select("PUMP = 'PUMP'");
340
                // 1, 2번
341
                foreach (DataRow dataRow in pumpRows) 
342
                {
343
                    pumpTagNum++;
344

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

    
347
                    string eqTag = string.Empty;
348
                    string EGFlowDirection = string.Empty;
349
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
350
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
351
                    {
352
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
353
                        {
354
                            eqTag = PSNItem.Groups.First().Items.First().Equipment.ItemTag;
355
                            EGFlowDirection = "O";
356
                        }                        
357
                    } 
358
                    else if(PSNItem.Groups.Last().Items.Last().Equipment != null)
359
                    {
360
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
361
                        {
362
                            eqTag = PSNItem.Groups.Last().Items.Last().Equipment.ItemTag;
363
                            EGFlowDirection = "I";
364
                        }
365
                    }
366

    
367
                    if(!string.IsNullOrEmpty(eqTag))
368
                    {
369
                        foreach (DataRow dr in pathItemRows)
370
                        {
371
                            dr["EqpGroupTag"] = eqTag;
372
                            dr["EGFlowDirection"] = EGFlowDirection;
373
                        }
374
                    }
375
                }
376

    
377
                // 3, 4번
378
                foreach (DataRow dataRow in pumpRows) 
379
                {
380

    
381
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
382
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
383
                    string EGFlowDirection = string.Empty;
384

    
385
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
386
                    {
387
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
388
                        {
389
                            EGFlowDirection = "O";
390
                        }
391
                    }
392
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
393
                    {
394
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
395
                        {
396
                            EGFlowDirection = "I";
397
                        }
398
                    }
399

    
400

    
401
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
402

    
403
                    foreach (DataRow dr in pathItemRows)
404
                    {
405
                        if(dr.Field<string>("ViewPipeSystemNetwork_OID") != dataRow["OID"].ToString())
406
                        {
407
                            string viewEGFlowDirection = string.Empty;
408
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
409
                            {
410
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));                               
411

    
412
                                if (viewPSNItem.Groups.First().Items.First().Equipment != null)
413
                                {
414
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
415
                                    {
416
                                        viewEGFlowDirection = "O";
417
                                    }
418
                                }
419
                                else if (viewPSNItem.Groups.Last().Items.Last().Equipment != null)
420
                                {
421
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
422
                                    {
423
                                        viewEGFlowDirection = "I";
424
                                    }
425
                                }
426

    
427
                                if (EGFlowDirection.Equals(viewEGFlowDirection) && !lstViewPipeSystemNetwork_OID.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
428
                                    lstViewPipeSystemNetwork_OID.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
429
                            }
430
                            else
431
                            {
432
                            }
433
                        }
434
                    }
435

    
436
                    string selectViewOID = string.Empty;
437

    
438
                    if (EGFlowDirection == "O") //From 이면 시작점에서 제일 먼 값
439
                    {
440
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
441
                        {
442
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
443
                            {                                
444
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
445
                            }
446
                        }
447
                    }
448
                    else if (EGFlowDirection == "I") //To 이면 시작점에서 제일 가까운 값
449
                    {
450
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
451
                        {
452
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
453
                            {
454
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
455
                                break;
456
                            }
457
                        }
458
                    }
459

    
460
                    if (!string.IsNullOrEmpty(selectViewOID)) //selectViewOID 가 있으면
461
                    {              
462
                        string EqpGroupTag = string.Empty;                       
463

    
464
                        if((EGFlowDirection == "O" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.Last().Field<string>("ViewPipeSystemNetwork_OID"))) ||
465
                            (EGFlowDirection == "I" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID"))))
466
                        { 
467
                            DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID")));
468

    
469
                            foreach (DataRow row in viewpathItemRows)
470
                            {
471
                                if (!string.IsNullOrEmpty(row.Field<string>("EqpGroupTag")))
472
                                {
473
                                    EqpGroupTag = row.Field<string>("EqpGroupTag");
474
                                    break;
475
                                }
476
                            }
477

    
478
                            foreach (DataRow dr in pathItemRows)
479
                            {
480
                                dr["EqpGroupTag"] = EqpGroupTag;
481
                            }
482

    
483
                        }
484
                        else
485
                        {
486
                            bool bCheck = false;
487
                            if (EGFlowDirection == "I") //To 일때
488
                            {
489
                                foreach (DataRow dr in pathItemRows)
490
                                {
491
                                    if (selectViewOID == dr["OID"].ToString())
492
                                    {
493
                                        dr["EGTConnectedPoint"] = "1";
494
                                        bCheck = true;
495
                                    }
496

    
497
                                    if (!bCheck)
498
                                    {
499
                                        dr["EqpGroupTag"] = string.Empty;
500
                                        dr["MainLineTag"] = string.Empty;
501
                                        dr["EGTConnectedPoint"] = "0";
502
                                        dr["EGFlowDirection"] = string.Empty;
503
                                    }
504
                                    else
505
                                    {
506
                                        dr["MainLineTag"] = "M";
507
                                    }
508
                                    
509
                                }
510

    
511
                            }
512
                            else if (EGFlowDirection == "O") //From 일 때
513
                            {
514
                                foreach (DataRow dr in pathItemRows)
515
                                {
516
                                    if (bCheck)
517
                                    {
518
                                        
519
                                        dr["EqpGroupTag"] = string.Empty;
520
                                        dr["MainLineTag"] = string.Empty;
521
                                        dr["EGTConnectedPoint"] = "0";
522
                                        dr["EGFlowDirection"] = string.Empty;
523
                                    }
524
                                    else
525
                                    {
526
                                        dr["MainLineTag"] = "M";
527
                                    }
528

    
529
                                    if (selectViewOID == dr["OID"].ToString())
530
                                    {
531
                                        dr["EGTConnectedPoint"] = "1";
532
                                        bCheck = true;
533
                                    }
534
                                }
535
                            }
536
                        }
537
                    }
538
                    else
539
                    {
540
                        foreach (DataRow dr in pathItemRows)
541
                        {
542
                            dr["EqpGroupTag"] = string.Empty;
543
                            dr["EGFlowDirection"] = string.Empty;
544
                        }
545
                    }
546
                }
547
                                
548
                // 5번
549
                foreach (DataRow dataRow in pumpRows)
550
                {
551
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
552

    
553
                    bool bCheck = false;
554
                    string EqpGroupTag = string.Empty;
555

    
556
                    string EGFlowDirection = string.Empty;                   
557

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

    
560
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
561
                    {
562
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
563
                        {
564
                            EGFlowDirection = "O";
565
                        }
566
                    }
567
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
568
                    {
569
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
570
                        {
571
                            EGFlowDirection = "I";
572
                        }
573
                    }
574

    
575
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
576
                    List<string> lstEqTagRows = new List<string>();
577
                    if (EGFlowDirection.Equals("I"))
578
                    {
579
                        foreach (DataRow dr in pathItemRows)
580
                        {                            
581
                            if (!string.IsNullOrEmpty(dr.Field<string>("MainLineTag")) && dr.Field<string>("MainLineTag").Equals("M") && !string.IsNullOrEmpty(dr.Field<string>("EqpGroupTag")))
582
                            {
583
                                bCheck = true;
584
                                EqpGroupTag = dr.Field<string>("EqpGroupTag");
585
                                if(!lstEqTagRows.Contains(EqpGroupTag))
586
                                    lstEqTagRows.Add(EqpGroupTag);
587

    
588
                                if(dataRow["OID"].ToString() != dr.Field<string>("ViewPipeSystemNetwork_OID"))
589
                                {
590
                                    PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));
591
                                    if (viewPSNItem.Groups.Last().Items.Last().Equipment == null)
592
                                        continue;
593

    
594
                                    if (!lstEqTagRows.Contains(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag))
595
                                        lstEqTagRows.Add(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag);
596
                                }
597
                                
598
                            }
599

    
600
                        }
601
                        if(bCheck)
602
                        {
603
                            foreach (DataRow row in pumpRows)
604
                            {
605
                                if (row.Field<string>("OID").Equals(dataRow["OID"].ToString()))
606
                                    continue;
607

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

    
610
                                if (viewPSNItem.Groups.First().Items.First().Equipment == null)
611
                                    continue;
612
                                
613
                                if (lstEqTagRows.Contains(viewPSNItem.Groups.First().Items.First().Equipment.ItemTag) && !lstViewPipeSystemNetwork_OID.Contains(row.Field<string>("OID")))
614
                                    lstViewPipeSystemNetwork_OID.Add(row.Field<string>("OID"));
615
                            }
616

    
617
                                
618

    
619
                            if (lstViewPipeSystemNetwork_OID.Count() > 0)
620
                            {
621
                                foreach (string viewPipesystem in lstViewPipeSystemNetwork_OID)
622
                                {
623
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewPipesystem));
624
                                    foreach (DataRow viewdr in viewpathItemRows)
625
                                    {
626
                                        if (!string.IsNullOrEmpty(viewdr["EqpGroupTag"].ToString()))
627
                                            viewdr["EqpGroupTag"] = EqpGroupTag;
628
                                    }
629
                                }
630
                            }
631
                        }                        
632
                    }                   
633
                }
634
                
635
                foreach (DataRow dataRow in airFinCoolerRows)
636
                {
637
                    afcTagNum++;
638
                    string EGFlowDirection = string.Empty;
639

    
640
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
641
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
642
                    {
643
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
644
                        {
645
                            EGFlowDirection = "O";
646
                        }
647
                    }
648
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
649
                    {
650
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
651
                        {
652
                            EGFlowDirection = "I";
653
                        }
654
                    }
655

    
656
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
657
                    List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
658
                    //ViewPipeSystemNetwork_OID
659
                    string MainLineTag = "";
660
                    if (dataRow["Type"].ToString() == "E2E")
661
                    {
662
                        MainLineTag = "M";
663
                         dataRow["AFC"] = "P3";
664
                    }
665
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
666
                    {
667
                        int bCount = 0;
668
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
669
                        {
670
                            if (viewOID == dataRow["OID"].ToString())
671
                                continue;
672

    
673
                            DataRow dr = PipeSystemNetwork.Select(string.Format("OID = '{0}'", viewOID)).First();
674
                            if (dr.Field<string>("AFC") != "P1")
675
                            {
676
                                bCount++;
677
                                string[] arr = dr.Field<string>("AFC").Split('_');
678
                                if (arr.Length == 1)
679
                                    dr["AFC"] = arr[0] + "_1";
680
                                else
681
                                {
682
                                    dr["AFC"] = arr[0] + "_" + Convert.ToInt32(arr[1]) + 1;
683
                                    afcTagNum++;
684
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID));
685
                                    foreach (DataRow viewdr in viewpathItemRows)
686
                                    {
687
                                        viewdr["EqpGroupTag"] = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));  //ATG Sequence No Rule 여쭤봐야함.
688
                                        viewdr["MainLineTag"] = "M";
689
                                    }
690
                                }
691

    
692
                            }
693
                        }
694
                        
695
                        if(bCount == 1)
696
                        {
697
                            MainLineTag = "M";
698
                           // dataRow["AFC"] = "P3";
699
                        }
700
                            
701
                    }
702

    
703
                    foreach (DataRow dr in pathItemRows)
704
                    {
705
                        dr["EqpGroupTag"] = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));  //ATG Sequence No Rule 여쭤봐야함.
706
                        dr["MainLineTag"] = MainLineTag; 
707
                        dr["EGFlowDirection"] = EGFlowDirection; 
708
                    }
709
                }
710
                
711
                foreach (DataRow dataRow in airFinCoolerRows)
712
                {
713
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = ''", dataRow["OID"].ToString()));
714
                    //ML이 공란인 PSN - P1이 있다면 해당 Pathitem에 P3인 psn이 있는지 확인 : 해당 값은 전부 돌린후 확인 가능하기 때문에 다시 조회
715
                    if (pathItemRows.Count() > 0)
716
                    {
717
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
718
                        List<string> lstpsn = new List<string>();
719
                        string EqpGroupTag = string.Empty;
720
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
721
                        {
722
                            if (dataRow["OID"].ToString() == viewOID)
723
                            {
724
                                //lstViewPipeSystemNetwork_OID.Remove(viewOID);
725
                                continue;
726
                            }
727
                            DataRow viewPSN = null;
728
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
729
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
730
                            
731
                            if (viewPSN != null)
732
                            {
733
                                EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
734
                                foreach (DataRow dr in pathItemRows)
735
                                {
736
                                    dr["EqpGroupTag"] = EqpGroupTag;
737

    
738
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains("ViewPipeSystemNetwork_OID"))
739
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
740
                                }
741
                            }
742
                            
743
                        }
744

    
745
                        while(lstpsn.Count() != 0)
746
                        {
747
                            foreach(string psn in lstpsn)
748
                            {
749
                                DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", psn));
750
                                foreach (DataRow dr in rule4pathItems)
751
                                {
752
                                    dr["EqpGroupTag"] = EqpGroupTag;
753

    
754
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains("ViewPipeSystemNetwork_OID"))
755
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
756
                                }
757

    
758
                                lstpsn.Remove(psn);
759
                            }                        
760

    
761
                        }
762
                    }
763
                    
764
                }
765

    
766
                //DataRow[]  = PipeSystemNetwork.Select("AFC = 'P1'");
767
                foreach(DataRow dr in PipeSystemNetwork.Rows)
768
                {
769
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
770
                    if(pathItemRows.Count() > 0)
771
                    {
772
                        if(dr["Type"].ToString() == "HD2")
773
                        {
774
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
775
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
776
                            {                              
777
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
778
                                {
779
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
780
                                    {
781
                                        dataRow["EGTConnectedPoint"] = "1";
782
                                    }
783
                                }
784
                            }
785
                        }
786
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
787
                        {
788
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
789
                            string lastP1 = string.Empty;
790
                            foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
791
                            {
792
                                if (viewpsn == dr["OID"].ToString())
793
                                    continue;
794

    
795
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).Length == 0)
796
                                    continue;
797

    
798
                                DataRow rows = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).First();
799
                                if(rows != null)
800
                                {
801
                                    lastP1 = viewpsn;
802
                                }
803
                            }
804

    
805
                            if(!string.IsNullOrEmpty(lastP1))
806
                            {
807
                                bool bCheck = false;
808
                                foreach (DataRow dataRow in pathItemRows)
809
                                {
810
                                    if (bCheck)
811
                                        dataRow["EqpGroupTag"] = string.Empty;
812

    
813
                                    if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
814
                                    {
815
                                        bCheck = true;
816
                                        dataRow["EGTConnectedPoint"] = 1;
817
                                    }                       
818
                                }
819
                            }
820
                        }
821
                    }
822
                }
823

    
824
                //psn data 정리
825
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
826
                {
827
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
828
                    string EGTag = string.Empty;
829
                    string HasMLTags = "False";
830

    
831
                    foreach (DataRow dataRow in pathItemRows)
832
                    {
833
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
834
                            EGTag = dataRow.Field<string>("EqpGroupTag");
835

    
836
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
837
                            HasMLTags = "True";
838

    
839
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
840
                            break;
841
                    }
842

    
843
                    pipesystem["EGTag"] = EGTag;
844
                    pipesystem["HasMLTags"] = HasMLTags;
845
                }
846
            }
847
            catch (Exception ex)
848
            {
849
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
850
            }
851
            //}
852
        }
853

    
854
        private void UpdateValveGrouping()
855
        {
856
            try
857
            {
858
                #region ValveGrouping Info
859
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
860
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
861
                foreach (DataRow row in dtValveGroupung.Rows)
862
                {
863
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
864
                    {
865
                        OID = row["OID"].ToString(),
866
                        GroupType = row["GroupType"].ToString(),
867
                        TagIdentifier = row["TagIdentifier"].ToString(),
868
                        AttributeName = row["AttributeName"].ToString(),
869
                        SppidSymbolName = row["SppidSymbolName"].ToString()
870
                    });
871
                }
872
                #endregion
873

    
874

    
875
                int vgTagNum = 1;
876
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
877
                foreach (DataRow drPathitem in tagpathItemRows)
878
                {
879
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
880
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
881
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
882
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
883
                        continue;
884
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
885
                    List<Item> valveGroupingItem = new List<Item>();
886
                    int bCnt = 0;
887

    
888
                    //bool bCheck = false;
889
                    List<DataRow> lstitem = new List<DataRow>();
890
                    foreach (DataRow dr in pathItemRows)
891
                    {
892
                        //if (!string.IsNullOrEmpty(dr["GROUPTAG"].ToString()))
893
                        //    break;
894

    
895
                       if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
896
                        {
897
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
898
                            if (dr["GROUPTAG"].ToString() == "Scope Break")
899
                            {
900
                                dr["GROUPTAG"] = string.Empty;
901
                                break;
902
                            }
903

    
904
                            if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
905
                            {
906
                               // bCheck = true;
907
                                lstitem.Add(dr);
908
                                keyValuePairs.Add(bCnt, lstitem.ToList());
909
                                bCnt++;
910
                                lstitem.Clear();
911
                            }
912
                            else
913
                                lstitem.Add(dr);
914
                        }
915
                        else
916
                            lstitem.Add(dr);
917
                    }
918

    
919
                    if (lstitem.Count > 0)
920
                    {
921
                        keyValuePairs.Add(bCnt, lstitem);
922
                        //bCnt++;
923
                    }
924

    
925
                    if (keyValuePairs.Count() == 0)
926
                        continue;
927

    
928
                    string VGTag = string.Empty;
929
                    if (valveitem.AttributeName == "NoSelection")
930
                    {
931
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
932
                        vgTagNum++;
933
                    }
934
                    else
935
                    {
936
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
937
                    }
938

    
939
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
940
                    {
941
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
942
                        {
943
                            foreach (DataRow dr in keyValuePair.Value)
944
                            {
945
                                dr["GROUPTAG"] = VGTag;
946
                            }
947
                        }
948
                    }
949

    
950
                    if(valveitem.GroupType.Contains("PSV"))
951
                    {
952
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
953
                        foreach (DataRow row in psnRows)
954
                            row["Pocket"] = "Yes";
955
                    }                    
956
                }
957

    
958

    
959
            }
960
            catch (Exception ex)
961
            {
962
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
963
            }
964
            //}
965
        }
966

    
967
        private void SetTopologyData()
968
        {
969
            // 13번 excel
970
            foreach (Group group in groups)
971
            {
972
                LineNumber prevLineNumber = null;
973
                for (int i = 0; i < group.Items.Count; i++)
974
                {
975
                    Item item = group.Items[i];
976
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
977
                    if (lineNumber == null)
978
                    {
979
                        if (prevLineNumber != null)
980
                        {
981
                            if (!prevLineNumber.IsCopy)
982
                            {
983
                                prevLineNumber = prevLineNumber.Copy();
984
                                item.Document.LineNumbers.Add(prevLineNumber);
985
                                item.MissingLineNumber1 = true;
986
                            }
987
                            item.Owner = prevLineNumber.UID;
988
                        }
989
                    }
990
                    else
991
                        prevLineNumber = lineNumber;
992
                }
993

    
994
                prevLineNumber = null;
995
                for (int i = group.Items.Count - 1; i > -1; i--)
996
                {
997
                    Item item = group.Items[i];
998
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
999
                    if (lineNumber == null)
1000
                    {
1001
                        if (prevLineNumber != null)
1002
                        {
1003
                            if (!prevLineNumber.IsCopy)
1004
                            {
1005
                                prevLineNumber = prevLineNumber.Copy();
1006
                                item.Document.LineNumbers.Add(prevLineNumber);
1007
                                item.MissingLineNumber1 = true;
1008
                            }
1009

    
1010
                            item.Owner = prevLineNumber.UID;
1011
                        }
1012
                    }
1013
                    else
1014
                        prevLineNumber = lineNumber;
1015
                }
1016

    
1017
                if (prevLineNumber == null)
1018
                {
1019
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1020
                    Random random = new Random();
1021
                    int index = random.Next(lineNumbers.Count - 1);
1022

    
1023
                    // Copy
1024
                    LineNumber cLineNumber = lineNumbers[index].Copy();
1025
                    group.Document.LineNumbers.Add(cLineNumber);
1026

    
1027
                    foreach (Item item in group.Items)
1028
                    {
1029
                        item.Owner = cLineNumber.UID;
1030
                        item.MissingLineNumber2 = true;
1031
                    }
1032
                }
1033
            }
1034

    
1035
            foreach (Document document in Documents)
1036
            {
1037
                foreach (Item item in document.Items)
1038
                {
1039
                    item.TopologyData = string.Empty;
1040
                    item.PSNPipeLineID = string.Empty;
1041
                    List<string> pipeLineID = new List<string>();
1042
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1043
                    if (lineNumber != null)
1044
                    {
1045
                        item.LineNumber = lineNumber;
1046

    
1047
                        foreach (DataRow row in topologyRuleDT.Rows)
1048
                        {
1049
                            string uid = row["UID"].ToString();
1050
                            //if (uid == "-")
1051
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1052
                            if (uid != "-")
1053
                            {
1054
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1055

    
1056
                                Attribute attribute = lineNumber.Attributes.Find(x => x.Name == uid);
1057
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1058
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1059
                            }
1060
                        }
1061

    
1062
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1063
                        {
1064
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1065
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1066
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1067
                                                                 //else
1068
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1069
                        }
1070

    
1071
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1072
                        item.TopologyData = string.Join("-", pipeLineID);
1073

    
1074
                    }
1075
                    else
1076
                    {
1077
                        item.TopologyData = "Empty LineNumber";
1078
                        item.LineNumber = new LineNumber();
1079
                    }
1080
                }
1081
            }
1082

    
1083
            int emptyIndex = 1;
1084
            foreach (Group group in groups)
1085
            {
1086
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1087
                if (groupItems.Count > 0)
1088
                {
1089
                    foreach (var item in groupItems)
1090
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1091
                    emptyIndex++;
1092
                }
1093
            }
1094

    
1095
        }
1096

    
1097
        private void ConnectByOPC()
1098
        {
1099
            try
1100
            {
1101
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1102
                {
1103
                    Item opcItem = group.Items.Last();
1104
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1105
                    if (fromRows.Length.Equals(1))
1106
                    {
1107
                        DataRow opcRow = fromRows.First();
1108
                        string toDrawing = opcRow["ToDrawing"].ToString();
1109
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
1110

    
1111
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1112
                        if (toDocument != null)
1113
                        {
1114
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1115
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1116
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1117
                            if (toRows.Length > 1)
1118
                            {
1119
                                //throw new Exception("OPC error(multi connect)");
1120
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1121
                                return;
1122
                            }
1123
                            group.EndGroup = toGroup;
1124
                            toGroup.StartGroup = group;
1125
                        }
1126
                    }
1127
                }
1128
            }
1129
            catch (Exception ex)
1130
            {
1131
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1132
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1133
            }
1134
        }
1135

    
1136
        private void SetPSNItem()
1137
        {
1138
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1139
            foreach (Group group in groups)
1140
                groupDic.Add(group, Guid.NewGuid().ToString());
1141

    
1142
            foreach (Group group in groups)
1143
            {
1144
                string groupKey = groupDic[group];
1145
                if (group.StartGroup != null)
1146
                {
1147
                    string otherKey = groupDic[group.StartGroup];
1148
                    ChangeGroupID(otherKey, groupKey);
1149
                }
1150
            }
1151

    
1152
            // PSN 정리
1153
            foreach (var item in groupDic)
1154
            {
1155
                Group group = item.Key;
1156
                string uid = item.Value;
1157
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1158
                if (PSNItem == null)
1159
                {
1160
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1161
                    PSNItems.Add(PSNItem);
1162
                }
1163
                PSNItem.Groups.Add(group);
1164
                foreach (Item groupItem in group.Items)
1165
                    groupItem.PSNItem = PSNItem;
1166
            }
1167

    
1168
            // Sort PSN
1169
            foreach (PSNItem PSNItem in PSNItems)
1170
            {
1171
                List<Group> _groups = new List<Group>();
1172

    
1173
                Stack<Group> stacks = new Stack<Group>();
1174
                stacks.Push(PSNItem.Groups.First());
1175
                while (stacks.Count > 0)
1176
                {
1177
                    Group stack = stacks.Pop();
1178
                    if (_groups.Contains(stack))
1179
                        continue;
1180

    
1181
                    if (_groups.Count == 0)
1182
                        _groups.Add(stack);
1183
                    else
1184
                    {
1185
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1186
                        {
1187
                            int index = _groups.IndexOf(stack.StartGroup);
1188
                            _groups.Insert(index + 1, stack);
1189
                        }
1190
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1191
                        {
1192
                            int index = _groups.IndexOf(stack.EndGroup);
1193
                            _groups.Insert(index, stack);
1194
                        }
1195
                    }
1196

    
1197
                    if (stack.StartGroup != null)
1198
                        stacks.Push(stack.StartGroup);
1199
                    if (stack.EndGroup != null)
1200
                        stacks.Push(stack.EndGroup);
1201
                }
1202

    
1203
                PSNItem.Groups.Clear();
1204
                PSNItem.Groups.AddRange(_groups);
1205
            }
1206

    
1207
            void ChangeGroupID(string from, string to)
1208
            {
1209
                if (from.Equals(to))
1210
                    return;
1211

    
1212
                List<Group> changeItems = new List<Group>();
1213
                foreach (var _item in groupDic)
1214
                    if (_item.Value.Equals(from))
1215
                        changeItems.Add(_item.Key);
1216
                foreach (var _item in changeItems)
1217
                    groupDic[_item] = to;
1218
            }
1219
        }
1220

    
1221
        private void SetPSNType()
1222
        {
1223
            foreach (PSNItem PSNItem in PSNItems)
1224
            {
1225
                Group firstGroup = PSNItem.Groups.First();
1226
                Group lastGroup = PSNItem.Groups.Last();
1227

    
1228
                Item firstItem = firstGroup.Items.First();
1229
                Item lastItem = lastGroup.Items.Last();
1230

    
1231
                PSNItem.StartType = GetPSNType(firstItem, true);
1232
                PSNItem.EndType = GetPSNType(lastItem, false);
1233

    
1234
            }
1235

    
1236
            PSNType GetPSNType(Item item, bool bFirst = true)
1237
            {
1238
                PSNType type = PSNType.None;
1239

    
1240
                if (item.ItemType == ItemType.Line)
1241
                {
1242
                    Group group = groups.Find(x => x.Items.Contains(item));
1243
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1244
                    {
1245
                        Item connItem = item.Relations[0].Item;
1246
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1247
                            type = PSNType.Branch;
1248
                        else if (connItem.ItemType == ItemType.Symbol)
1249
                            type = PSNType.Symbol;
1250
                    }
1251
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1252
                    {
1253
                        Item connItem = item.Relations[1].Item;
1254
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1255
                            type = PSNType.Branch;
1256
                        else if (connItem.ItemType == ItemType.Symbol)
1257
                            type = PSNType.Symbol;
1258
                    }
1259
                }
1260
                else if (item.ItemType == ItemType.Symbol)
1261
                {
1262
                    if (item.SubItemType == SubItemType.Nozzle)
1263
                        type = PSNType.Equipment;
1264
                    else if (item.SubItemType == SubItemType.Header)
1265
                        type = PSNType.Header;
1266
                    else if (item.SubItemType == SubItemType.OPC)
1267
                        type = PSNType.OPC;
1268
                }
1269

    
1270
                return type;
1271
            }
1272
        }
1273

    
1274
        private void SetBranchInfo()
1275
        {
1276
            foreach (Document document in Documents)
1277
            {
1278
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1279
                foreach (Item line in lines)
1280
                {
1281
                    double[] point = line.Relations[0].Point;
1282
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1283
                    connLines.Sort(SortBranchLine);
1284
                    line.BranchItems.AddRange(connLines);
1285

    
1286
                    int SortBranchLine(Item a, Item b)
1287
                    {
1288
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1289
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1290

    
1291
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1292
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1293

    
1294
                        // 내림차순
1295
                        return distanceA.CompareTo(distanceB);
1296
                    }
1297
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1298
                    {
1299
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1300
                    }
1301
                }
1302
            }
1303
        }
1304

    
1305
        private void SetTopology()
1306
        {
1307
            try
1308
            {
1309
                #region 기본 topology 정리
1310
                foreach (PSNItem PSNItem in PSNItems)
1311
                {
1312
                    Topology topology = null;
1313
                    foreach (Group group in PSNItem.Groups)
1314
                    {
1315
                        foreach (Item item in group.Items)
1316
                        {
1317
                            if (string.IsNullOrEmpty(item.TopologyData))
1318
                                topology = null;
1319
                            else
1320
                            {
1321
                                if (topology == null)
1322
                                {
1323
                                    topology = new Topology()
1324
                                    {
1325
                                        ID = item.TopologyData
1326
                                    };
1327
                                    Topologies.Add(topology);
1328

    
1329
                                    if (!PSNItem.Topologies.Contains(topology))
1330
                                        PSNItem.Topologies.Add(topology);
1331
                                }
1332
                                else
1333
                                {
1334
                                    if (topology.ID != item.TopologyData)
1335
                                    {
1336
                                        topology = new Topology()
1337
                                        {
1338
                                            ID = item.TopologyData
1339
                                        };
1340
                                        Topologies.Add(topology);
1341

    
1342
                                        if (!PSNItem.Topologies.Contains(topology))
1343
                                            PSNItem.Topologies.Add(topology);
1344
                                    }
1345
                                }
1346

    
1347
                                item.Topology = topology;
1348
                                topology.Items.Add(item);
1349
                            }
1350
                        }
1351
                    }
1352
                }
1353
                #endregion
1354

    
1355
                #region Type
1356
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1357
                foreach (string id in ids)
1358
                {
1359
                    try
1360
                    {
1361

    
1362

    
1363
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1364

    
1365
                        // Main
1366
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1367
                        foreach (Topology topology in mainTopologies)
1368
                            topology.Type = "M";
1369

    
1370
                        // Branch
1371
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1372
                        foreach (Topology topology in branchToplogies)
1373
                            topology.Type = "B";
1374
                    }
1375
                    catch (Exception ex)
1376
                    {
1377
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1378
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1379
                    }
1380
                }
1381
                #endregion
1382
            }
1383
            catch (Exception ex)
1384
            {
1385
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1386
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1387
            }
1388

    
1389
        }
1390

    
1391
        private void SetTopologyIndex()
1392
        {
1393
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1394
            foreach (string id in ids)
1395
            {
1396
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1397

    
1398
                // Main
1399
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1400
                foreach (Topology topology in mainTopologies)
1401
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1402

    
1403
                // Branch
1404
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1405
                foreach (Topology topology in branchToplogies)
1406
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1407
            }
1408
        }
1409

    
1410
        private void SetPSNBypass()
1411
        {
1412
            foreach (PSNItem PSNItem in PSNItems)
1413
                PSNItem.IsBypass = IsBypass(PSNItem);
1414
        }
1415

    
1416
        private List<Topology> FindMainTopology(List<Topology> data)
1417
        {
1418
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1419
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1420
            //2021.11.17 안쓰네 JY
1421
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1422

    
1423
            List<Topology> main = new List<Topology>();
1424
            main.AddRange(data);
1425
            //
1426
            main = GetNozzleTopology(data);
1427
            if (main.Count == 1)
1428
                return main;
1429
            else
1430
            {
1431
                if (main.Count > 0)
1432
                    main = GetPMCTopology(main);
1433
                else
1434
                    main = GetPMCTopology(data);
1435

    
1436
                if (main.Count == 1)
1437
                    return main;
1438
                else
1439
                {
1440
                    if (main.Count > 0)
1441
                        main = GetDiaTopology(main);
1442
                    else
1443
                        main = GetDiaTopology(data);
1444

    
1445

    
1446
                    if (main.Count == 1)
1447
                        return main;
1448
                    else
1449
                    {
1450
                        if (main.Count > 0)
1451
                            main = GetItemTopology(main);
1452
                        else
1453
                            main = GetItemTopology(data);
1454
                    }
1455
                }
1456
            }
1457

    
1458
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1459
            {
1460
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1461
            }
1462

    
1463
            List<Topology> GetPMCTopology(List<Topology> topologies)
1464
            {
1465
                List<Topology> result = new List<Topology>();
1466
                foreach (DataRow row in PMCDT.Rows)
1467
                {
1468
                    string value = row["CODE"].ToString();
1469
                    foreach (Topology topology in topologies)
1470
                    {
1471
                        foreach (Item item in topology.Items)
1472
                        {
1473
                            if (item.LineNumber == null)
1474
                                continue;
1475
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1476
                            if (attribute != null && value == attribute.Value)
1477
                            {
1478
                                result.Add(topology);
1479
                                break;
1480
                            }
1481
                        }
1482
                    }
1483

    
1484
                    if (result.Count > 0)
1485
                        break;
1486
                }
1487

    
1488
                return result;
1489
            }
1490

    
1491
            List<Topology> GetDiaTopology(List<Topology> topologies)
1492
            {
1493
                List<Topology> result = new List<Topology>();
1494
                foreach (DataRow row in nominalDiameterDT.Rows)
1495
                {
1496
                    string inchValue = row["InchStr"].ToString();
1497
                    string metricValue = row["MetricStr"].ToString();
1498
                    foreach (Topology topology in topologies)
1499
                    {
1500
                        foreach (Item item in topology.Items)
1501
                        {
1502
                            if (item.LineNumber == null)
1503
                                continue;
1504
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1505
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1506
                            {
1507
                                result.Add(topology);
1508
                                break;
1509
                            }
1510
                        }
1511
                    }
1512

    
1513
                    if (result.Count > 0)
1514
                        break;
1515
                }
1516

    
1517
                return result;
1518
            }
1519

    
1520
            List<Topology> GetItemTopology(List<Topology> topologies)
1521
            {
1522
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1523
            }
1524

    
1525
            return main;
1526
        }
1527

    
1528
        private DataTable GetOPCInfo()
1529
        {
1530
            DataTable opc = DB.SelectOPCRelations();
1531
            DataTable drawing = DB.AllDrawings();
1532

    
1533
            DataTable dt = new DataTable();
1534
            dt.Columns.Add("FromDrawing", typeof(string));
1535
            dt.Columns.Add("FromDrawingUID", typeof(string));
1536
            dt.Columns.Add("FromOPCUID", typeof(string));
1537
            dt.Columns.Add("ToDrawing", typeof(string));
1538
            dt.Columns.Add("ToDrawingUID", typeof(string));
1539
            dt.Columns.Add("ToOPCUID", typeof(string));
1540
            foreach (DataRow row in opc.Rows)
1541
            {
1542
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1543
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1544
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1545
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1546
                if (!string.IsNullOrEmpty(toOPCUID))
1547
                {
1548
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
1549
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
1550
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
1551
                    {
1552
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
1553
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
1554

    
1555
                        DataRow newRow = dt.NewRow();
1556
                        newRow["FromDrawing"] = fromDrawingName;
1557
                        newRow["FromDrawingUID"] = fromDrawingUID;
1558
                        newRow["FromOPCUID"] = fromOPCUID;
1559
                        newRow["ToDrawing"] = toDrawingName;
1560
                        newRow["ToDrawingUID"] = toDrawingUID;
1561
                        newRow["ToOPCUID"] = toOPCUID;
1562

    
1563
                        dt.Rows.Add(newRow);
1564
                    }
1565
                }
1566
            }
1567

    
1568
            return dt;
1569
        }
1570

    
1571
        private DataTable GetTopologyRule()
1572
        {
1573
            DataTable dt = DB.SelectTopologyRule();
1574

    
1575
            return dt;
1576
        }
1577

    
1578
        private bool IsConnected(Item item1, Item item2)
1579
        {
1580
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
1581
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
1582
                return true;
1583
            else
1584
                return false;
1585
        }
1586

    
1587
        private void SaveNozzleAndEquipment()
1588
        {
1589
            List<Item> nozzles = new List<Item>();
1590
            List<Equipment> equipments = new List<Equipment>();
1591
            foreach (Document document in Documents)
1592
            {
1593
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1594
                equipments.AddRange(document.Equipments);
1595
            }
1596

    
1597

    
1598
            DataTable nozzleDT = new DataTable();
1599
            nozzleDT.Columns.Add("OID", typeof(string));
1600
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1601
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1602
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1603
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1604
            nozzleDT.Columns.Add("FLUID", typeof(string));
1605
            nozzleDT.Columns.Add("NPD", typeof(string));
1606
            nozzleDT.Columns.Add("PMC", typeof(string));
1607
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1608
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1609

    
1610
            foreach (Item item in nozzles)
1611
            {
1612
                DataRow row = nozzleDT.NewRow();
1613
                row["OID"] = item.UID;
1614

    
1615
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
1616
                if (relation != null)
1617
                {
1618
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
1619
                    equipment.Nozzles.Add(item);
1620
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
1621
                    row["Equipment_OID"] = equipment.UID;
1622
                    item.Equipment = equipment;
1623
                }
1624
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
1625
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
1626
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
1627
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
1628
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1629
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
1630
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1631
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
1632

    
1633
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1634
                if (angle >= Math.PI * 2)
1635
                    angle = angle - Math.PI * 2;
1636
                row["ROTATION"] = angle.ToString();
1637

    
1638
                if (item.Topology.Items.First().Equals(item))
1639
                    row["FlowDirection"] = "Outlet";
1640
                else if (item.Topology.Items.Last().Equals(item))
1641
                    row["FlowDirection"] = "Inlet";
1642
                else
1643
                    row["FlowDirection"] = string.Empty;
1644

    
1645
                nozzleDT.Rows.Add(row);
1646
            }
1647

    
1648
            DataTable equipDT = new DataTable();
1649
            equipDT.Columns.Add("OID", typeof(string));
1650
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1651
            equipDT.Columns.Add("XCOORDS", typeof(string));
1652
            equipDT.Columns.Add("YCOORDS", typeof(string));
1653

    
1654
            foreach (Equipment equipment in equipments)
1655
            {
1656
                DataRow row = equipDT.NewRow();
1657
                row["OID"] = equipment.UID;
1658
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
1659
                {
1660
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
1661
                    if (attribute != null)
1662
                        equipment.ItemTag = attribute.Value;
1663
                }
1664
                else
1665
                    equipment.ItemTag = equipment.Name;
1666

    
1667
                row["ITEMTAG"] = equipment.ItemTag;
1668
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
1669
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
1670

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

    
1674
                equipDT.Rows.Add(row);
1675
            }
1676

    
1677
            Equipment = equipDT;
1678
            Nozzle = nozzleDT;
1679
        }
1680

    
1681
        private void SavePSNData()
1682
        {
1683
            try
1684
            {
1685
                DataTable pathItemsDT = new DataTable();
1686
                pathItemsDT.Columns.Add("OID", typeof(string));
1687
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
1688
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
1689
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
1690
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
1691
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
1692
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
1693
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
1694
                pathItemsDT.Columns.Add("Class", typeof(string));
1695
                pathItemsDT.Columns.Add("SubClass", typeof(string));
1696
                pathItemsDT.Columns.Add("TYPE", typeof(string));
1697
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
1698
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
1699
                pathItemsDT.Columns.Add("NPD", typeof(string));
1700
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
1701
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
1702
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
1703
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
1704
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
1705
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
1706
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
1707
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
1708

    
1709
                DataTable sequenceDataDT = new DataTable();
1710
                sequenceDataDT.Columns.Add("OID", typeof(string));
1711
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
1712
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
1713
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1714

    
1715
                DataTable pipeSystemNetworkDT = new DataTable();
1716
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
1717
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
1718
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
1719
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
1720
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
1721
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
1722
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1723
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
1724
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
1725
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
1726
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
1727
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
1728
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
1729
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
1730
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
1731
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
1732
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
1733
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
1734
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
1735

    
1736
                DataTable topologySetDT = new DataTable();
1737
                topologySetDT.Columns.Add("OID", typeof(string));
1738
                topologySetDT.Columns.Add("Type", typeof(string));
1739
                topologySetDT.Columns.Add("SubType", typeof(string));
1740
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
1741
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
1742
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
1743
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
1744

    
1745
                DataTable pipelineDT = new DataTable();
1746
                pipelineDT.Columns.Add("OID", typeof(string));
1747
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
1748
                pipelineDT.Columns.Add("FLUID", typeof(string));
1749
                pipelineDT.Columns.Add("PMC", typeof(string));
1750
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
1751
                pipelineDT.Columns.Add("INSULATION", typeof(string));
1752
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
1753
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
1754
                pipelineDT.Columns.Add("Unit", typeof(string));
1755

    
1756
                DataTable pipesystemDT = new DataTable();
1757
                pipesystemDT.Columns.Add("OID", typeof(string));
1758
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
1759
                pipesystemDT.Columns.Add("FLUID", typeof(string));
1760
                pipesystemDT.Columns.Add("PMC", typeof(string));
1761
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
1762
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
1763

    
1764
                // Set Vent/Drain Info
1765
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1766
                DataTable dt = DB.SelectVentDrainSetting();
1767
                foreach (DataRow row in dt.Rows)
1768
                {
1769
                    string groupID = row["GROUP_ID"].ToString();
1770
                    string desc = row["DESCRIPTION"].ToString();
1771
                    int index = Convert.ToInt32(row["INDEX"]);
1772
                    string name = row["NAME"].ToString();
1773

    
1774
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1775
                    if (ventDrainInfo == null)
1776
                    {
1777
                        ventDrainInfo = new VentDrainInfo(groupID);
1778
                        ventDrainInfo.Description = desc;
1779
                        VentDrainInfos.Add(ventDrainInfo);
1780
                    }
1781

    
1782
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1783
                    {
1784
                        Index = index,
1785
                        Name = name
1786
                    });
1787
                }
1788
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1789
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
1790

    
1791
                #region Keyword Info
1792
                KeywordInfo KeywordInfos = new KeywordInfo();
1793
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1794
                foreach (DataRow row in dtKeyword.Rows)
1795
                {
1796
                    int index = Convert.ToInt32(row["INDEX"]);
1797
                    string name = row["NAME"].ToString();
1798
                    string keyword = row["KEYWORD"].ToString();
1799

    
1800
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1801
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1802
                    {
1803
                        Index = index,
1804
                        Name = name,
1805
                        Keyword = keyword
1806
                    });
1807
                }
1808
                #endregion
1809

    
1810
                #region ValveGrouping Info
1811
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1812
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1813
                foreach (DataRow row in dtValveGroupung.Rows)
1814
                {
1815
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1816
                    {
1817
                        OID = row["OID"].ToString(),
1818
                        GroupType = row["GroupType"].ToString(),
1819
                        TagIdentifier = row["TagIdentifier"].ToString(),
1820
                        AttributeName = row["AttributeName"].ToString(),
1821
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1822
                    });
1823
                }
1824
                #endregion
1825

    
1826
                #region EquipmentNoPocket Info
1827
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
1828
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
1829
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
1830
                {
1831
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
1832
                    {
1833
                        Index = Convert.ToInt32(row["INDEX"]),
1834
                        Type = row["TYPE"].ToString(),
1835
                        Name = row["NAME"].ToString()
1836
                    });
1837
                }
1838
                #endregion
1839

    
1840
                #region EquipmentAirFinCooler Info
1841
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
1842
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
1843
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
1844
                {
1845
                    //pump type도 마찬가지?
1846
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
1847
                    {
1848
                        Type = row["Type"].ToString(),
1849
                        Name = row["Name"].ToString()
1850
                    });
1851
                }
1852
                #endregion
1853

    
1854
                // key = 미입력 branch
1855
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1856
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1857
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
1858
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
1859
                foreach (PSNItem PSNItem in PSNItems)
1860
                {
1861
                    try
1862
                    {
1863
                        int psnOrder = 0;
1864
                        int index = 0;
1865
                        bool bPSNStart = true;
1866
                        string sPSNData = string.Empty;
1867
                        bool bVentDrain = false;
1868

    
1869
                        List<Group> Groups = PSNItem.Groups;
1870
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
1871
                        List<Item> valveGroupingItem = new List<Item>();
1872

    
1873
                        //VentDrain 검사
1874
                        if (PSNItem.Groups.Count.Equals(1))
1875
                        {
1876
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1877
                            for (int g = 0; g < Groups.Count; g++)
1878
                            {
1879
                                Group group = Groups[g];
1880
                                for (int i = 0; i < group.Items.Count; i++)
1881
                                {
1882
                                    Item item = group.Items[i];
1883
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1884
                                    {
1885
                                        if (endInfos.Contains(ventDrainInfo))
1886
                                            continue;
1887

    
1888
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1889
                                        {
1890
                                            endInfos.Add(ventDrainInfo);
1891
                                            continue;
1892
                                        }
1893

    
1894
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1895
                                        {
1896
                                            bVentDrain = true;
1897
                                            break;
1898
                                        }
1899
                                    }
1900

    
1901
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1902
                                        break;
1903
                                }
1904

    
1905
                                if (!bVentDrain)
1906
                                {
1907
                                    endInfos = new List<VentDrainInfo>();
1908
                                    for (int i = 0; i < group.Items.Count; i++)
1909
                                    {
1910
                                        Item item = group.Items[group.Items.Count - i - 1];
1911
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1912
                                        {
1913
                                            if (endInfos.Contains(ventDrainInfo))
1914
                                                continue;
1915

    
1916
                                            if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1917
                                            {
1918
                                                endInfos.Add(ventDrainInfo);
1919
                                                continue;
1920
                                            }
1921

    
1922
                                            if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1923
                                            {
1924
                                                bVentDrain = true;
1925
                                                break;
1926
                                            }
1927
                                        }
1928

    
1929
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1930
                                            break;
1931
                                    }
1932
                                }
1933
                            }
1934
                        }
1935

    
1936
                        try
1937
                        {
1938
                            foreach (Group group in PSNItem.Groups)
1939
                            {
1940
                                foreach (Item item in group.Items)
1941
                                {
1942
                                    string VgTag = string.Empty;
1943
                                    
1944
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
1945
                                    {
1946
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
1947
                                        string value = string.Empty;
1948

    
1949
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection")
1950
                                            value = "NoSelection";
1951
                                        else
1952
                                            value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
1953

    
1954
                                        if (valveitem.GroupType == "Scope Break")
1955
                                            VgTag = "Scope Break";
1956
                                        else
1957
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
1958

    
1959
                                    }
1960

    
1961
                                    string PathitemUID = string.Empty;
1962
                                    if (item.BranchItems.Count == 0)
1963
                                    {
1964
                                        PathitemUID = item.UID;
1965
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1966
                                        CreateSequenceDataDataRow(PathitemUID);
1967
                                        index++;
1968
                                    }
1969
                                    else
1970
                                    {
1971
                                        PathitemUID = item.UID + "_L1";
1972
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1973
                                        CreateSequenceDataDataRow(PathitemUID);
1974
                                        index++;
1975
                                        for (int i = 0; i < item.BranchItems.Count; i++)
1976
                                        {
1977
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1978
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1979
                                            index++;
1980

    
1981
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1982
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1983
                                            index++;
1984

    
1985
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1986
                                                startBranchDic.Add(item.BranchItems[i], item);
1987
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1988
                                                endBranchDic.Add(item.BranchItems[i], item);
1989
                                        }
1990
                                    }
1991

    
1992
                                    if (bPSNStart)
1993
                                    {
1994
                                        CreatePipeSystemNetworkDataRow();
1995
                                        sPSNData = item.TopologyData;
1996
                                        psnOrder++;
1997
                                        bPSNStart = false;
1998
                                    }
1999
                                    else
2000
                                    {
2001
                                        if (item.TopologyData != sPSNData)
2002
                                        {
2003
                                            CreatePipeSystemNetworkDataRow();
2004
                                            sPSNData = item.TopologyData;
2005
                                            psnOrder++;
2006
                                        }
2007
                                    }
2008

    
2009
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
2010
                                    {
2011
                                        DataRow newRow = pathItemsDT.NewRow();
2012

    
2013
                                        if (itemType == "Nozzles")
2014
                                        {
2015
                                            newRow["Equipment_OID"] = item.Equipment != null ? item.Equipment.UID : "";
2016
                                        }
2017

    
2018
                                        newRow["OID"] = itemOID;
2019
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2020
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
2021
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2022
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2023
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
2024
                                        newRow["ITEMTAG"] = GetItemTag(item);
2025
                                        newRow["Class"] = GetClass(item, itemOID);
2026
                                        string subClass = GetSubClass(item, itemOID);
2027
                                        newRow["SubClass"] = subClass;
2028

    
2029
                                        if (item.ItemType == ItemType.Symbol)
2030
                                            newRow["TYPE"] = item.ID2DBName;
2031
                                        else if (item.ItemType == ItemType.Line)
2032
                                            newRow["TYPE"] = item.ID2DBType;
2033
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2034

    
2035
                                        // NPD
2036
                                        if (item.LineNumber != null)
2037
                                        {
2038
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2039
                                            if (attribute != null)
2040
                                                newRow["NPD"] = attribute.Value;
2041
                                        }
2042
                                        else
2043
                                            newRow["NPD"] = null;
2044

    
2045
                                        newRow["GROUPTAG"] = GROUPTAG;
2046
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2047
                                        if (branchItem == null)
2048
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2049
                                        else
2050
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2051

    
2052
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2053
                                        newRow["EGTConnectedPoint"] = 0;
2054
                                        pathItemsDT.Rows.Add(newRow);
2055
                                    }
2056

    
2057

    
2058
                                    void CreateSequenceDataDataRow(string itemOID)
2059
                                    {
2060
                                        DataRow newRow = sequenceDataDT.NewRow();
2061
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2062
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2063
                                        newRow["PathItem_OID"] = itemOID;
2064
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2065

    
2066
                                        sequenceDataDT.Rows.Add(newRow);
2067
                                    }
2068

    
2069
                                    void CreatePipeSystemNetworkDataRow()
2070
                                    {
2071
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2072
                                        string FluidCode = string.Empty;
2073
                                        if (lineNumber != null)
2074
                                        {
2075
                                            List<Attribute> att = lineNumber.Attributes;
2076
                                            if (att != null)
2077
                                            {
2078
                                                List<string> oid = new List<string>();
2079
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2080
                                                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;
2081
                                                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;
2082
                                                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;
2083
                                                //InsulationPurpose
2084
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2085
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2086

    
2087
                                                string PipeSystem_OID = string.Join("-", oid);
2088

    
2089
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2090
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2091

    
2092
                                                string OID = string.Join("-", oid);
2093
                                                string FluidCodeGL = string.Empty;
2094
                                                string PMCGL = string.Empty;
2095

    
2096

    
2097
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2098
                                                {
2099
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2100
                                                    newPipelineRow["OID"] = OID;
2101
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2102
                                                    newPipelineRow["FLUID"] = FluidCode;
2103
                                                    newPipelineRow["PMC"] = PMC;
2104
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2105
                                                    newPipelineRow["INSULATION"] = INSULATION;
2106
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2107
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2108
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2109
                                                    pipelineDT.Rows.Add(newPipelineRow);
2110
                                                }
2111

    
2112
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2113
                                                {
2114
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2115
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2116
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2117
                                                    newPipesystemRow["FLUID"] = FluidCode;
2118
                                                    newPipesystemRow["PMC"] = PMC;
2119
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2120
                                                    string GroundLevel = string.Empty;
2121
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2122
                                                    {
2123
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2124
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2125
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2126
                                                            GroundLevel = "AG";
2127
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2128
                                                            GroundLevel = "UG";
2129
                                                        else
2130
                                                            GroundLevel = "AG_UG";
2131
                                                    }
2132
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2133

    
2134
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2135
                                                }
2136
                                            }
2137
                                        }
2138

    
2139
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2140
                                        newRow["OID"] = PSNItem.PSN_OID();
2141

    
2142
                                        newRow["OrderNumber"] = psnOrder;
2143
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2144
                                        PSNItem.KeywordInfos = KeywordInfos;
2145
                                        PSNItem.Nozzle = Nozzle;
2146

    
2147
                                        string FromType = string.Empty;
2148
                                        Item From_item = new Item();
2149

    
2150
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
2151
                                        string status = string.Empty;
2152
                                        if (psnOrder == 0)
2153
                                        {
2154
                                            status = PSNItem.Status;
2155
                                        }
2156

    
2157
                                        if (PSNItem.IsKeyword)
2158
                                        {
2159
                                            PSNItem.StartType = PSNType.Equipment;
2160
                                        }
2161
                                        string ToType = string.Empty;
2162
                                        Item To_item = new Item();
2163
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
2164
                                        if (PSNItem.IsKeyword)
2165
                                        {
2166
                                            PSNItem.EndType = PSNType.Equipment;
2167
                                        }
2168

    
2169
                                        //if (Groups.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
2170
                                        //{
2171
                                        if (!string.IsNullOrEmpty(PSNItem.Status))
2172
                                            status += PSNItem.Status;
2173
                                        //}
2174

    
2175
                                        newRow["FROM_DATA"] = FROM_DATA;
2176
                                        newRow["TO_DATA"] = TO_DATA;
2177
                                        newRow["Type"] = PSNItem.GetPSNType();
2178

    
2179
                                        if (psnOrder > 0)
2180
                                        {
2181
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2182
                                            if (!string.IsNullOrEmpty(PSNItem.Status))
2183
                                            {//status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2184
                                                if (dr["Status"].ToString().Contains(PSNItem.Status))
2185
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
2186
                                                else if (dr["Status"].ToString().Contains(PSNItem.Status.Remove(0, 2)))
2187
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
2188

    
2189
                                            }
2190

    
2191
                                            if (dr != null)
2192
                                            {
2193
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2194
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2195
                                                newRow["Type"] = dr.Field<string>("Type");
2196
                                            }
2197
                                        }
2198

    
2199
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2200
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
2201
                                        {
2202
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
2203
                                            int cnt = matches.Count;
2204
                                            if (cnt > 1)
2205
                                                status.Replace(", Missing LineNumber_1", string.Empty);
2206
                                        }
2207
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2208
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
2209

    
2210

    
2211
                                        newRow["IsValid"] = PSNItem.IsValid;
2212
                                        newRow["Status"] = status;
2213
                                        newRow["PBS"] = PSNItem.GetPBSData();
2214

    
2215
                                        List<string> drawingNames = new List<string>();
2216
                                        foreach (Group _group in PSNItem.Groups)
2217
                                        {
2218
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2219
                                            {
2220
                                                if (drawingNames.Count == 0)
2221
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2222
                                                else
2223
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2224
                                                drawingNames.Add(_group.Document.DrawingName);
2225
                                            }
2226
                                        }
2227

    
2228
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2229
                                        if (bVentDrain)
2230
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2231
                                        else
2232
                                            newRow["IncludingVirtualData"] = "No";
2233
                                        //    return;
2234
                                        //newRow["IncludingVirtualData"] = "No";
2235
                                        newRow["PSNAccuracy"] = "100";
2236

    
2237
                                        string Pocket = "No";
2238
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2239
                                        if (Condition.Equals("Flare"))
2240
                                            Pocket = "Yes";
2241

    
2242
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null) 
2243
                                        {
2244
                                          //  string itemName = From_item.Name;
2245
                                            Equipment Equipment = From_item.Equipment;
2246
                                      
2247
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2248
                                          
2249

    
2250
                                            if (nopocket != null)
2251
                                            {
2252
                                                DataRow bNozzle = null;
2253
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2254
                                                {
2255
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2256
                                                    if (drNozzle != null)
2257
                                                    {
2258
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2259
                                                        {
2260
                                                            bNozzle = drNozzle;
2261
                                                        }
2262

    
2263
                                                        if (bNozzle == null)
2264
                                                        {
2265
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2266

    
2267
                                                            if (drNozzle != null)
2268
                                                            {
2269
                                                                bNozzle = drNozzle;
2270
                                                                foreach (DataRow it in nozzleRows)
2271
                                                                {
2272
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2273
                                                                    {
2274
                                                                        bNozzle = null;
2275
                                                                        break;
2276
                                                                    }
2277
                                                                }
2278
                                                            }
2279
                                                        }
2280
                                                    }
2281

    
2282
                                                    if (bNozzle != null)
2283
                                                        Pocket = "Yes";
2284
                                                }
2285
                                                else
2286
                                                    Pocket = "Yes";
2287
                                            }
2288
                                        }
2289
                                        
2290
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null) //To는 전체
2291
                                        {
2292
                                           // string itemName = To_item.Name;
2293
                                            Equipment Equipment = To_item.Equipment;
2294
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2295
                                            if (nopocket != null)
2296
                                            {
2297
                                                DataRow bNozzle = null;
2298
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2299
                                                {
2300
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2301
                                                    if(drNozzle != null)
2302
                                                    {
2303
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2304
                                                        {
2305
                                                            bNozzle = drNozzle;
2306
                                                        }
2307

    
2308
                                                        if (bNozzle == null)
2309
                                                        {
2310
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2311

    
2312
                                                            if (drNozzle != null)
2313
                                                            {
2314
                                                                bNozzle = drNozzle;
2315
                                                                foreach (DataRow it in nozzleRows)
2316
                                                                {
2317
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2318
                                                                    {
2319
                                                                        bNozzle = null;
2320
                                                                        break;
2321
                                                                    }
2322
                                                                }
2323
                                                            }
2324
                                                        }
2325
                                                    }                                                   
2326

    
2327
                                                    if (bNozzle != null)
2328
                                                        Pocket = "Yes";
2329
                                                }
2330
                                                else
2331
                                                    Pocket = "Yes";
2332
                                            }
2333
                                        }
2334
                                        
2335
                                        newRow["Pocket"] = Pocket;
2336
                                        string AFC = "P2";
2337
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2338
                                        {
2339
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2340
                                                AFC = "P1";
2341
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2342
                                                newRow["PUMP"] = "PUMP";
2343
                                        }
2344

    
2345
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2346
                                        {
2347
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2348
                                                AFC = "P1";
2349
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2350
                                                newRow["PUMP"] = "PUMP";
2351
                                        }
2352

    
2353
                                        newRow["AFC"] = AFC;
2354

    
2355
                                        newRow["EGTag"] = string.Empty;
2356
                                        newRow["HasMLTags"] = "False";
2357
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2358
                                    }
2359
                                }
2360

    
2361
                            }
2362
                        
2363

    
2364
                        }
2365
                        catch (Exception ex)
2366
                        {
2367
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2368
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2369
                        }
2370

    
2371
                        //TopologySet 관련
2372
                        foreach (Topology topology in PSNItem.Topologies)
2373
                        {
2374
                            DataRow newRow = topologySetDT.NewRow();
2375
                            newRow["OID"] = topology.FullName;
2376
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
2377
                            if (bVentDrain)
2378
                                newRow["SubType"] = "Vent_Drain";
2379
                            else
2380
                                newRow["SubType"] = null;
2381
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
2382
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
2383
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
2384
                            newRow["TailItemSPID"] = topology.Items.First().UID;
2385
                            topologySetDT.Rows.Add(newRow);
2386
                        }
2387

    
2388
                    }
2389
                    catch (Exception ee)
2390
                    {
2391

    
2392
                    }
2393
                }
2394

    
2395

    
2396
                foreach (var item in startBranchDic)
2397
                {
2398
                    string uid = item.Key.UID;
2399
                    string topologyName = item.Value.Topology.FullName;
2400
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2401

    
2402
                    if (rows.Length == 1)
2403
                    {
2404
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2405
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2406
                    }
2407
                    else if (rows.Length > 1)
2408
                    {
2409
                        DataRow targetRow = null;
2410
                        int index = int.MaxValue;
2411
                        foreach (DataRow row in rows)
2412
                        {
2413
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2414
                            if (split.StartsWith("L"))
2415
                            {
2416
                                int num = Convert.ToInt32(split.Remove(0, 1));
2417
                                if (index > num)
2418
                                {
2419
                                    index = num;
2420
                                    targetRow = row;
2421
                                }
2422
                            }
2423
                        }
2424

    
2425
                        if (targetRow != null)
2426
                        {
2427
                            targetRow["BranchTopologySet_OID"] = topologyName;
2428
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2429
                        }
2430
                    }
2431
                }
2432

    
2433
                foreach (var item in endBranchDic)
2434
                {
2435
                    string uid = item.Key.UID;
2436
                    string topologyName = item.Value.Topology.FullName;
2437
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2438
                    if (rows.Length == 1)
2439
                    {
2440
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2441
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2442
                    }
2443
                    else if (rows.Length > 1)
2444
                    {
2445
                        DataRow targetRow = null;
2446
                        int index = int.MinValue;
2447
                        foreach (DataRow row in rows)
2448
                        {
2449
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2450
                            if (split.StartsWith("L"))
2451
                            {
2452
                                int num = Convert.ToInt32(split.Remove(0, 1));
2453
                                if (index < num)
2454
                                {
2455
                                    index = num;
2456
                                    targetRow = row;
2457
                                }
2458
                            }
2459
                        }
2460

    
2461
                        if (targetRow != null)
2462
                        {
2463
                            targetRow["BranchTopologySet_OID"] = topologyName;
2464
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2465
                        }
2466
                    }
2467
                }
2468

    
2469
                PathItems = pathItemsDT;
2470
                SequenceData = sequenceDataDT;
2471
                PipeSystemNetwork = pipeSystemNetworkDT;
2472
                TopologySet = topologySetDT;
2473
                PipeLine = pipelineDT;
2474
                PipeSystem = pipesystemDT;
2475
            }
2476
            catch (Exception ex)
2477
            {
2478
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2479
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2480
            }
2481
        }
2482

    
2483
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2484
        {
2485
            foreach (double lacc in lstAcc)
2486
            {
2487
                acc *= lacc;
2488
            }
2489
            return acc;
2490
        }
2491

    
2492
        private void UpdateSubType()
2493
        {
2494
            try
2495
            {
2496
                foreach (PSNItem PSNItem in PSNItems)
2497
                {
2498
                    if (PSNItem.IsBypass)
2499
                    {
2500
                        foreach (Topology topology in PSNItem.Topologies)
2501
                        {
2502
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2503
                            if (rows.Length.Equals(1))
2504
                                rows.First()["SubType"] = "Bypass";
2505
                        }
2506
                    }
2507

    
2508
                    if (PSNItem.StartType == PSNType.Header)
2509
                    {
2510
                        Topology topology = PSNItem.Topologies.First();
2511
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2512
                        if (rows.Length.Equals(1))
2513
                            rows.First()["SubType"] = "Header";
2514
                    }
2515
                    else if (PSNItem.EndType == PSNType.Header)
2516
                    {
2517
                        Topology topology = PSNItem.Topologies.Last();
2518
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2519
                        if (rows.Length.Equals(1))
2520
                            rows.First()["SubType"] = "Header";
2521
                    }
2522
                }
2523

    
2524

    
2525
                foreach (Topology topology in Topologies)
2526
                {
2527
                    try
2528
                    {
2529
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2530

    
2531
                        if (rows.Count() > 0)
2532
                        {
2533
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2534
                            {
2535
                                if (topology.Items == null)
2536
                                    continue;
2537

    
2538
                                Item firstItem = topology.Items.First();
2539
                                Item lastItem = topology.Items.Last();
2540

    
2541
                                List<Relation> relations = new List<Relation>();
2542

    
2543
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2544
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2545

    
2546
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2547
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2548

    
2549
                                if (relations.Count > 0)
2550
                                    rows.First()["SubType"] = "OtherSystem";
2551
                            }
2552
                        }
2553
                    }
2554
                    catch (Exception ex)
2555
                    {
2556

    
2557
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2558
                    }
2559
                }
2560

    
2561
                foreach (DataRow row in TopologySet.Rows)
2562
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
2563
                        row["SubType"] = "Normal";
2564
            }
2565
            catch (Exception ex)
2566
            {
2567
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2568
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2569
            }
2570
        }
2571

    
2572
        private bool IsBypass(PSNItem PSNItem)
2573
        {
2574
            bool bResult = false;
2575

    
2576
            if (PSNItem.GetPSNType() == "B2B")
2577
            {
2578
                Group firstGroup = PSNItem.Groups.First();
2579
                Group lastGroup = PSNItem.Groups.Last();
2580
                Item firstItem = firstGroup.Items.First();
2581
                Item lastItem = lastGroup.Items.Last();
2582

    
2583
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
2584
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
2585

    
2586
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
2587
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
2588
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
2589
                    bResult = true;
2590
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
2591
                    bResult = true;
2592
            }
2593

    
2594
            Item GetConnectedItemByPSN(Item item)
2595
            {
2596
                Item result = null;
2597

    
2598
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
2599
                if (relation != null)
2600
                    result = relation.Item;
2601

    
2602

    
2603
                return result;
2604
            }
2605

    
2606
            return bResult;
2607
        }
2608

    
2609
        private void DeleteVentDrain()
2610
        {
2611
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
2612

    
2613
            foreach (DataRow dataRow in ventdrainRows)
2614
            {
2615
                dataRow.Delete();
2616
            }
2617
        }
2618

    
2619
        private void UpdateAccuracy()
2620
        {
2621
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
2622
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
2623
            List<double> lstAcc = null;
2624
            string Status = string.Empty;
2625

    
2626
            foreach (DataRow dataRow in statusRows)
2627
            {
2628
                lstAcc = new List<double>();
2629
                Status = dataRow.Field<string>("Status");
2630
                if (!string.IsNullOrEmpty(Status))
2631
                {
2632
                    string[] arrStatus = Status.Split(',');
2633
                    foreach (string arrstr in arrStatus)
2634
                    {
2635
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
2636
                            lstAcc.Add(0.75);
2637

    
2638
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2639
                            lstAcc.Add(0.7);
2640

    
2641
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2642
                            lstAcc.Add(0.5);
2643

    
2644
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2645
                            lstAcc.Add(0.65);
2646

    
2647
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2648
                            lstAcc.Add(0.6);
2649
                    }
2650
                }
2651

    
2652
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
2653
                if (PSNAccuracy == "100")
2654
                    PSNAccuracy = "1";
2655

    
2656
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
2657
                //if (PSNAccuracy != "100")
2658
                //{
2659
                //    //dataRow["IncludingVirtualData"] = "No";
2660
                dataRow["PSNAccuracy"] = PSNAccuracy;
2661
                //}
2662
            }
2663
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
2664
            foreach (DataRow dr in dt.Rows)
2665
            {
2666
                string oid = dr.Field<string>("OID");
2667
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
2668
                double totalDdr = 0;
2669
                foreach (DataRow ddr in select)
2670
                {
2671
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
2672
                    if (acc == 100) acc = 1;
2673
                    if (totalDdr == 0) totalDdr = acc;
2674
                    else totalDdr *= acc;
2675
                }
2676

    
2677
                totalDdr *= 100;
2678

    
2679
                if (totalDdr != 100)
2680
                {
2681
                    foreach (DataRow ddr in select)
2682
                    {
2683
                        ddr["IncludingVirtualData"] = "Yes";
2684
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2685
                    }
2686
                }
2687
                else
2688
                {
2689
                    foreach (DataRow ddr in select)
2690
                    {
2691
                        ddr["IncludingVirtualData"] = "No";
2692
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2693
                    }
2694
                }
2695
            }
2696

    
2697
        }
2698

    
2699
        private void UpdateKeywordForPSN()
2700
        {
2701
            #region Keyword Info
2702
            KeywordInfo KeywordInfos = new KeywordInfo();
2703
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2704
            foreach (DataRow row in dtKeyword.Rows)
2705
            {
2706
                int index = Convert.ToInt32(row["INDEX"]);
2707
                string name = row["NAME"].ToString();
2708
                string keyword = row["KEYWORD"].ToString();
2709

    
2710
                //KeywordInfo keywordInfo = new KeywordInfo();   
2711
                KeywordInfos.KeywordItems.Add(new KeywordItem()
2712
                {
2713
                    Index = index,
2714
                    Name = name,
2715
                    Keyword = keyword
2716
                });
2717
            }
2718
            #endregion
2719

    
2720
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
2721
            foreach (DataRow dataRow in endofHeaderRows)
2722
            {
2723
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2724

    
2725
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
2726
                {
2727
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2728
                    DataRow dr = pathItemRows.First();
2729
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
2730
                    dr["TYPE"] = "End";
2731
                    dr["ITEMTAG"] = "ENDOFHEADER";
2732
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2733
                }
2734

    
2735
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
2736
                {
2737
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2738
                    DataRow dr = pathItemRows.Last();
2739
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
2740
                    dr["TYPE"] = "End";
2741
                    dr["ITEMTAG"] = "ENDOFHEADER";
2742
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2743
                }
2744
            }
2745

    
2746
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2747
            {
2748
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
2749
                foreach (DataRow dataRow in keywordRows)
2750
                {
2751
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2752

    
2753
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
2754
                    {
2755
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2756

    
2757
                        //
2758
                        //if(.)
2759
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
2760
                        {
2761
                            DataRow dr = pathItemRows.First();
2762
                            //dr["CLASS"] = ""; //Type
2763
                            dr["TYPE"] = "End";
2764
                            dr["ITEMTAG"] = keyitem.Keyword;
2765
                            dr["DESCRIPTION"] = keyitem.Keyword;
2766
                        }
2767

    
2768
                    }
2769

    
2770
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
2771
                    {
2772
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2773

    
2774
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
2775
                        {
2776
                            DataRow dr = pathItemRows.Last();
2777
                            //dr["CLASS"] = ""; //Type
2778
                            dr["TYPE"] = "End";
2779
                            dr["ITEMTAG"] = keyitem.Keyword;
2780
                            dr["DESCRIPTION"] = keyitem.Keyword;
2781
                            //dr.Field<string>("Type")
2782
                        }
2783

    
2784
                    }
2785
                }
2786
            }
2787
        }
2788

    
2789
        private void UpdateErrorForPSN()
2790
        {
2791
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
2792
            foreach (DataRow dataRow in errorRows)
2793
            {
2794
                try
2795
                {
2796
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2797
                    bool change = false;
2798
                    bool bCheck = false;
2799
                    int bCount = 0;
2800
                    if (!PSNItem.EnableType(PSNItem.StartType))
2801
                    {
2802
                        change = true;
2803
                        bCheck = change;
2804
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2805
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2806

    
2807
                        Item item = PSNItem.Groups.First().Items.First();
2808
                        try
2809
                        {
2810
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2811

    
2812
                            tieInPointIndex++;
2813

    
2814

    
2815
                            if (item.ItemType == ItemType.Line)
2816
                            {
2817
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2818
                                bCount = 2;
2819

    
2820
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2821
                                {
2822
                                    loopRow["FROM_DATA"] = FROM_DATA;
2823
                                    if (loopRow.Field<string>("OrderNumber") == "0")
2824
                                    {
2825
                                        string status = loopRow.Field<string>("Status");
2826
                                        //string isvali
2827
                                        if (string.IsNullOrEmpty(status))
2828
                                            status = "Line Disconnected";
2829
                                        else if (!status.Contains("Line Disconnected"))
2830
                                            status += ", Line Disconnected";
2831
                                        loopRow["Status"] = status;
2832
                                        if (!string.IsNullOrEmpty(status))
2833
                                            loopRow["IsValid"] = "Error";
2834
                                    }
2835
                                }
2836
                            }
2837
                            else
2838
                            {
2839
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
2840
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
2841

    
2842
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2843
                                   
2844
                                
2845
                                bCount = 3;
2846
                            }
2847

    
2848
                            PSNItem.StartType = PSNType.Equipment;
2849
                        }
2850
                        catch (Exception ex)
2851
                        {
2852
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2853
                            return;
2854
                        }
2855
                    }
2856

    
2857
                    if (!PSNItem.EnableType(PSNItem.EndType))
2858
                    {
2859
                        change = true;
2860
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2861
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
2862
                        DataRow dr = pathItemRows.Last();
2863
                        if (change)
2864
                            dr = pathItemRows[pathItemRows.Count() - bCount];
2865

    
2866
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2867

    
2868
                        Item item = PSNItem.Groups.Last().Items.Last();
2869
                        try
2870
                        {
2871
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2872

    
2873
                            if (item.ItemType == ItemType.Line)
2874
                            {
2875
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2876
                                {
2877
                                    loopRow["TO_DATA"] = TO_DATA;
2878
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
2879
                                    {
2880
                                        string status = loopRow.Field<string>("Status");
2881
                                        if (string.IsNullOrEmpty(status))
2882
                                            status = "Line Disconnected";
2883
                                        else if (!status.Contains("Line Disconnected"))
2884
                                            status += ", Line Disconnected";
2885
                                        loopRow["Status"] = status;
2886
                                        if (!string.IsNullOrEmpty(status))
2887
                                            loopRow["IsValid"] = "Error";
2888
                                    }
2889
                                }
2890
                            }
2891

    
2892
                            tieInPointIndex++;
2893

    
2894
                            if (item.ItemType == ItemType.Line)
2895
                            {
2896
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
2897
                            }
2898
                            else
2899
                            {
2900
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
2901
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
2902
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
2903
                            }
2904

    
2905
                            PSNItem.EndType = PSNType.Equipment;
2906
                        }
2907
                        catch (Exception ex)
2908
                        {
2909
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2910
                            return;
2911
                        }
2912
                    }
2913

    
2914
                    dataRow["Type"] = PSNItem.GetPSNType();
2915
                    if (change)
2916
                    {
2917
                        int rowIndex = 0;
2918
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2919
                        {
2920
                            DataRow row = PathItems.Rows[i];
2921
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
2922
                                continue;
2923
                            string sequenceData = row["SequenceData_OID"].ToString();
2924
                            string[] split = sequenceData.Split(new char[] { '_' });
2925

    
2926
                            StringBuilder sb = new StringBuilder();
2927
                            for (int j = 0; j < split.Length - 1; j++)
2928
                                sb.Append(split[j] + "_");
2929
                            sb.Append(rowIndex++);
2930
                            row["SequenceData_OID"] = sb.ToString();
2931

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

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

    
2937
                            if (seqItemRows == null)
2938
                            {
2939
                                DataRow newRow = SequenceData.NewRow();
2940
                                newRow["OID"] = sb.ToString();
2941
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2942
                                newRow["PathItem_OID"] = row["OID"];
2943
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2944
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2945
                            }
2946
                            else
2947
                            {
2948
                                seqItemRows["OID"] = sb.ToString();
2949
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2950
                                seqItemRows["PathItem_OID"] = row["OID"];
2951
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2952
                            }
2953
                        }
2954
                    }
2955

    
2956
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
2957
                    {
2958
                        DataRow newRow = PathItems.NewRow();
2959
                        newRow["OID"] = Guid.NewGuid().ToString();
2960
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2961
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2962
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2963
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2964
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
2965
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
2966
                        newRow["DESCRIPTION"] = DATA;
2967
                        newRow["Class"] = "End of line terminator";
2968
                        newRow["SubClass"] = "End of line terminator";
2969
                        newRow["TYPE"] = "End";
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
                    DataRow createLineRow(DataRow itemRow)
2980
                    {
2981
                        DataRow newRow = PathItems.NewRow();
2982
                        newRow["OID"] = Guid.NewGuid().ToString();
2983
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2984
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2985
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2986
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2987
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
2988
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2989
                        newRow["Class"] = itemRow["Class"];
2990
                        newRow["SubClass"] = itemRow["SubClass"];
2991
                        newRow["TYPE"] = itemRow["TYPE"];
2992
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2993
                        newRow["NPD"] = itemRow["NPD"];
2994
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2995
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2996
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2997
                        newRow["EGTConnectedPoint"] = "0";
2998
                        return newRow;
2999
                    }
3000
                }
3001
                catch (Exception ex)
3002
                {
3003

    
3004
                }
3005
            }
3006
        }
3007

    
3008
        private void InsertTeePSN()
3009
        {
3010
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
3011
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
3012
            bool change = false;
3013
            foreach (DataRow dataRow in branchRows)
3014
            {
3015
                try
3016
                {
3017
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3018
                    change = false;
3019

    
3020
                    if (PSNItem.StartType == PSNType.Branch)
3021
                    {
3022
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3023
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3024
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3025
                        try
3026
                        {
3027
                            if (Teeitem.ItemType == ItemType.Line)
3028
                            {
3029
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3030
                                {
3031
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3032
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3033
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3034
                                    change = true;
3035
                                }
3036

    
3037
                            }
3038
                        }
3039
                        catch (Exception ex)
3040
                        {
3041
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3042
                            return;
3043
                        }
3044
                    }
3045

    
3046
                    if (PSNItem.EndType == PSNType.Branch)
3047
                    {
3048
                        //change = true;
3049
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3050

    
3051
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3052

    
3053
                        DataRow dr = pathItemRows.Last();
3054
                        if (change)
3055
                            dr = pathItemRows[pathItemRows.Count() - 2];
3056

    
3057
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3058

    
3059
                        try
3060
                        {
3061
                            if (Teeitem.ItemType == ItemType.Line)
3062
                            {
3063
                                if (dr.Field<string>("SubClass") != "Tee")
3064
                                {
3065
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3066
                                    change = true;
3067
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3068
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3069
                                }
3070

    
3071
                            }
3072
                        }
3073
                        catch (Exception ex)
3074
                        {
3075
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3076
                            return;
3077
                        }
3078
                    }
3079

    
3080
                    if (change)
3081
                    {
3082
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3083
                        int rowIndex = 0;
3084
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3085
                        {
3086
                            DataRow row = PathItems.Rows[i];
3087
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3088
                                continue;
3089
                            string sequenceData = row["SequenceData_OID"].ToString();
3090
                            string[] split = sequenceData.Split(new char[] { '_' });
3091

    
3092
                            StringBuilder sb = new StringBuilder();
3093
                            for (int j = 0; j < split.Length - 1; j++)
3094
                                sb.Append(split[j] + "_");
3095
                            sb.Append(rowIndex++);
3096
                            row["SequenceData_OID"] = sb.ToString();
3097

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

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

    
3103
                            if (seqItemRows == null)
3104
                            {
3105
                                DataRow newRow = SequenceData.NewRow();
3106
                                newRow["OID"] = sb.ToString();
3107
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3108
                                newRow["PathItem_OID"] = row["OID"];
3109
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3110
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3111
                            }
3112
                            else
3113
                            {
3114
                                seqItemRows["OID"] = sb.ToString();
3115
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3116
                                seqItemRows["PathItem_OID"] = row["OID"];
3117
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3118
                            }
3119
                        }
3120
                    }
3121

    
3122
                    DataRow createTeeRow(DataRow itemRow)
3123
                    {
3124
                        DataRow newRow = PathItems.NewRow();
3125
                        newRow["OID"] = Guid.NewGuid().ToString();
3126
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3127
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3128
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3129
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3130
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3131
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3132
                        newRow["DESCRIPTION"] = "";
3133
                        newRow["Class"] = "Branch";
3134
                        newRow["SubClass"] = "Tee";
3135
                        newRow["TYPE"] = itemRow["TYPE"];
3136
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3137
                        newRow["NPD"] = itemRow["NPD"];
3138
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3139
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3140
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3141
                      
3142
                        newRow["EGTConnectedPoint"] = 0;
3143
                        return newRow;
3144
                    }
3145
                }
3146
                catch (Exception ex)
3147
                {
3148

    
3149
                }
3150
            }
3151
        }
3152
    }
3153

    
3154
    public class PSNItem
3155
    {
3156
        public PSNItem(int count, int Revision)
3157
        {
3158
            Groups = new List<Group>();
3159
            Topologies = new List<Topology>();
3160

    
3161
            Index = count + 1;
3162
            this.Revision = Revision;
3163
        }
3164

    
3165
        private int Revision;
3166
        public string UID { get; set; }
3167
        public List<Group> Groups { get; set; }
3168
        public List<Topology> Topologies { get; set; }
3169
        public PSNType StartType { get; set; }
3170
        public PSNType EndType { get; set; }
3171
        public int Index { get; set; }
3172
        public string IsValid { get; set; }
3173
        public bool IsKeyword { get; set; }
3174
        public string Status { get; set; }
3175
        public string IncludingVirtualData { get; set; }
3176
        public string PSNAccuracy { get; set; }
3177
        public KeywordInfo KeywordInfos = new KeywordInfo();
3178
        public DataTable Nozzle = new DataTable();
3179

    
3180
        public string PSN_OID()
3181
        {
3182
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
3183
        }
3184

    
3185
        public string GetPSNType()
3186
        {
3187
            string result = string.Empty;
3188

    
3189
            if (EnableType(StartType) && EnableType(EndType))
3190
            {
3191
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
3192
                    result = "E2E";
3193
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
3194
                    result = "B2B";
3195
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
3196
                    result = "HD2";
3197

    
3198
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
3199
                    result = "E2B";
3200
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
3201
                    result = "B2E";
3202

    
3203
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
3204
                    result = "HDB";
3205
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
3206
                    result = "HDB";
3207

    
3208
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
3209
                    result = "HDE";
3210
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
3211
                    result = "HDE";
3212
                else
3213
                    result = "Error";
3214
            }
3215
            else
3216
                result = "Error";
3217

    
3218
            return result;
3219

    
3220

    
3221
        }
3222

    
3223
        public bool EnableType(PSNType type)
3224
        {
3225
            bool result = false;
3226

    
3227
            if (type == PSNType.Branch ||
3228
                type == PSNType.Equipment ||
3229
                type == PSNType.Header)
3230
            {
3231
                result = true;
3232
            }
3233

    
3234
            return result;
3235
        }
3236

    
3237
        public bool IsBypass { get; set; }
3238

    
3239
        public string GetFromData(ref string Type, ref Item item)
3240
        {
3241
            Status = string.Empty;
3242
            string result = string.Empty;
3243
            if (IsKeyword)
3244
                IsKeyword = false;
3245
            try
3246
            {
3247
                item = Groups.First().Items.First();
3248

    
3249
                if (StartType == PSNType.Header)
3250
                    result = "ENDOFHEADER";
3251
                else if (StartType == PSNType.Branch)
3252
                {
3253
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3254
                    if (!item.MissingLineNumber2 && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3255
                        result = item.Relations.First().Item.LineNumber.Name;
3256
                    else
3257
                    {
3258
                        IsValid = "Error";
3259
                        Status += ", Missing LineNumber_2";
3260
                        result = "Empty LineNumber";
3261
                    }
3262

    
3263
                    //if (item.MissingLineNumber1)
3264
                    //{
3265
                    //    Status += ", Missing LineNumber_1";
3266
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3267

    
3268
                    //}
3269
                }
3270
                else if (StartType == PSNType.Equipment)
3271
                {
3272
                    if (Groups.First().Items.First().Equipment != null)
3273
                        result = Groups.First().Items.First().Equipment.ItemTag;
3274
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
3275

    
3276
                    if (drNozzle != null)
3277
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3278
                }
3279
                else
3280
                {
3281
                    IsValid = "Error";
3282
                    item = Groups.First().Items.First();
3283
                    if (item.ItemType == ItemType.Symbol)
3284
                    {
3285

    
3286
                        string keyword = string.Empty;
3287
                        keyword = GetFromKeywordData(ref Type, item);
3288

    
3289
                        if (string.IsNullOrEmpty(keyword))
3290
                        {
3291
                            if (item.ID2DBType.Contains("OPC's"))
3292
                                Status += ", OPC Disconnected";
3293
                            else
3294
                                Status += ", Missing ItemTag or Description";
3295

    
3296
                            result = item.ID2DBName;
3297
                        }
3298
                        else
3299
                        {
3300
                            result = keyword;
3301
                            IsKeyword = true;
3302
                            IsValid = string.Empty;
3303
                        }
3304

    
3305
                    }
3306
                    else if (item.ItemType == ItemType.Line)
3307
                    {
3308

    
3309
                        if (item.MissingLineNumber1)
3310
                        {
3311
                            IsValid = "Error";
3312
                            Status += ", Missing LineNumber_1";
3313
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3314
                        }
3315
                        else
3316
                            result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3317
                    }
3318
                    else
3319
                        result = "Unknown";
3320

    
3321
                }
3322
            }
3323
            catch (Exception ex)
3324
            {
3325

    
3326
            }
3327

    
3328
            return result;
3329
        }
3330

    
3331
        public string GetFromKeywordData(ref string Type, Item item)
3332
        {
3333
            string result = string.Empty;
3334

    
3335
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3336
            {
3337
                if (keyitem.Name.Equals(item.Name))
3338
                {
3339
                    result = keyitem.Keyword;
3340
                    Type = item.ID2DBType;
3341
                    break;
3342
                }
3343
            }
3344

    
3345
            return result;
3346
        }
3347

    
3348
        public string GetToKeywordData(ref string Type, Item item)
3349
        {
3350
            string result = string.Empty;
3351

    
3352
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3353
            {
3354
                if (keyitem.Name.Equals(item.Name))
3355
                {
3356
                    result = keyitem.Keyword;
3357
                    Type = item.ID2DBType;
3358
                    break;
3359
                }
3360
            }
3361
            return result;
3362
        }
3363

    
3364
        public string GetToData(ref string ToType, ref Item item)
3365
        {
3366
            string result = string.Empty;
3367
            Status = string.Empty;
3368

    
3369
            if (IsKeyword)
3370
                IsKeyword = false;
3371

    
3372
            item = Groups.Last().Items.Last();
3373

    
3374
            if (EndType == PSNType.Header)
3375
                result = "ENDOFHEADER";
3376
            else if (EndType == PSNType.Branch)
3377
            {
3378
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3379
                if (!item.MissingLineNumber2 && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3380
                    result = item.Relations.Last().Item.LineNumber.Name;
3381
                else
3382
                {
3383
                    IsValid = "Error";
3384
                    Status += ", Missing LineNumber_2";
3385
                    result = "Empty LineNumber";
3386
                }
3387

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

    
3393
                //}
3394
            }
3395
            else if (EndType == PSNType.Equipment)
3396
            {
3397
                if (Groups.Last().Items.Last().Equipment != null)
3398
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3399

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

    
3402
                if (drNozzle != null)
3403
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3404
            }
3405
            else
3406
            {
3407
                IsValid = "Error";
3408
                item = Groups.Last().Items.Last();
3409
                if (item.ItemType == ItemType.Symbol)
3410
                {
3411
                    string keyword = string.Empty;
3412
                    keyword = GetToKeywordData(ref ToType, item);
3413

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

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

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

    
3445

    
3446
            }
3447

    
3448

    
3449

    
3450
            return result;
3451
        }
3452

    
3453
        public string GetPBSData()
3454
        {
3455
            string result = string.Empty;
3456
            List<string> PBSList = new List<string>();
3457
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3458
            {
3459
                string attrValue = Settings.Default.PBSSettingValue;
3460

    
3461
                foreach (Group group in Groups)
3462
                {
3463
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3464
                    foreach (LineNumber lineNumber in lineNumbers)
3465
                    {
3466
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3467
                        if (attribute != null)
3468
                        {
3469
                            string value = attribute.Value;
3470
                            if (!PBSList.Contains(value))
3471
                                PBSList.Add(value);
3472
                        }
3473
                    }
3474
                }
3475
            }
3476
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3477
            {
3478
                string attrValue = Settings.Default.PBSSettingValue;
3479

    
3480
                foreach (Group group in Groups)
3481
                {
3482
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3483
                    foreach (Item item in items)
3484
                    {
3485
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3486
                        if (!PBSList.Contains(value))
3487
                            PBSList.Add(value);
3488
                    }
3489
                }
3490
            }
3491
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3492
            {
3493
                string attrValue = Settings.Default.PBSSettingValue;
3494

    
3495
                foreach (Group group in Groups)
3496
                {
3497
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3498
                    foreach (Document document in documents)
3499
                    {
3500
                        string name = document.DrawingName;
3501

    
3502
                        int startIndex = Settings.Default.PBSSettingStartValue;
3503
                        int endIndex = Settings.Default.PBSSettingEndValue;
3504

    
3505
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3506
                        if (!PBSList.Contains(subStr))
3507
                            PBSList.Add(subStr);
3508
                    }
3509
                }
3510
            }
3511
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3512
            {
3513
                foreach (Group group in Groups)
3514
                {
3515
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3516
                    foreach (Document document in documents)
3517
                    {
3518
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
3519
                        foreach (TextInfo textInfo in textInfos)
3520
                        {
3521
                            if (!PBSList.Contains(textInfo.Value))
3522
                                PBSList.Add(textInfo.Value);
3523
                        }
3524
                    }
3525
                }
3526
            }
3527

    
3528
            foreach (var item in PBSList)
3529
            {
3530
                if (string.IsNullOrEmpty(result))
3531
                    result = item;
3532
                else
3533
                    result += ", " + item;
3534
            }
3535
            return result;
3536
        }
3537
    }
3538
}
클립보드 이미지 추가 (최대 크기: 500 MB)