프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ 6805be6e

이력 | 보기 | 이력해설 | 다운로드 (199 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 PSN From/To Keyword & EndofHeader
244
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateKeywordForPSN ( 55 % )");
245
            UpdateKeywordForPSN(); 
246
          
247
            // Topology의 subtype을 update(bypass, Header, 등등) 
248
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateSubType ( 60 % )");
249
            UpdateSubType();
250

    
251
            // Vent/Drain PSN 데이터 제거
252
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  DeleteVentDrain ( 65 % )");
253
            DeleteVentDrain();
254

    
255
            // Update Error
256
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateErrorForPSN ( 70 % )");
257
            PathItemSorting();
258
            UpdateErrorForPSN();
259
            // Insert Tee
260
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  InsertTeePSN ( 75 % )");
261
            PathItemSorting();
262
            InsertTeePSN();
263

    
264
            // ValveGrouping            
265
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateValveGrouping ( 80 % )");
266
            PathItemSorting(); 
267
            UpdateValveGrouping();
268

    
269
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  PathItemSorting ( 85 % )");
270
            PathItemSorting();
271

    
272
            // AirFinCooler 
273
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAirFinCooler ( 90 % )");
274
            UpdateAirFinCooler();
275

    
276
            // 확도 계산
277
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAccuracy ( 95 % )");
278
            UpdateAccuracy();
279

    
280
            //UpdatePSNType();
281

    
282
        }
283

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

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

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

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

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

    
331
                        dtSequenceItems.Rows.Add(newRow);
332
                    }
333

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

    
339
                        foreach (DataColumn column in PathItems.Columns)
340
                            if (dtPathItems.Columns[column.ColumnName] != null)
341
                                newRow[column.ColumnName] = row[column.ColumnName];
342

    
343
                        dtPathItems.Rows.Add(newRow);
344
                    }
345
                }
346

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

    
377
                
378
                DataRow[] pumpRows = PipeSystemNetwork.Select("PUMP = 'PUMP'");
379
                Dictionary<string, string> eqkeyValuePairs = new Dictionary<string, string>();
380
                // 1, 2번
381
                foreach (DataRow dataRow in pumpRows) 
382
                {                  
383
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
384

    
385
                    string EGTAG = "EGTAG";
386
                   // string ItemTag = "ItemTag";
387
                    string EGFlowDirection = string.Empty;
388
                    string Prefix = string.Empty;
389
                    string SymbolName = string.Empty;
390

    
391
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
392
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
393
                    {
394
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
395
                        {
396
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
397
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
398
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null
399
                                   ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
400

    
401
                            SymbolName = PSNItem.Groups.First().Items.First().Equipment.Name;
402
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
403
                            EGFlowDirection = "O";
404
                        }                        
405
                    } 
406
                    
407
                    if(string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
408
                    {
409
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
410
                        {
411
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
412
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
413
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null
414
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
415

    
416
                            SymbolName = PSNItem.Groups.Last().Items.Last().Equipment.Name;
417
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
418
                            EGFlowDirection = "I";
419
                        }
420
                    }
421

    
422
                    //Attribute가 세팅되어있지 않다면
423
                    if (EGTAG.Equals("EGTAG"))
424
                    {
425
                        if (!eqkeyValuePairs.ContainsKey(SymbolName))
426
                        {
427
                            if (!string.IsNullOrEmpty(Prefix))
428
                            {
429
                                pumpTagNum++;
430
                                EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", pumpTagNum));
431
                                eqkeyValuePairs.Add(SymbolName, EGTAG);
432
                            }
433
                            else
434
                            {
435
                                eqkeyValuePairs.Add(SymbolName, SymbolName);
436
                            }
437
                        }
438
                        else
439
                        {
440
                            EGTAG = eqkeyValuePairs[SymbolName];
441
                        }
442
                    }
443
                    else
444
                    {
445
                        if (!string.IsNullOrEmpty(Prefix))
446
                            EGTAG = Prefix + "-" + EGTAG;
447
                    }
448

    
449

    
450
                    foreach (DataRow dr in pathItemRows)
451
                    {
452
                        dr["EqpGroupTag"] = EGTAG;
453
                        dr["EGFlowDirection"] = EGFlowDirection;
454
                    }
455
                }
456

    
457
                // 3, 4번
458
                foreach (DataRow dataRow in pumpRows) 
459
                {
460

    
461
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
462
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
463
                    string EGFlowDirection = string.Empty;
464

    
465
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
466
                    {
467
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
468
                        {
469
                            EGFlowDirection = "O";
470
                        }
471
                    }
472
                    
473
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
474
                    {
475
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
476
                        {
477
                            EGFlowDirection = "I";
478
                        }
479
                    }
480

    
481

    
482
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
483

    
484
                    foreach (DataRow dr in pathItemRows)
485
                    {
486
                        if(dr.Field<string>("ViewPipeSystemNetwork_OID") != dataRow["OID"].ToString())
487
                        {
488
                            string viewEGFlowDirection = string.Empty;
489
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
490
                            {
491
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));                               
492

    
493
                                if (viewPSNItem.Groups.First().Items.First().Equipment != null)
494
                                {
495
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
496
                                    {
497
                                        viewEGFlowDirection = "O";
498
                                    }
499
                                }
500
                                
501
                                
502
                                if (string.IsNullOrEmpty(viewEGFlowDirection) && viewPSNItem.Groups.Last().Items.Last().Equipment != null)
503
                                {
504
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
505
                                    {
506
                                        viewEGFlowDirection = "I";
507
                                    }
508
                                }
509

    
510
                                if (EGFlowDirection.Equals(viewEGFlowDirection) && !lstViewPipeSystemNetwork_OID.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
511
                                    lstViewPipeSystemNetwork_OID.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
512
                            }
513
                            else
514
                            {
515
                            }
516
                        }
517
                    }
518

    
519
                    string selectViewOID = string.Empty;
520

    
521
                    if (EGFlowDirection == "O") //From 이면 시작점에서 제일 먼 값
522
                    {
523
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
524
                        {
525
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
526
                            {                                
527
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
528
                            }
529
                        }
530
                    }
531
                    else if (EGFlowDirection == "I") //To 이면 시작점에서 제일 가까운 값
532
                    {
533
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
534
                        {
535
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
536
                            {
537
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
538
                                break;
539
                            }
540
                        }
541
                    }
542

    
543
                    if (!string.IsNullOrEmpty(selectViewOID)) //selectViewOID 가 있으면
544
                    {              
545
                        string EqpGroupTag = string.Empty;                       
546

    
547
                        if((EGFlowDirection == "O" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.Last().Field<string>("ViewPipeSystemNetwork_OID"))) ||
548
                            (EGFlowDirection == "I" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID"))))
549
                        { 
550
                            DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID")));
551

    
552
                            foreach (DataRow row in viewpathItemRows)
553
                            {
554
                                if (!string.IsNullOrEmpty(row.Field<string>("EqpGroupTag")))
555
                                {
556
                                    EqpGroupTag = row.Field<string>("EqpGroupTag");
557
                                    break;
558
                                }
559
                            }
560

    
561
                            foreach (DataRow dr in pathItemRows)
562
                            {
563
                                dr["EqpGroupTag"] = EqpGroupTag;
564
                            }
565

    
566
                        }
567
                        else
568
                        {
569
                            bool bCheck = false;
570
                            if (EGFlowDirection == "I") //To 일때
571
                            {
572
                                foreach (DataRow dr in pathItemRows)
573
                                {
574
                                    if (selectViewOID == dr["OID"].ToString())
575
                                    {
576
                                        dr["EGTConnectedPoint"] = "1";
577
                                        bCheck = true;
578
                                    }
579

    
580
                                    if (!bCheck)
581
                                    {
582
                                        dr["EqpGroupTag"] = string.Empty;
583
                                        dr["MainLineTag"] = string.Empty;
584
                                        dr["EGTConnectedPoint"] = "0";
585
                                        dr["EGFlowDirection"] = string.Empty;
586
                                    }
587
                                    else
588
                                    {
589
                                        dr["MainLineTag"] = "M";
590
                                    }
591
                                    
592
                                }
593

    
594
                            }
595
                            else if (EGFlowDirection == "O") //From 일 때
596
                            {
597
                                foreach (DataRow dr in pathItemRows)
598
                                {
599
                                    if (bCheck)
600
                                    {
601
                                        
602
                                        dr["EqpGroupTag"] = string.Empty;
603
                                        dr["MainLineTag"] = string.Empty;
604
                                        dr["EGTConnectedPoint"] = "0";
605
                                        dr["EGFlowDirection"] = string.Empty;
606
                                    }
607
                                    else
608
                                    {
609
                                        dr["MainLineTag"] = "M";
610
                                    }
611

    
612
                                    if (selectViewOID == dr["OID"].ToString())
613
                                    {
614
                                        dr["EGTConnectedPoint"] = "1";
615
                                        bCheck = true;
616
                                    }
617
                                }
618
                            }
619
                        }
620
                    }
621
                    else
622
                    {
623
                        //foreach (DataRow dr in pathItemRows)
624
                        //{
625
                        //    dr["EqpGroupTag"] = string.Empty;
626
                        //    dr["EGFlowDirection"] = string.Empty;
627
                        //    dr["EGTConnectedPoint"] = "0";
628
                        //    dr["MainLineTag"] = string.Empty;
629
                        //}
630
                    }
631
                }
632
                                
633
                // 5번
634
                foreach (DataRow dataRow in pumpRows)
635
                {
636
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
637

    
638
                    bool bCheck = false;
639
                    string EqpGroupTag = string.Empty;
640

    
641
                    string EGFlowDirection = string.Empty;                   
642

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

    
645
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
646
                    {
647
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
648
                        {
649
                            EGFlowDirection = "O";
650
                        }
651
                    }
652
                    
653
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
654
                    {
655
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
656
                        {
657
                            EGFlowDirection = "I";
658
                        }
659
                    }
660

    
661
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
662
                    List<string> lstEqTagRows = new List<string>();
663
                    if (EGFlowDirection.Equals("I"))
664
                    {
665
                        foreach (DataRow dr in pathItemRows)
666
                        {                            
667
                            if (!string.IsNullOrEmpty(dr.Field<string>("MainLineTag")) && dr.Field<string>("MainLineTag").Equals("M") && !string.IsNullOrEmpty(dr.Field<string>("EqpGroupTag")))
668
                            {
669
                                bCheck = true;
670
                                EqpGroupTag = dr.Field<string>("EqpGroupTag");
671
                                if(!lstEqTagRows.Contains(EqpGroupTag))
672
                                    lstEqTagRows.Add(EqpGroupTag);
673

    
674
                                if(dataRow["OID"].ToString() != dr.Field<string>("ViewPipeSystemNetwork_OID"))
675
                                {
676
                                    PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));
677
                                    if (viewPSNItem.Groups.Last().Items.Last().Equipment == null)
678
                                        continue;
679

    
680
                                    if (!lstEqTagRows.Contains(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag))
681
                                        lstEqTagRows.Add(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag);
682
                                }
683
                                
684
                            }
685

    
686
                        }
687
                        if(bCheck)
688
                        {
689
                            foreach (DataRow row in pumpRows)
690
                            {
691
                                if (row.Field<string>("OID").Equals(dataRow["OID"].ToString()))
692
                                    continue;
693

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

    
696
                                if (viewPSNItem.Groups.First().Items.First().Equipment == null)
697
                                    continue;
698
                                
699
                                if (lstEqTagRows.Contains(viewPSNItem.Groups.First().Items.First().Equipment.ItemTag) && !lstViewPipeSystemNetwork_OID.Contains(row.Field<string>("OID")))
700
                                    lstViewPipeSystemNetwork_OID.Add(row.Field<string>("OID"));
701
                            }
702

    
703
                                
704

    
705
                            if (lstViewPipeSystemNetwork_OID.Count() > 0)
706
                            {
707
                                foreach (string viewPipesystem in lstViewPipeSystemNetwork_OID)
708
                                {
709
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewPipesystem));
710
                                    foreach (DataRow viewdr in viewpathItemRows)
711
                                    {
712
                                        if (!string.IsNullOrEmpty(viewdr["EqpGroupTag"].ToString()))
713
                                            viewdr["EqpGroupTag"] = EqpGroupTag;
714
                                    }
715
                                }
716
                            }
717
                        }                        
718
                    }                   
719
                }
720
                
721
                int afcTagNum = 0;
722
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
723
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
724
                foreach (DataRow dataRow in airFinCoolerRows)
725
                {
726
                    string EGFlowDirection = string.Empty;
727
                    string EGTAG = "EGTAG";
728
                    string Prefix = string.Empty;
729
                    string SymbolName = string.Empty;
730

    
731
                    //item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
732
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
733
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
734
                    {
735
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
736
                        {
737
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
738
                            if(!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
739
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
740
                                    ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
741

    
742
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
743
                            EGFlowDirection = "O";
744
                        }
745
                    }
746

    
747
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
748
                    {
749
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
750
                        {
751
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
752
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
753
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
754
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
755

    
756
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
757
                            EGFlowDirection = "I";
758
                        }
759
                    }
760

    
761
                    if(!string.IsNullOrEmpty(EGFlowDirection))
762
                    {
763
                        string[] afcTag = dataRow.Field<string>("AFC").Split(new string[] { "\\" }, StringSplitOptions.None);
764

    
765
                        //Attribute가 세팅되어있지 않다면
766
                        if (EGTAG.Equals("EGTAG"))
767
                        {                          
768
                            if (!keyValuePairs.ContainsKey(afcTag[1]))
769
                            {
770
                                if (!string.IsNullOrEmpty(Prefix))
771
                                {
772
                                    afcTagNum++;
773
                                    EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", afcTagNum));
774
                                    keyValuePairs.Add(afcTag[1], EGTAG);
775
                                }
776
                                else
777
                                {
778
                                    keyValuePairs.Add(afcTag[1], afcTag[1]);
779

    
780
                                }
781
                            }
782
                            else
783
                            {
784
                                EGTAG = keyValuePairs[afcTag[1]];
785
                            }
786
                            
787
                        }
788
                        else
789
                        {
790
                            if (!string.IsNullOrEmpty(Prefix))
791
                                EGTAG = Prefix + "-" + EGTAG;                          
792
                        }
793

    
794
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
795
                        foreach (DataRow dr in pathItemRows)
796
                        {
797
                            dr["EqpGroupTag"] = EGTAG;
798
                            dr["EGFlowDirection"] = EGFlowDirection;
799
                        }
800
                    }
801
                    
802
                }
803

    
804
                List<string> changePSN = new List<string>();
805
                foreach (DataRow dataRow in airFinCoolerRows)
806
                {
807
                    if (changePSN.Contains(dataRow["OID"].ToString()))
808
                        continue;
809

    
810
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
811
                    string AFCTag = string.Empty;
812
                    if (pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).Count() > 0)
813
                        AFCTag = pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");
814

    
815
                    List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
816

    
817
                    if (dataRow["Type"].ToString() == "E2E")
818
                    {
819
                        foreach (DataRow dr in pathItemRows)
820
                        {
821
                            dr["MainLineTag"] = "M";
822
                        }
823
                        dataRow["AFC"] = "P3";
824
                    }
825
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
826
                    {
827
                        foreach (string lstoid in lstViewPipeSystemNetwork_OID)
828
                        {
829
                            DataRow[] p2psn = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", lstoid));
830

    
831
                            if (p2psn.Count() > 0)
832
                            {
833
                                DataRow[] viewPathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
834
                                List<string> lstview = viewPathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
835
                                lstview.Remove(dataRow["OID"].ToString()); // P1인 자신 제거
836
                                lstview.Remove(lstoid); // P2 자신 제거
837

    
838
                                List<string> lstnewpipe = new List<string>();
839
                                foreach (string lstvw in lstview) //자신 외 P1이 있는지 확인
840
                                {
841
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID").Equals(lstvw)).Count() > 0) //P1이면 리스트에 추가
842
                                        lstnewpipe.Add(lstvw);
843
                                }
844

    
845
                                if (lstnewpipe.Count() == 0)
846
                                {
847
                                    foreach (DataRow dr in pathItemRows)
848
                                    {
849
                                        dr["MainLineTag"] = "M";
850
                                    }
851
                                    dataRow["AFC"] = "P3";
852
                                }
853
                                else
854
                                {
855
                                    // P2에 ML값 AGT값 지정
856
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
857
                                    DataRow[] pipesystemRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", lstoid));
858
                                    foreach (DataRow viewdr in pipesystemRows)
859
                                    {
860
                                        viewdr["AFC"] = "P4";
861
                                    }
862

    
863
                                    foreach (DataRow viewdr in viewpathItemRows)
864
                                    {
865
                                        viewdr["EqpGroupTag"] = AFCTag;
866
                                        viewdr["MainLineTag"] = "M";
867
                                    }
868
                                    // 연결된 모든 P1들의 AGT값 치환
869
                                    foreach (string pipe in lstnewpipe)
870
                                    {
871
                                        viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipe));
872
                                        foreach (DataRow viewdr in viewpathItemRows)
873
                                        {
874
                                            viewdr["EqpGroupTag"] = AFCTag;
875
                                        }
876
                                    }
877
                                }
878
                            }                               
879
                        }   
880
                    }
881
                }
882
                
883
                //P3을 제외한 P1
884
                airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
885
                foreach (DataRow dataRow in airFinCoolerRows)
886
                {
887
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
888
                    
889
                    if (pathItemRows.Count() > 0)
890
                    {
891
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
892
                        List<string> lstpsn = new List<string>();
893
                        List<string> lstAll = new List<string>();
894
                        string EqpGroupTag = string.Empty;
895
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
896
                        {
897
                            if (dataRow["OID"].ToString() == viewOID)
898
                            {
899
                                lstAll.Add(viewOID);
900
                                continue;
901
                            }
902

    
903
                            //P3이면
904
                            DataRow viewPSN = null;
905
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
906
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
907
                            
908
                            if (viewPSN != null)
909
                            {
910
                                //P3의 AGT를 가져와 P1에 입력
911
                                if(string.IsNullOrEmpty(EqpGroupTag))
912
                                    EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
913

    
914
                                foreach (DataRow dr in pathItemRows)
915
                                {
916
                                    dr["EqpGroupTag"] = EqpGroupTag;
917

    
918
                                    //P1의 AGT와 같은 모든 AGT를 P3의 AGT로 변경하기위해 
919
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
920
                                    {
921
                                        //AND MainLineTag = ''
922
                                        if (PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' ", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
923
                                        {
924
                                            lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
925
                                            lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
926
                                        }
927
                                    }
928
                                }
929
                            }                            
930
                        }
931

    
932
                        while (lstpsn.Count() != 0)
933
                        {                            
934
                            DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstpsn[0]));
935
                            foreach (DataRow dr in rule4pathItems)
936
                            {
937
                                if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstAll.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
938
                                {
939
                                    DataRow viewPSN = null;
940

    
941
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).Count() > 0)
942
                                        viewPSN = airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).First();
943
                                                                        
944
                                    if (viewPSN != null)
945
                                    {
946
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
947
                                        lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
948
                                    }
949
                                }                                
950

    
951
                                dr["EqpGroupTag"] = EqpGroupTag;
952

    
953
                            }
954
                            lstpsn.Remove(lstpsn[0]);
955
                        }
956
                    }
957
                    
958
                }
959

    
960
                foreach(DataRow dr in PipeSystemNetwork.Rows)
961
                {
962
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
963
                    if(pathItemRows.Count() > 0)
964
                    {
965
                        if(dr["Type"].ToString() == "HD2")
966
                        {
967
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
968
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
969
                            {                              
970
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
971
                                {
972
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
973
                                    {
974
                                        dataRow["EGTConnectedPoint"] = "1";
975
                                    }
976
                                }
977
                            }
978
                        }
979
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
980
                        {
981
                            PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dr["OID"].ToString());
982
                            string EGFlowDirection = string.Empty;
983
                            if (PSNItem.Groups.First().Items.First().Equipment != null)
984
                            {
985
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
986
                                {
987
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
988
                                    if (equipmentAirFinCoolerItem != null)
989
                                        EGFlowDirection = "O";
990
                                }
991
                            }
992
                            
993
                            if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
994
                            {
995
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
996
                                {
997
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
998
                                    if(equipmentAirFinCoolerItem != null)
999
                                        EGFlowDirection = "I";
1000
                                }
1001
                            }
1002

    
1003
                            if (!string.IsNullOrEmpty(EGFlowDirection))
1004
                            {
1005
                                List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
1006
                                string lastP1 = string.Empty;
1007

    
1008
                                foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
1009
                                {
1010
                                    if (viewpsn == dr["OID"].ToString())
1011
                                        continue;
1012

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

    
1016
                                    DataRow rows = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC Like 'P1%'", viewpsn)).First();
1017

    
1018
                                    if (rows != null)
1019
                                    {
1020
                                        lastP1 = viewpsn;
1021
                                        if (EGFlowDirection.Equals("I")) // To         
1022
                                            break;
1023
                                    }
1024
                                }
1025

    
1026
                                if (!string.IsNullOrEmpty(lastP1))
1027
                                {
1028
                                    bool bCheck = false;
1029
                                    if (EGFlowDirection.Equals("O")) // From
1030
                                    {
1031
                                        foreach (DataRow dataRow in pathItemRows)
1032
                                        {
1033
                                            if (bCheck)
1034
                                            {
1035
                                                dataRow["EqpGroupTag"] = string.Empty;
1036
                                                dataRow["MainLineTag"] = string.Empty;
1037
                                                dataRow["EGTConnectedPoint"] = 0;
1038
                                                dataRow["EGFlowDirection"] = string.Empty;
1039
                                            }
1040

    
1041
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1042
                                            {
1043
                                                bCheck = true;
1044
                                                dataRow["EGTConnectedPoint"] = 1;
1045
                                            }
1046
                                        }
1047
                                    }
1048
                                    else
1049
                                    {
1050
                                        foreach (DataRow dataRow in pathItemRows)
1051
                                        {
1052
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1053
                                            {
1054
                                                dataRow["EGTConnectedPoint"] = 1;
1055
                                                break;
1056
                                            }
1057
                                            
1058
                                            dataRow["EqpGroupTag"] = string.Empty;
1059
                                            dataRow["MainLineTag"] = string.Empty;
1060
                                            dataRow["EGTConnectedPoint"] = 0;
1061
                                            dataRow["EGFlowDirection"] = string.Empty;
1062

    
1063
                                        }
1064
                                    }
1065
                                }
1066
                            }                          
1067
                        }
1068
                    }
1069
                }
1070

    
1071
                //psn data 정리
1072
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
1073
                {
1074
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
1075
                    string EGTag = string.Empty;
1076
                    string HasMLTags = "False";
1077

    
1078
                    foreach (DataRow dataRow in pathItemRows)
1079
                    {
1080
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
1081
                            EGTag = dataRow.Field<string>("EqpGroupTag");
1082

    
1083
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
1084
                            HasMLTags = "True";
1085

    
1086
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
1087
                            break;
1088
                    }
1089

    
1090
                    pipesystem["EGTag"] = EGTag;
1091
                    pipesystem["HasMLTags"] = HasMLTags;
1092
                }
1093
            }
1094
            catch (Exception ex)
1095
            {
1096
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1097
            }
1098
            //}
1099
        }
1100

    
1101
        private void UpdateValveGrouping()
1102
        {
1103
            try
1104
            {
1105
                #region ValveGrouping Info
1106
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1107
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1108
                foreach (DataRow row in dtValveGroupung.Rows)
1109
                {
1110
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1111
                    {
1112
                        OID = row["OID"].ToString(),
1113
                        GroupType = row["GroupType"].ToString(),
1114
                        TagIdentifier = row["TagIdentifier"].ToString(),
1115
                        AttributeName = row["AttributeName"].ToString(),
1116
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1117
                    });
1118
                }
1119
                #endregion
1120

    
1121

    
1122
                int vgTagNum = 1;
1123
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
1124
                List<string> pathOid = new List<string>();
1125
                foreach (DataRow drPathitem in tagpathItemRows)
1126
                {
1127
                    if (pathOid.Contains(drPathitem.Field<string>("OID")))
1128
                        continue;
1129

    
1130
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
1131
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1132
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
1133
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
1134
                        continue;
1135
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
1136
                    List<Item> valveGroupingItem = new List<Item>();
1137
                    int bCnt = 0;
1138

    
1139
                    
1140
                    List<DataRow> lstitem = new List<DataRow>();
1141
                    foreach (DataRow dr in pathItemRows)
1142
                    {
1143
                        if (dr["GROUPTAG"].ToString() == "Scope Break")
1144
                        {
1145
                            dr["GROUPTAG"] = string.Empty;
1146
                            keyValuePairs.Add(bCnt, lstitem.ToList());
1147
                            bCnt++;
1148
                            lstitem.Clear();
1149
                            continue;
1150
                        }
1151
                        else if(!string.IsNullOrEmpty(dr["GROUPTAG"].ToString()) && !dr.Field<string>("OID").Equals(drPathitem.Field<string>("OID")))
1152
                        {
1153

    
1154
                            List<DataRow> lstitem2 = new List<DataRow>();
1155
                            int indexOf = 0;
1156
                            
1157
                            for (int i = 0; i < lstitem.Count; i++)
1158
                            {
1159
                                DataRow dataRow = lstitem[lstitem.Count() - i - 1];
1160
                                if (!string.IsNullOrEmpty(dataRow["BranchTopologySet_OID"].ToString()))
1161
                                {
1162
                                    indexOf = lstitem.Count() - i - 1;
1163
                                    break;
1164
                                }
1165
                            }
1166

    
1167
                            for (int i = 0; i < lstitem.Count; i++)
1168
                            {
1169
                                if (indexOf == i)
1170
                                {
1171
                                    keyValuePairs.Add(bCnt, lstitem2.ToList());
1172
                                    lstitem2.Clear();
1173
                                    bCnt++;
1174
                                }
1175
                                lstitem2.Add(lstitem[i]);
1176
                            }
1177

    
1178
                            lstitem = lstitem2.ToList();
1179
                        }
1180

    
1181
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1182
                        {
1183
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));                          
1184
                           
1185
                            if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
1186
                            {
1187
                                if (lstitem.ToList().Where(x => !string.IsNullOrEmpty(x.Field<string>("GROUPTAG"))).Count() > 0)
1188
                                {
1189
                                    lstitem.Add(dr);
1190
                                    keyValuePairs.Add(bCnt, lstitem.ToList());
1191
                                    lstitem.Clear();
1192
                                }
1193
                                else
1194
                                {
1195
                                    keyValuePairs.Add(bCnt, lstitem.ToList());
1196
                                    lstitem.Clear();
1197
                                    lstitem.Add(dr);
1198
                                }
1199
                                bCnt++;
1200

    
1201
                            }
1202
                            else
1203
                                lstitem.Add(dr);
1204
                            
1205
                        }
1206
                        else
1207
                            lstitem.Add(dr);
1208
                    }
1209

    
1210
                    if (lstitem.Count > 0)
1211
                    {
1212
                        keyValuePairs.Add(bCnt, lstitem);
1213
                    }
1214

    
1215
                    if (keyValuePairs.Count() == 0)
1216
                        continue;
1217

    
1218
                    string VGTag = string.Empty;
1219
                    if (valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
1220
                    {
1221
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1222
                        vgTagNum++;
1223
                    }
1224
                    else
1225
                    {                        
1226
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
1227
                    }
1228

    
1229
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
1230
                    {                       
1231
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
1232
                        {
1233
                            if (!pathOid.Contains(drPathitem.Field<string>("OID")))
1234
                                pathOid.Add(drPathitem.Field<string>("OID"));
1235

    
1236
                            foreach (DataRow dr in keyValuePair.Value)
1237
                            {
1238
                                dr["GROUPTAG"] = VGTag;
1239

    
1240
                                if(!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1241
                                {
1242
                                    if(TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1243
                                    {
1244
                                        DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1245
                                        foreach(DataRow path in rows)
1246
                                        {
1247
                                            DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1248
                                            if (topology.Field<string>("SubType").Equals("Bypass"))
1249
                                            {
1250
                                                DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1251
                                                //if (dr["GROUPTAG"].ToString() == "Scope Break")
1252
                                                if(drPathItem.Where(x => x.Field<string>("GROUPTAG") == "Scope Break").Count() == 0)
1253
                                                {
1254
                                                    foreach (DataRow pathitem in drPathItem)
1255
                                                    {
1256
                                                        pathitem["GROUPTAG"] = VGTag;
1257
                                                    }
1258
                                                }
1259
                                            }
1260
                                        }
1261
                                    }
1262
                                }
1263
                            }
1264
                        }
1265
                        else
1266
                        {                            
1267
                            foreach (DataRow drs in tagpathItemRows)
1268
                            {
1269
                                if (drs.Field<string>("OID").Equals(drPathitem.Field<string>("OID")))
1270
                                    continue;
1271
                              
1272
                                if(keyValuePair.Value.Where(x => x.Field<string>("OID") == drs.Field<string>("OID")).Count() > 0)
1273
                                {
1274
                                    if (!pathOid.Contains(drs.Field<string>("OID")))
1275
                                    {
1276
                                        pathOid.Add(drs.Field<string>("OID"));
1277

    
1278
                                        valvetag = drs["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
1279
                                        ValveGroupItem valveitems = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
1280
                                        if (valveitems == null || valveitems.GroupType == "Scope Break")
1281
                                            continue;
1282

    
1283
                                        VGTag = string.Empty;
1284
                                        if (valveitems.AttributeName == "NoSelection" || valveitems.AttributeName == string.Empty)
1285
                                        {
1286
                                            VGTag = valveitems.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1287
                                            vgTagNum++;
1288
                                        }
1289
                                        else
1290
                                        {
1291
                                            VGTag = valveitems.TagIdentifier + "-" + valvetag[1];
1292
                                        }
1293

    
1294
                                        foreach (DataRow dr in keyValuePair.Value)
1295
                                        {
1296
                                            dr["GROUPTAG"] = VGTag;
1297

    
1298
                                            if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1299
                                            {
1300
                                                if (TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1301
                                                {
1302
                                                    DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1303
                                                    foreach (DataRow path in rows)
1304
                                                    {
1305
                                                        DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1306
                                                        if (topology.Field<string>("SubType").Equals("Bypass"))
1307
                                                        {
1308
                                                            DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1309
                                                            if (drPathItem.Where(x => x.Field<string>("GROUPTAG") == "Scope Break").Count() == 0)
1310
                                                            {
1311
                                                                foreach (DataRow pathitem in drPathItem)
1312
                                                                {
1313
                                                                    pathitem["GROUPTAG"] = VGTag;
1314
                                                                }
1315
                                                            }
1316
                                                        }
1317
                                                    }
1318
                                                }
1319
                                            }
1320
                                        }
1321

    
1322
                                        if (valveitems.GroupType.Contains("PSV"))
1323
                                        {
1324
                                            DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1325
                                            foreach (DataRow row in psnRows)
1326
                                                row["Pocket"] = "Yes";
1327
                                        }
1328
                                    }     
1329
                                }
1330
                            }                            
1331
                        }
1332
                    }
1333

    
1334
                    if(valveitem.GroupType.Contains("PSV"))
1335
                    {
1336
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1337
                        foreach (DataRow row in psnRows)
1338
                            row["Pocket"] = "Yes";
1339
                    }                    
1340
                }
1341

    
1342
                tagpathItemRows = PathItems.Select(string.Format("GROUPTAG = 'Scope Break'"));
1343
                foreach (DataRow drPathitem in tagpathItemRows)
1344
                {
1345
                    drPathitem["GROUPTAG"] = string.Empty;
1346
                }
1347
            }
1348
            catch (Exception ex)
1349
            {
1350
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1351
            }
1352
        }
1353

    
1354
        private void SetTopologyData()
1355
        {
1356
            // 13번 excel
1357
            foreach (Group group in groups)
1358
            {
1359
                LineNumber prevLineNumber = null;
1360
                for (int i = 0; i < group.Items.Count; i++)
1361
                {
1362
                    Item item = group.Items[i];
1363
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1364
                    if (lineNumber == null)
1365
                    {
1366
                        if (prevLineNumber != null)
1367
                        {
1368
                            if (!prevLineNumber.IsCopy)
1369
                            {
1370
                                prevLineNumber = prevLineNumber.Copy();
1371
                                prevLineNumber.MissingLineNumber1 = true;
1372
                                item.Document.LineNumbers.Add(prevLineNumber);
1373
                                //item.LineNumber.MissingLineNumber1 = true;
1374
                            }
1375
                            item.Owner = prevLineNumber.UID;
1376
                        }
1377
                    }
1378
                    else
1379
                        prevLineNumber = lineNumber;
1380
                }
1381

    
1382
                prevLineNumber = null;
1383
                for (int i = group.Items.Count - 1; i > -1; i--)
1384
                {
1385
                    Item item = group.Items[i];
1386
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1387
                    if (lineNumber == null)
1388
                    {
1389
                        if (prevLineNumber != null)
1390
                        {
1391
                            if (!prevLineNumber.IsCopy)
1392
                            {
1393
                                prevLineNumber = prevLineNumber.Copy();
1394
                                prevLineNumber.MissingLineNumber1 = true;
1395
                                item.Document.LineNumbers.Add(prevLineNumber);
1396
                                //item.LineNumber.MissingLineNumber1 = true;                                
1397
                            }
1398

    
1399
                            item.Owner = prevLineNumber.UID;
1400
                        }
1401
                    }
1402
                    else
1403
                        prevLineNumber = lineNumber;
1404
                }
1405

    
1406
                if (prevLineNumber == null)
1407
                {
1408
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1409
                    Random random = new Random();
1410

    
1411
                    LineNumber cLineNumber = null;
1412

    
1413
                    if (lineNumbers.Count == 0)
1414
                    {
1415
                        var _groups = groups.Where(w => w != group).ToList();
1416
                        while (cLineNumber == null)
1417
                        {
1418
                            int _index = random.Next(_groups.Count - 1);
1419
                            List<LineNumber> _lineNumbers = groups[_index].Document.LineNumbers.FindAll(x => !x.IsCopy);
1420
                            if (_lineNumbers.Count != 0)
1421
                            {
1422
                                _index = random.Next(_lineNumbers.Count - 1);
1423

    
1424
                                // Copy
1425
                                cLineNumber = _lineNumbers[_index].Copy();
1426
                            }
1427
                        }
1428
                    }
1429
                    else
1430
                    {
1431
                        int index = random.Next(lineNumbers.Count - 1);
1432

    
1433
                        // Copy
1434
                        cLineNumber = lineNumbers[index].Copy();
1435
                    }
1436

    
1437
                    cLineNumber.MissingLineNumber2 = true;
1438
                    group.Document.LineNumbers.Add(cLineNumber);
1439

    
1440
                    foreach (Item item in group.Items)
1441
                    {
1442
                        item.Owner = cLineNumber.UID;                        
1443
                    }
1444
                }
1445

    
1446
                //if (prevLineNumber == null)
1447
                //{
1448
                //    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1449
                //    Random random = new Random();
1450
                //    int index = random.Next(lineNumbers.Count - 1);
1451

    
1452
                //    // Copy
1453
                //    LineNumber cLineNumber = lineNumbers[index].Copy();
1454
                //    group.Document.LineNumbers.Add(cLineNumber);
1455

    
1456
                //    foreach (Item item in group.Items)
1457
                //    {
1458
                //        item.Owner = cLineNumber.UID;
1459
                //        item.Document.MissingLineNumber2 = true;
1460
                //    }
1461
                //}
1462
            }
1463

    
1464
            foreach (Document document in Documents)
1465
            {
1466
                foreach (Item item in document.Items)
1467
                {
1468
                    item.TopologyData = string.Empty;
1469
                    item.PSNPipeLineID = string.Empty;
1470
                    List<string> pipeLineID = new List<string>();
1471
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1472
                    
1473
                    if (lineNumber != null)
1474
                    {
1475
                        item.LineNumber = lineNumber;
1476

    
1477
                        foreach (DataRow row in topologyRuleDT.Rows)
1478
                        {
1479
                            string uid = row["UID"].ToString();
1480
                            //if (uid == "-")
1481
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1482
                            if (uid != "-")
1483
                            {
1484
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1485

    
1486
                                Attribute attribute = lineNumber.Attributes.Find(x => x.DisplayName == uid);
1487
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1488
                                {
1489
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1490
                                                                    //if (uid.Equals("Tag Seq No") && attribute.Value.ToString().Substring(attribute.Value.ToString().Length - 1, 1).Equals("V"))
1491
                                                                    //{
1492
                                    if (item.LineNumber.MissingLineNumber1 && item.LineNumber.MissingLineNumber2)
1493
                                    {
1494

    
1495
                                    }
1496

    
1497
                                 
1498
                                    //    //if (item.Document.MissingLineNumber1)
1499
                                    //    //    item.MissingLineNumber1 = true;
1500
                                    //    //else if (item.Document.MissingLineNumber2)
1501
                                    //    //    item.MissingLineNumber2 = true;
1502
                                    //}
1503
                                }
1504
                            }
1505
                        }
1506
                        
1507
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1508
                        {
1509
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1510
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1511
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1512
                                                                 //else
1513
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1514
                        }
1515

    
1516
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1517
                        item.TopologyData = string.Join("-", pipeLineID);
1518
                        
1519
                    }
1520
                    else
1521
                    {
1522
                        item.TopologyData = "Empty LineNumber";
1523
                        item.LineNumber = new LineNumber();
1524
                    }
1525
                }
1526
            }
1527

    
1528
            int emptyIndex = 1;
1529
            foreach (Group group in groups)
1530
            {
1531
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1532
                if (groupItems.Count > 0)
1533
                {
1534
                    foreach (var item in groupItems)
1535
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1536
                    emptyIndex++;
1537
                }
1538
            }
1539

    
1540
        }
1541

    
1542
        private void ConnectByOPC()
1543
        {
1544
            try
1545
            {
1546
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1547
                {
1548
                    Item opcItem = group.Items.Last();
1549
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1550
                    if (fromRows.Length.Equals(1))
1551
                    {
1552
                        DataRow opcRow = fromRows.First();
1553
                        string toDrawing = opcRow["ToDrawing"].ToString();
1554
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
1555

    
1556
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1557
                        if (toDocument != null)
1558
                        {
1559
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1560
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1561
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1562
                            if (toRows.Length > 1)
1563
                            {
1564
                                //throw new Exception("OPC error(multi connect)");
1565
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1566
                                return;
1567
                            }
1568
                            group.EndGroup = toGroup;
1569
                            toGroup.StartGroup = group;
1570
                        }
1571
                    }
1572
                }
1573
            }
1574
            catch (Exception ex)
1575
            {
1576
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1577
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1578
            }
1579
        }
1580

    
1581
        private void SetPSNItem()
1582
        {
1583
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1584
            foreach (Group group in groups)
1585
                groupDic.Add(group, Guid.NewGuid().ToString());
1586

    
1587
            foreach (Group group in groups)
1588
            {
1589
                string groupKey = groupDic[group];
1590
                if (group.StartGroup != null)
1591
                {
1592
                    string otherKey = groupDic[group.StartGroup];
1593
                    ChangeGroupID(otherKey, groupKey);
1594
                }
1595
            }
1596

    
1597
            // PSN 정리
1598
            foreach (var item in groupDic)
1599
            {
1600
                Group group = item.Key;
1601
                string uid = item.Value;
1602
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1603
                if (PSNItem == null)
1604
                {
1605
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1606
                    PSNItems.Add(PSNItem);
1607
                }
1608
                PSNItem.Groups.Add(group);
1609
                foreach (Item groupItem in group.Items)
1610
                    groupItem.PSNItem = PSNItem;
1611
            }
1612

    
1613
            // Sort PSN
1614
            foreach (PSNItem PSNItem in PSNItems)
1615
            {
1616
                List<Group> _groups = new List<Group>();
1617

    
1618
                Stack<Group> stacks = new Stack<Group>();
1619
                stacks.Push(PSNItem.Groups.First());
1620
                while (stacks.Count > 0)
1621
                {
1622
                    Group stack = stacks.Pop();
1623
                    if (_groups.Contains(stack))
1624
                        continue;
1625

    
1626
                    if (_groups.Count == 0)
1627
                        _groups.Add(stack);
1628
                    else
1629
                    {
1630
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1631
                        {
1632
                            int index = _groups.IndexOf(stack.StartGroup);
1633
                            _groups.Insert(index + 1, stack);
1634
                        }
1635
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1636
                        {
1637
                            int index = _groups.IndexOf(stack.EndGroup);
1638
                            _groups.Insert(index, stack);
1639
                        }
1640
                    }
1641

    
1642
                    if (stack.StartGroup != null)
1643
                        stacks.Push(stack.StartGroup);
1644
                    if (stack.EndGroup != null)
1645
                        stacks.Push(stack.EndGroup);
1646
                }
1647

    
1648
                PSNItem.Groups.Clear();
1649
                PSNItem.Groups.AddRange(_groups);
1650
            }
1651

    
1652
            void ChangeGroupID(string from, string to)
1653
            {
1654
                if (from.Equals(to))
1655
                    return;
1656

    
1657
                List<Group> changeItems = new List<Group>();
1658
                foreach (var _item in groupDic)
1659
                    if (_item.Value.Equals(from))
1660
                        changeItems.Add(_item.Key);
1661
                foreach (var _item in changeItems)
1662
                    groupDic[_item] = to;
1663
            }
1664
        }
1665

    
1666
        private void SetPSNType()
1667
        {
1668
            foreach (PSNItem PSNItem in PSNItems)
1669
            {
1670
                Group firstGroup = PSNItem.Groups.First();
1671
                Group lastGroup = PSNItem.Groups.Last();
1672

    
1673
                Item firstItem = firstGroup.Items.First();
1674
                Item lastItem = lastGroup.Items.Last();
1675

    
1676
                PSNItem.StartType = GetPSNType(firstItem, true);
1677
                PSNItem.EndType = GetPSNType(lastItem, false);
1678

    
1679
            }
1680

    
1681
            PSNType GetPSNType(Item item, bool bFirst = true)
1682
            {
1683
                PSNType type = PSNType.None;
1684

    
1685
                if (item.ItemType == ItemType.Line)
1686
                {
1687
                    Group group = groups.Find(x => x.Items.Contains(item));
1688
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1689
                    {
1690
                        Item connItem = item.Relations[0].Item;
1691
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1692
                            type = PSNType.Branch;
1693
                        else if (connItem.ItemType == ItemType.Symbol)
1694
                            type = PSNType.Symbol;
1695
                    }
1696
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1697
                    {
1698
                        Item connItem = item.Relations[1].Item;
1699
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1700
                            type = PSNType.Branch;
1701
                        else if (connItem.ItemType == ItemType.Symbol)
1702
                            type = PSNType.Symbol;
1703
                    }
1704
                }
1705
                else if (item.ItemType == ItemType.Symbol)
1706
                {
1707
                    if (item.SubItemType == SubItemType.Nozzle)
1708
                        type = PSNType.Equipment;
1709
                    else if (item.SubItemType == SubItemType.Header)
1710
                        type = PSNType.Header;
1711
                    else if (item.SubItemType == SubItemType.OPC)
1712
                        type = PSNType.OPC;
1713
                }
1714

    
1715
                return type;
1716
            }
1717
        }
1718

    
1719
        private void SetBranchInfo()
1720
        {
1721
            foreach (Document document in Documents)
1722
            {
1723
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1724
                foreach (Item line in lines)
1725
                {
1726
                    double[] point = line.Relations[0].Point;
1727
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1728
                    connLines.Sort(SortBranchLine);
1729
                    line.BranchItems.AddRange(connLines);
1730

    
1731
                    int SortBranchLine(Item a, Item b)
1732
                    {
1733
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1734
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1735

    
1736
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1737
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1738

    
1739
                        // 내림차순
1740
                        return distanceA.CompareTo(distanceB);
1741
                    }
1742
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1743
                    {
1744
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1745
                    }
1746
                }
1747
            }
1748
        }
1749

    
1750
        private void SetTopology()
1751
        {
1752
            try
1753
            {
1754
                #region 기본 topology 정리
1755
                foreach (PSNItem PSNItem in PSNItems)
1756
                {
1757
                    Topology topology = null;
1758
                    foreach (Group group in PSNItem.Groups)
1759
                    {
1760
                        foreach (Item item in group.Items)
1761
                        {
1762
                            if (string.IsNullOrEmpty(item.TopologyData))
1763
                                topology = null;
1764
                            else
1765
                            {
1766
                                if (topology == null)
1767
                                {
1768
                                    topology = new Topology()
1769
                                    {
1770
                                        ID = item.TopologyData
1771
                                    };
1772
                                    Topologies.Add(topology);
1773

    
1774
                                    if (!PSNItem.Topologies.Contains(topology))
1775
                                        PSNItem.Topologies.Add(topology);
1776
                                }
1777
                                else
1778
                                {
1779
                                    if (topology.ID != item.TopologyData)
1780
                                    {
1781
                                        topology = new Topology()
1782
                                        {
1783
                                            ID = item.TopologyData
1784
                                        };
1785
                                        Topologies.Add(topology);
1786

    
1787
                                        if (!PSNItem.Topologies.Contains(topology))
1788
                                            PSNItem.Topologies.Add(topology);
1789
                                    }
1790
                                }
1791

    
1792
                                item.Topology = topology;
1793
                                topology.Items.Add(item);
1794
                            }
1795
                        }
1796
                    }
1797
                }
1798
                #endregion
1799

    
1800
                #region Type
1801
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1802
                foreach (string id in ids)
1803
                {
1804
                    try
1805
                    {
1806

    
1807

    
1808
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1809

    
1810
                        // Main
1811
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1812
                        foreach (Topology topology in mainTopologies)
1813
                            topology.Type = "M";
1814

    
1815
                        // Branch
1816
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1817
                        foreach (Topology topology in branchToplogies)
1818
                            topology.Type = "B";
1819
                    }
1820
                    catch (Exception ex)
1821
                    {
1822
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1823
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1824
                    }
1825
                }
1826
                #endregion
1827
            }
1828
            catch (Exception ex)
1829
            {
1830
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1831
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1832
            }
1833

    
1834
        }
1835

    
1836
        private void SetTopologyIndex()
1837
        {
1838
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1839
            foreach (string id in ids)
1840
            {
1841
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1842

    
1843
                // Main
1844
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1845
                foreach (Topology topology in mainTopologies)
1846
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1847

    
1848
                // Branch
1849
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1850
                foreach (Topology topology in branchToplogies)
1851
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1852
            }
1853
        }
1854

    
1855
        private void SetPSNBypass()
1856
        {
1857
            foreach (PSNItem PSNItem in PSNItems)
1858
                PSNItem.IsBypass = IsBypass(PSNItem);
1859
        }
1860

    
1861
        private List<Topology> FindMainTopology(List<Topology> data)
1862
        {
1863
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1864
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1865
            //2021.11.17 안쓰네 JY
1866
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1867

    
1868
            List<Topology> main = new List<Topology>();
1869
            main.AddRange(data);
1870
            //
1871
            main = GetNozzleTopology(data);
1872
            if (main.Count == 1)
1873
                return main;
1874
            else
1875
            {
1876
                if (main.Count > 0)
1877
                    main = GetPMCTopology(main);
1878
                else
1879
                    main = GetPMCTopology(data);
1880

    
1881
                if (main.Count == 1)
1882
                    return main;
1883
                else
1884
                {
1885
                    if (main.Count > 0)
1886
                        main = GetDiaTopology(main);
1887
                    else
1888
                        main = GetDiaTopology(data);
1889

    
1890

    
1891
                    if (main.Count == 1)
1892
                        return main;
1893
                    else
1894
                    {
1895
                        if (main.Count > 0)
1896
                            main = GetItemTopology(main);
1897
                        else
1898
                            main = GetItemTopology(data);
1899
                    }
1900
                }
1901
            }
1902

    
1903
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1904
            {
1905
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1906
            }
1907

    
1908
            List<Topology> GetPMCTopology(List<Topology> topologies)
1909
            {
1910
                List<Topology> result = new List<Topology>();
1911
                foreach (DataRow row in PMCDT.Rows)
1912
                {
1913
                    string value = row["CODE"].ToString();
1914
                    foreach (Topology topology in topologies)
1915
                    {
1916
                        foreach (Item item in topology.Items)
1917
                        {
1918
                            if (item.LineNumber == null)
1919
                                continue;
1920
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1921
                            if (attribute != null && value == attribute.Value)
1922
                            {
1923
                                result.Add(topology);
1924
                                break;
1925
                            }
1926
                        }
1927
                    }
1928

    
1929
                    if (result.Count > 0)
1930
                        break;
1931
                }
1932

    
1933
                return result;
1934
            }
1935

    
1936
            List<Topology> GetDiaTopology(List<Topology> topologies)
1937
            {
1938
                List<Topology> result = new List<Topology>();
1939
                foreach (DataRow row in nominalDiameterDT.Rows)
1940
                {
1941
                    string inchValue = row["InchStr"].ToString();
1942
                    string metricValue = row["MetricStr"].ToString();
1943
                    foreach (Topology topology in topologies)
1944
                    {
1945
                        foreach (Item item in topology.Items)
1946
                        {
1947
                            if (item.LineNumber == null)
1948
                                continue;
1949
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1950
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1951
                            {
1952
                                result.Add(topology);
1953
                                break;
1954
                            }
1955
                        }
1956
                    }
1957

    
1958
                    if (result.Count > 0)
1959
                        break;
1960
                }
1961

    
1962
                return result;
1963
            }
1964

    
1965
            List<Topology> GetItemTopology(List<Topology> topologies)
1966
            {
1967
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1968
            }
1969

    
1970
            return main;
1971
        }
1972

    
1973
        private DataTable GetOPCInfo()
1974
        {
1975
            DataTable opc = DB.SelectOPCRelations();
1976
            DataTable drawing = DB.AllDrawings();
1977

    
1978
            DataTable dt = new DataTable();
1979
            dt.Columns.Add("FromDrawing", typeof(string));
1980
            dt.Columns.Add("FromDrawingUID", typeof(string));
1981
            dt.Columns.Add("FromOPCUID", typeof(string));
1982
            dt.Columns.Add("ToDrawing", typeof(string));
1983
            dt.Columns.Add("ToDrawingUID", typeof(string));
1984
            dt.Columns.Add("ToOPCUID", typeof(string));
1985
            foreach (DataRow row in opc.Rows)
1986
            {
1987
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1988
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1989
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1990
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1991
                if (!string.IsNullOrEmpty(toOPCUID))
1992
                {
1993
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
1994
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
1995
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
1996
                    {
1997
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
1998
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
1999

    
2000
                        DataRow newRow = dt.NewRow();
2001
                        newRow["FromDrawing"] = fromDrawingName;
2002
                        newRow["FromDrawingUID"] = fromDrawingUID;
2003
                        newRow["FromOPCUID"] = fromOPCUID;
2004
                        newRow["ToDrawing"] = toDrawingName;
2005
                        newRow["ToDrawingUID"] = toDrawingUID;
2006
                        newRow["ToOPCUID"] = toOPCUID;
2007

    
2008
                        dt.Rows.Add(newRow);
2009
                    }
2010
                }
2011
            }
2012

    
2013
            return dt;
2014
        }
2015

    
2016
        private DataTable GetTopologyRule()
2017
        {
2018
            DataTable dt = DB.SelectTopologyRule();
2019

    
2020
            return dt;
2021
        }
2022

    
2023
        private bool IsConnected(Item item1, Item item2)
2024
        {
2025
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
2026
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
2027
                return true;
2028
            else
2029
                return false;
2030
        }
2031

    
2032
        private void SaveNozzleAndEquipment()
2033
        {
2034
            List<Item> nozzles = new List<Item>();
2035
            List<Equipment> equipments = new List<Equipment>();
2036
            foreach (Document document in Documents)
2037
            {
2038
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
2039
                equipments.AddRange(document.Equipments);
2040
            }
2041

    
2042

    
2043
            DataTable nozzleDT = new DataTable();
2044
            nozzleDT.Columns.Add("OID", typeof(string));
2045
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
2046
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
2047
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
2048
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
2049
            nozzleDT.Columns.Add("FLUID", typeof(string));
2050
            nozzleDT.Columns.Add("NPD", typeof(string));
2051
            nozzleDT.Columns.Add("PMC", typeof(string));
2052
            nozzleDT.Columns.Add("ROTATION", typeof(string));
2053
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
2054

    
2055
            foreach (Item item in nozzles)
2056
            {
2057
                DataRow row = nozzleDT.NewRow();
2058
                row["OID"] = item.UID;
2059

    
2060
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
2061
                if (relation != null)
2062
                {
2063
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
2064
                    equipment.Nozzles.Add(item);
2065
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
2066
                    row["Equipment_OID"] = equipment.UID;
2067
                    item.Equipment = equipment;
2068
                }
2069
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
2070
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
2071
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
2072
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
2073
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2074
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
2075
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
2076
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
2077

    
2078
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
2079
                if (angle >= Math.PI * 2)
2080
                    angle = angle - Math.PI * 2;
2081
                row["ROTATION"] = angle.ToString();
2082

    
2083
                if (item.Topology.Items.First().Equals(item))
2084
                    row["FlowDirection"] = "Outlet";
2085
                else if (item.Topology.Items.Last().Equals(item))
2086
                    row["FlowDirection"] = "Inlet";
2087
                else
2088
                    row["FlowDirection"] = string.Empty;
2089

    
2090
                nozzleDT.Rows.Add(row);
2091
            }
2092

    
2093
            DataTable equipDT = new DataTable();
2094
            equipDT.Columns.Add("OID", typeof(string));
2095
            equipDT.Columns.Add("ITEMTAG", typeof(string));
2096
            equipDT.Columns.Add("XCOORDS", typeof(string));
2097
            equipDT.Columns.Add("YCOORDS", typeof(string));
2098

    
2099
            foreach (Equipment equipment in equipments)
2100
            {
2101
                DataRow row = equipDT.NewRow();
2102
                row["OID"] = equipment.UID;
2103
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
2104
                {
2105
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
2106
                    if (attribute != null)
2107
                        equipment.ItemTag = attribute.Value;
2108
                }
2109
                else
2110
                    equipment.ItemTag = equipment.Name;
2111

    
2112
                row["ITEMTAG"] = equipment.ItemTag;
2113
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
2114
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
2115

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

    
2119
                equipDT.Rows.Add(row);
2120
            }
2121

    
2122
            Equipment = equipDT;
2123
            Nozzle = nozzleDT;
2124
        }
2125

    
2126
        private void SavePSNData()
2127
        {
2128
            try
2129
            {
2130
                DataTable pathItemsDT = new DataTable();
2131
                pathItemsDT.Columns.Add("OID", typeof(string));
2132
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
2133
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
2134
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
2135
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
2136
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
2137
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
2138
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
2139
                pathItemsDT.Columns.Add("Class", typeof(string));
2140
                pathItemsDT.Columns.Add("SubClass", typeof(string));
2141
                pathItemsDT.Columns.Add("TYPE", typeof(string));
2142
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
2143
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
2144
                pathItemsDT.Columns.Add("NPD", typeof(string));
2145
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
2146
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
2147
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
2148
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
2149
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
2150
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
2151
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
2152
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
2153

    
2154
                DataTable sequenceDataDT = new DataTable();
2155
                sequenceDataDT.Columns.Add("OID", typeof(string));
2156
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
2157
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
2158
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2159

    
2160
                DataTable pipeSystemNetworkDT = new DataTable();
2161
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
2162
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
2163
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
2164
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
2165
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
2166
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
2167
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2168
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
2169
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
2170
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
2171
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
2172
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
2173
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
2174
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
2175
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
2176
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
2177
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
2178
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
2179
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
2180

    
2181
                DataTable topologySetDT = new DataTable();
2182
                topologySetDT.Columns.Add("OID", typeof(string));
2183
                topologySetDT.Columns.Add("Type", typeof(string));
2184
                topologySetDT.Columns.Add("SubType", typeof(string));
2185
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
2186
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
2187
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
2188
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
2189

    
2190
                DataTable pipelineDT = new DataTable();
2191
                pipelineDT.Columns.Add("OID", typeof(string));
2192
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
2193
                pipelineDT.Columns.Add("FLUID", typeof(string));
2194
                pipelineDT.Columns.Add("PMC", typeof(string));
2195
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
2196
                pipelineDT.Columns.Add("INSULATION", typeof(string));
2197
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
2198
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
2199
                pipelineDT.Columns.Add("Unit", typeof(string));
2200

    
2201
                DataTable pipesystemDT = new DataTable();
2202
                pipesystemDT.Columns.Add("OID", typeof(string));
2203
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
2204
                pipesystemDT.Columns.Add("FLUID", typeof(string));
2205
                pipesystemDT.Columns.Add("PMC", typeof(string));
2206
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
2207
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
2208

    
2209
                // Set Vent/Drain Info
2210
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
2211
                DataTable dt = DB.SelectVentDrainSetting();
2212
                foreach (DataRow row in dt.Rows)
2213
                {
2214
                    string groupID = row["GROUP_ID"].ToString();
2215
                    string desc = row["DESCRIPTION"].ToString();
2216
                    int index = Convert.ToInt32(row["INDEX"]);
2217
                    string name = row["NAME"].ToString();
2218

    
2219
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
2220
                    if (ventDrainInfo == null)
2221
                    {
2222
                        ventDrainInfo = new VentDrainInfo(groupID);
2223
                        ventDrainInfo.Description = desc;
2224
                        VentDrainInfos.Add(ventDrainInfo);
2225
                    }
2226

    
2227
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
2228
                    {
2229
                        Index = index,
2230
                        Name = name
2231
                    });
2232
                }
2233
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2234
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
2235

    
2236
                #region Keyword Info
2237
                KeywordInfo KeywordInfos = new KeywordInfo();
2238
                DataTable dtKeyword = DB.SelectKeywordsSetting();
2239
                foreach (DataRow row in dtKeyword.Rows)
2240
                {
2241
                    int index = Convert.ToInt32(row["INDEX"]);
2242
                    string name = row["NAME"].ToString();
2243
                    string keyword = row["KEYWORD"].ToString();
2244

    
2245
                    //KeywordInfo keywordInfo = new KeywordInfo();   
2246
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
2247
                    {
2248
                        Index = index,
2249
                        Name = name,
2250
                        Keyword = keyword
2251
                    });
2252
                }
2253
                #endregion
2254

    
2255
                #region ValveGrouping Info
2256
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
2257
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
2258
                foreach (DataRow row in dtValveGroupung.Rows)
2259
                {
2260
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
2261
                    {
2262
                        OID = row["OID"].ToString(),
2263
                        GroupType = row["GroupType"].ToString(),
2264
                        TagIdentifier = row["TagIdentifier"].ToString(),
2265
                        AttributeName = row["AttributeName"].ToString(),
2266
                        SppidSymbolName = row["SppidSymbolName"].ToString()
2267
                    });
2268
                }
2269
                #endregion
2270

    
2271
                #region EquipmentNoPocket Info
2272
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
2273
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
2274
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
2275
                {
2276
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
2277
                    {
2278
                        Index = Convert.ToInt32(row["INDEX"]),
2279
                        Type = row["TYPE"].ToString(),
2280
                        Name = row["NAME"].ToString()
2281
                    });
2282
                }
2283
                #endregion
2284

    
2285
                #region EquipmentAirFinCooler Info
2286
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
2287
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
2288
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
2289
                {
2290
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
2291
                    {
2292
                        Type = row["Type"].ToString(),
2293
                        Name = row["Name"].ToString()
2294
                    });
2295
                }
2296
                #endregion
2297

    
2298
                // key = 미입력 branch
2299
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
2300
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
2301
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
2302
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
2303
                foreach (PSNItem PSNItem in PSNItems)
2304
                {
2305
                    try
2306
                    {
2307
                        int psnOrder = 0;
2308
                        int index = 0;
2309
                        bool bPSNStart = true;
2310
                        string sPSNData = string.Empty;
2311
                        bool bVentDrain = false;
2312

    
2313
                      List<Group> Groups = PSNItem.Groups;
2314
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
2315
                        List<Item> valveGroupingItem = new List<Item>();
2316

    
2317
                        //VentDrain 검사
2318
                        if (PSNItem.Groups.Count.Equals(1))
2319
                        {
2320
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
2321
                            for (int g = 0; g < Groups.Count; g++)
2322
                            {
2323
                                Group group = Groups[g];
2324

    
2325
                                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2326
                                {
2327
                                    if(!bVentDrain)
2328
                                    {
2329
                                        for (int i = 0; i < group.Items.Count; i++)
2330
                                        {
2331
                                            Item item = group.Items[i];
2332
                                            if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2333
                                                endInfos.Add(ventDrainInfo);
2334
                                            else
2335
                                            {
2336
                                                endInfos.Clear();
2337
                                                if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2338
                                                    endInfos.Add(ventDrainInfo);
2339
                                            }
2340

    
2341
                                            if (ventDrainInfo.VentDrainItems.Count().Equals(endInfos.Count()))
2342
                                            {
2343
                                                bVentDrain = true;
2344
                                                break;
2345
                                            }
2346
                                        }
2347
                                    }                                   
2348
                                }                               
2349

    
2350
                                if (!bVentDrain)
2351
                                {
2352
                                    endInfos = new List<VentDrainInfo>();
2353

    
2354
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2355
                                    {
2356
                                        if (!bVentDrain)
2357
                                        {
2358
                                            for (int i = 0; i < group.Items.Count; i++)
2359
                                            {
2360
                                                Item item = group.Items[group.Items.Count - i - 1];
2361

    
2362
                                                if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2363
                                                    endInfos.Add(ventDrainInfo);
2364
                                                else
2365
                                                {
2366
                                                    endInfos.Clear();
2367
                                                    if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2368
                                                        endInfos.Add(ventDrainInfo);
2369
                                                }
2370

    
2371
                                                if (ventDrainInfo.VentDrainItems.Count().Equals(endInfos.Count()))
2372
                                                {
2373
                                                    bVentDrain = true;
2374
                                                    break;
2375
                                                }
2376
                                            }
2377
                                        }
2378
                                    }
2379
                                }
2380
                            }
2381
                        }
2382

    
2383
                        try
2384
                        {
2385
                            foreach (Group group in PSNItem.Groups)
2386
                            {
2387
                                foreach (Item item in group.Items)
2388
                                {
2389
                                    string VgTag = string.Empty;
2390
                                    
2391
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
2392
                                    {
2393
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
2394
                                        string value = string.Empty;
2395

    
2396
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
2397
                                            value = "NoSelection";
2398
                                        else
2399
                                        {
2400
                                            if(item.Attributes.Find(x => x.Name == valveitem.AttributeName) == null)
2401
                                                value = "NoSelection";
2402
                                            else
2403
                                                value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
2404
                                        }
2405

    
2406
                                        if (valveitem.GroupType == "Scope Break")
2407
                                            VgTag = "Scope Break";
2408
                                        else
2409
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
2410

    
2411
                                    }
2412

    
2413
                                    string PathitemUID = string.Empty;
2414
                                    if (item.BranchItems.Count == 0)
2415
                                    {
2416
                                        PathitemUID = item.UID;
2417
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2418
                                        CreateSequenceDataDataRow(PathitemUID);
2419
                                        index++;
2420
                                    }
2421
                                    else
2422
                                    {
2423
                                        PathitemUID = item.UID + "_L1";
2424
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2425
                                        CreateSequenceDataDataRow(PathitemUID);
2426
                                        index++;
2427
                                        for (int i = 0; i < item.BranchItems.Count; i++)
2428
                                        {
2429
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
2430
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
2431
                                            index++;
2432

    
2433
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
2434
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
2435
                                            index++;
2436

    
2437
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
2438
                                                startBranchDic.Add(item.BranchItems[i], item);
2439
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
2440
                                                endBranchDic.Add(item.BranchItems[i], item);
2441
                                        }
2442
                                    }
2443

    
2444
                                    if (bPSNStart)
2445
                                    {
2446
                                        CreatePipeSystemNetworkDataRow();
2447
                                        sPSNData = item.TopologyData;
2448
                                        psnOrder++;
2449
                                        bPSNStart = false;
2450
                                    }
2451
                                    else
2452
                                    {
2453
                                        if (item.TopologyData != sPSNData)
2454
                                        {
2455
                                            CreatePipeSystemNetworkDataRow();
2456
                                            sPSNData = item.TopologyData;
2457
                                            psnOrder++;
2458
                                        }
2459
                                    }
2460

    
2461
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
2462
                                    {
2463
                                        DataRow newRow = pathItemsDT.NewRow();
2464

    
2465
                                        if (itemType == "Nozzles")
2466
                                        {
2467
                                            newRow["Equipment_OID"] = item.Equipment != null ? item.Equipment.UID : "";
2468
                                        }
2469

    
2470
                                        newRow["OID"] = itemOID;
2471
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2472
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
2473
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2474
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2475
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
2476
                                        newRow["ITEMTAG"] = GetItemTag(item);
2477
                                        newRow["Class"] = GetClass(item, itemOID);
2478
                                        string subClass = GetSubClass(item, itemOID);
2479
                                        newRow["SubClass"] = subClass;
2480

    
2481
                                        if (item.ItemType == ItemType.Symbol)
2482
                                            newRow["TYPE"] = item.ID2DBName;
2483
                                        else if (item.ItemType == ItemType.Line)
2484
                                            newRow["TYPE"] = item.ID2DBType;
2485
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2486

    
2487
                                        // NPD
2488
                                        if (item.LineNumber != null)
2489
                                        {
2490
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2491
                                            if (attribute != null)
2492
                                                newRow["NPD"] = attribute.Value;
2493
                                        }
2494
                                        else
2495
                                            newRow["NPD"] = null;
2496

    
2497
                                        newRow["GROUPTAG"] = GROUPTAG;
2498
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2499
                                        if (branchItem == null)
2500
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2501
                                        else
2502
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2503

    
2504
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2505
                                        newRow["EGTConnectedPoint"] = 0;
2506
                                        pathItemsDT.Rows.Add(newRow);
2507
                                    }
2508

    
2509

    
2510
                                    void CreateSequenceDataDataRow(string itemOID)
2511
                                    {
2512
                                        DataRow newRow = sequenceDataDT.NewRow();
2513
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2514
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2515
                                        newRow["PathItem_OID"] = itemOID;
2516
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2517

    
2518
                                        sequenceDataDT.Rows.Add(newRow);
2519
                                    }
2520

    
2521
                                    void CreatePipeSystemNetworkDataRow()
2522
                                    {
2523
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2524
                                        string FluidCode = string.Empty;
2525
                                        if (lineNumber != null)
2526
                                        {
2527
                                            List<Attribute> att = lineNumber.Attributes;
2528
                                            if (att != null)
2529
                                            {
2530
                                                List<string> oid = new List<string>();
2531
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2532
                                                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;
2533
                                                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;
2534
                                                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;
2535
                                                //InsulationPurpose
2536
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2537
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2538

    
2539
                                                string PipeSystem_OID = string.Join("-", oid);
2540

    
2541
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2542
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2543

    
2544
                                                string OID = string.Join("-", oid);
2545
                                                string FluidCodeGL = string.Empty;
2546
                                                string PMCGL = string.Empty;
2547

    
2548

    
2549
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2550
                                                {
2551
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2552
                                                    newPipelineRow["OID"] = OID;
2553
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2554
                                                    newPipelineRow["FLUID"] = FluidCode;
2555
                                                    newPipelineRow["PMC"] = PMC;
2556
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2557
                                                    newPipelineRow["INSULATION"] = INSULATION;
2558
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2559
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2560
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2561
                                                    pipelineDT.Rows.Add(newPipelineRow);
2562
                                                }
2563

    
2564
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2565
                                                {
2566
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2567
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2568
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2569
                                                    newPipesystemRow["FLUID"] = FluidCode;
2570
                                                    newPipesystemRow["PMC"] = PMC;
2571
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2572
                                                    string GroundLevel = string.Empty;
2573
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2574
                                                    {
2575
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2576
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2577
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2578
                                                            GroundLevel = "AG";
2579
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2580
                                                            GroundLevel = "UG";
2581
                                                        else
2582
                                                            GroundLevel = "AG_UG";
2583
                                                    }
2584
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2585

    
2586
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2587
                                                }
2588
                                            }
2589
                                        }
2590

    
2591
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2592
                                        newRow["OID"] = PSNItem.PSN_OID();
2593

    
2594
                                        newRow["OrderNumber"] = psnOrder;
2595
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2596
                                        PSNItem.KeywordInfos = KeywordInfos;
2597
                                        PSNItem.Nozzle = Nozzle;
2598

    
2599
                                        string FromType = string.Empty;
2600
                                        Item From_item = new Item();
2601

    
2602
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
2603
                                        string status = string.Empty;
2604
                                        status = PSNItem.Status;                                      
2605

    
2606
                                        if (PSNItem.IsKeyword)
2607
                                        {
2608
                                            PSNItem.StartType = PSNType.Equipment;
2609
                                        }
2610
                                        string ToType = string.Empty;
2611
                                        Item To_item = new Item();
2612
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
2613
                                        if (PSNItem.IsKeyword)
2614
                                        {
2615
                                            PSNItem.EndType = PSNType.Equipment;
2616
                                        }
2617
                                                   
2618
                                        newRow["FROM_DATA"] = FROM_DATA;
2619
                                        newRow["TO_DATA"] = TO_DATA;
2620
                                       
2621
                                        newRow["Type"] = PSNItem.GetPSNType();
2622

    
2623
                                       
2624
                                        if(psnOrder == 0) //order 0일땐 그냥 붙여줌
2625
                                        {
2626
                                            if (!string.IsNullOrEmpty(PSNItem.Status)) //to에 status가 있다면
2627
                                            {
2628
                                                status += PSNItem.Status;
2629
                                            }                                            
2630
                                        }
2631
                                        else if (psnOrder > 0) //0보다 크면 
2632
                                        {
2633
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2634
                                            if (psnOrder == 1) //1이면 0번 Order에 From Status 값만 남김 
2635
                                            {
2636
                                                dr["Status"] = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty; //status;
2637
                                            }
2638
                                            if (psnOrder > 1) // 2 -> 1 3->2 엔 status 값 삭제
2639
                                            {
2640
                                                dr["Status"] = string.Empty;
2641
                                            }
2642

    
2643
                                            status = PSNItem.Status;
2644
                                            if (dr != null)
2645
                                            {
2646
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2647
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2648
                                                newRow["Type"] = dr.Field<string>("Type");
2649
                                            }
2650
                                        }
2651

    
2652
                                        
2653
                                    
2654
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2655
                                        string[] st = status.Split(new string[] { ", " }, StringSplitOptions.None);
2656
                                        if (st.Count() > 1)
2657
                                        {
2658
                                            status = string.Join(", ", st.Distinct());                                                                                     
2659
                                        }
2660
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2661
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
2662

    
2663

    
2664
                                        newRow["IsValid"] = PSNItem.IsValid;
2665
                                        newRow["Status"] = status;
2666
                                        newRow["PBS"] = PSNItem.GetPBSData();
2667

    
2668
                                        List<string> drawingNames = new List<string>();
2669
                                        foreach (Group _group in PSNItem.Groups)
2670
                                        {
2671
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2672
                                            {
2673
                                                if (drawingNames.Count == 0)
2674
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2675
                                                else
2676
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2677
                                                drawingNames.Add(_group.Document.DrawingName);
2678
                                            }
2679
                                        }
2680

    
2681
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2682
                                        if (bVentDrain)
2683
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2684
                                        else
2685
                                            newRow["IncludingVirtualData"] = "No";
2686
                                        //    return;
2687
                                        //newRow["IncludingVirtualData"] = "No";
2688
                                        newRow["PSNAccuracy"] = "100";
2689

    
2690
                                        string Pocket = "No";
2691
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2692
                                        if (Condition.Equals("Flare"))
2693
                                            Pocket = "Yes";
2694

    
2695
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null) 
2696
                                        {
2697
                                          //  string itemName = From_item.Name;
2698
                                            Equipment Equipment = From_item.Equipment;
2699
                                      
2700
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2701
                                          
2702

    
2703
                                            if (nopocket != null)
2704
                                            {
2705
                                                DataRow bNozzle = null;
2706
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2707
                                                {
2708
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2709
                                                    if (drNozzle != null)
2710
                                                    {
2711
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2712
                                                        {
2713
                                                            bNozzle = drNozzle;
2714
                                                        }
2715

    
2716
                                                        if (bNozzle == null)
2717
                                                        {
2718
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2719

    
2720
                                                            if (drNozzle != null)
2721
                                                            {
2722
                                                                bNozzle = drNozzle;
2723
                                                                foreach (DataRow it in nozzleRows)
2724
                                                                {
2725
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2726
                                                                    {
2727
                                                                        bNozzle = null;
2728
                                                                        break;
2729
                                                                    }
2730
                                                                }
2731
                                                            }
2732
                                                        }
2733
                                                    }
2734

    
2735
                                                    if (bNozzle != null)
2736
                                                        Pocket = "Yes";
2737
                                                }
2738
                                                else
2739
                                                    Pocket = "Yes";
2740
                                            }
2741
                                        }
2742
                                        
2743
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null) //To는 전체
2744
                                        {
2745
                                           // string itemName = To_item.Name;
2746
                                            Equipment Equipment = To_item.Equipment;
2747
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2748
                                            if (nopocket != null)
2749
                                            {
2750
                                                DataRow bNozzle = null;
2751
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2752
                                                {
2753
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2754
                                                    if(drNozzle != null)
2755
                                                    {
2756
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2757
                                                        {
2758
                                                            bNozzle = drNozzle;
2759
                                                        }
2760

    
2761
                                                        if (bNozzle == null)
2762
                                                        {
2763
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2764

    
2765
                                                            if (drNozzle != null)
2766
                                                            {
2767
                                                                bNozzle = drNozzle;
2768
                                                                foreach (DataRow it in nozzleRows)
2769
                                                                {
2770
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2771
                                                                    {
2772
                                                                        bNozzle = null;
2773
                                                                        break;
2774
                                                                    }
2775
                                                                }
2776
                                                            }
2777
                                                        }
2778
                                                    }                                                   
2779

    
2780
                                                    if (bNozzle != null)
2781
                                                        Pocket = "Yes";
2782
                                                }
2783
                                                else
2784
                                                    Pocket = "Yes";
2785
                                            }
2786
                                        }
2787
                                        
2788
                                        newRow["Pocket"] = Pocket;
2789
                                        string AFC = "P2";
2790
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2791
                                        {
2792
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2793
                                                AFC = "P1\\" + From_item.Equipment.Name;
2794
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2795
                                                newRow["PUMP"] = "PUMP";
2796
                                        }
2797

    
2798
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2799
                                        {
2800
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2801
                                                AFC = "P1\\" + To_item.Equipment.Name;
2802
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2803
                                                newRow["PUMP"] = "PUMP";
2804
                                        }
2805

    
2806
                                        newRow["AFC"] = AFC;
2807

    
2808
                                        newRow["EGTag"] = string.Empty;
2809
                                        newRow["HasMLTags"] = "False";
2810
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2811
                                    }
2812
                                }
2813

    
2814
                            }
2815
                        
2816

    
2817
                        }
2818
                        catch (Exception ex)
2819
                        {
2820
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2821
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2822
                        }
2823

    
2824
                        //TopologySet 관련
2825
                        foreach (Topology topology in PSNItem.Topologies)
2826
                        {
2827
                            DataRow newRow = topologySetDT.NewRow();
2828
                            newRow["OID"] = topology.FullName;
2829
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
2830
                            if (bVentDrain)
2831
                                newRow["SubType"] = "Vent_Drain";
2832
                            else
2833
                                newRow["SubType"] = null;
2834
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
2835
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
2836
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
2837
                            newRow["TailItemSPID"] = topology.Items.First().UID;
2838
                            topologySetDT.Rows.Add(newRow);
2839
                        }
2840

    
2841
                    }
2842
                    catch (Exception ee)
2843
                    {
2844

    
2845
                    }
2846
                }
2847

    
2848

    
2849
                foreach (var item in startBranchDic)
2850
                {
2851
                    string uid = item.Key.UID;
2852
                    string topologyName = item.Value.Topology.FullName;
2853
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2854

    
2855
                    if (rows.Length == 1)
2856
                    {
2857
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2858
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2859
                    }
2860
                    else if (rows.Length > 1)
2861
                    {
2862
                        DataRow targetRow = null;
2863
                        int index = int.MaxValue;
2864
                        foreach (DataRow row in rows)
2865
                        {
2866
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2867
                            if (split.StartsWith("L"))
2868
                            {
2869
                                int num = Convert.ToInt32(split.Remove(0, 1));
2870
                                if (index > num)
2871
                                {
2872
                                    index = num;
2873
                                    targetRow = row;
2874
                                }
2875
                            }
2876
                        }
2877

    
2878
                        if (targetRow != null)
2879
                        {
2880
                            targetRow["BranchTopologySet_OID"] = topologyName;
2881
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2882
                        }
2883
                    }
2884
                }
2885

    
2886
                foreach (var item in endBranchDic)
2887
                {
2888
                    string uid = item.Key.UID;
2889
                    string topologyName = item.Value.Topology.FullName;
2890
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2891
                    if (rows.Length == 1)
2892
                    {
2893
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2894
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2895
                    }
2896
                    else if (rows.Length > 1)
2897
                    {
2898
                        DataRow targetRow = null;
2899
                        int index = int.MinValue;
2900
                        foreach (DataRow row in rows)
2901
                        {
2902
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2903
                            if (split.StartsWith("L"))
2904
                            {
2905
                                int num = Convert.ToInt32(split.Remove(0, 1));
2906
                                if (index < num)
2907
                                {
2908
                                    index = num;
2909
                                    targetRow = row;
2910
                                }
2911
                            }
2912
                        }
2913

    
2914
                        if (targetRow != null)
2915
                        {
2916
                            targetRow["BranchTopologySet_OID"] = topologyName;
2917
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2918
                        }
2919
                    }
2920
                }
2921

    
2922
                PathItems = pathItemsDT;
2923
                SequenceData = sequenceDataDT;
2924
                PipeSystemNetwork = pipeSystemNetworkDT;
2925
                TopologySet = topologySetDT;
2926
                PipeLine = pipelineDT;
2927
                PipeSystem = pipesystemDT;
2928
            }
2929
            catch (Exception ex)
2930
            {
2931
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2932
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2933
            }
2934
        }
2935

    
2936
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2937
        {
2938
            foreach (double lacc in lstAcc)
2939
            {
2940
                acc *= lacc;
2941
            }
2942
            return acc;
2943
        }
2944

    
2945
        private void UpdateSubType()
2946
        {
2947
            try
2948
            {
2949
                foreach (PSNItem PSNItem in PSNItems)
2950
                {
2951
                    if (PSNItem.IsBypass)
2952
                    {
2953
                        foreach (Topology topology in PSNItem.Topologies)
2954
                        {
2955
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2956
                            if (rows.Length.Equals(1))
2957
                                rows.First()["SubType"] = "Bypass";
2958
                        }
2959
                    }
2960

    
2961
                    if (PSNItem.StartType == PSNType.Header)
2962
                    {
2963
                        Topology topology = PSNItem.Topologies.First();
2964
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2965
                        if (rows.Length.Equals(1))
2966
                            rows.First()["SubType"] = "Header";
2967
                    }
2968
                    else if (PSNItem.EndType == PSNType.Header)
2969
                    {
2970
                        Topology topology = PSNItem.Topologies.Last();
2971
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2972
                        if (rows.Length.Equals(1))
2973
                            rows.First()["SubType"] = "Header";
2974
                    }
2975
                }
2976

    
2977

    
2978
                foreach (Topology topology in Topologies)
2979
                {
2980
                    try
2981
                    {
2982
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2983

    
2984
                        if (rows.Count() > 0)
2985
                        {
2986
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2987
                            {
2988
                                if (topology.Items == null)
2989
                                    continue;
2990

    
2991
                                Item firstItem = topology.Items.First();
2992
                                Item lastItem = topology.Items.Last();
2993

    
2994
                                List<Relation> relations = new List<Relation>();
2995

    
2996
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2997
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2998

    
2999
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
3000
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
3001

    
3002
                                if (relations.Count > 0)
3003
                                    rows.First()["SubType"] = "OtherSystem";
3004
                            }
3005
                        }
3006
                    }
3007
                    catch (Exception ex)
3008
                    {
3009

    
3010
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
3011
                    }
3012
                }
3013

    
3014
                foreach (DataRow row in TopologySet.Rows)
3015
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
3016
                        row["SubType"] = "Normal";
3017
            }
3018
            catch (Exception ex)
3019
            {
3020
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3021
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
3022
            }
3023
        }
3024

    
3025
        private bool IsBypass(PSNItem PSNItem)
3026
        {
3027
            bool bResult = false;
3028

    
3029
            if (PSNItem.GetPSNType() == "B2B")
3030
            {
3031
                Group firstGroup = PSNItem.Groups.First();
3032
                Group lastGroup = PSNItem.Groups.Last();
3033
                Item firstItem = firstGroup.Items.First();
3034
                Item lastItem = lastGroup.Items.Last();
3035

    
3036
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
3037
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
3038

    
3039
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
3040
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
3041
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
3042
                    bResult = true;
3043
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
3044
                    bResult = true;
3045
            }
3046

    
3047
            Item GetConnectedItemByPSN(Item item)
3048
            {
3049
                Item result = null;
3050

    
3051
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
3052
                if (relation != null)
3053
                    result = relation.Item;
3054

    
3055

    
3056
                return result;
3057
            }
3058

    
3059
            return bResult;
3060
        }
3061

    
3062
        private void DeleteVentDrain()
3063
        {
3064
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
3065

    
3066
            foreach (DataRow dataRow in ventdrainRows)
3067
            {
3068
                dataRow.Delete();
3069
            }
3070
        }
3071

    
3072
        private void UpdateAccuracy()
3073
        {
3074
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
3075
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
3076
            List<double> lstAcc = null;
3077
            string Status = string.Empty;
3078

    
3079
            foreach (DataRow dataRow in statusRows)
3080
            {
3081
                lstAcc = new List<double>();
3082
                Status = dataRow.Field<string>("Status");
3083
                if (!string.IsNullOrEmpty(Status))
3084
                {
3085
                    string[] arrStatus = Status.Split(',');
3086
                    foreach (string arrstr in arrStatus)
3087
                    {
3088
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
3089
                            lstAcc.Add(0.75);
3090

    
3091
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
3092
                            lstAcc.Add(0.7);
3093

    
3094
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
3095
                            lstAcc.Add(0.5);
3096

    
3097
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
3098
                            lstAcc.Add(0.65);
3099

    
3100
                        if (arrstr.Contains(Rule5)) //Line Disconnected
3101
                            lstAcc.Add(0.6);
3102
                    }
3103
                }
3104

    
3105
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
3106
                if (PSNAccuracy == "100")
3107
                    PSNAccuracy = "1";
3108

    
3109
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
3110
                //if (PSNAccuracy != "100")
3111
                //{
3112
                //    //dataRow["IncludingVirtualData"] = "No";
3113
                dataRow["PSNAccuracy"] = PSNAccuracy;
3114
                //}
3115
            }
3116
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
3117
            foreach (DataRow dr in dt.Rows)
3118
            {
3119
                string oid = dr.Field<string>("OID");
3120
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
3121
                double totalDdr = 0;
3122
                foreach (DataRow ddr in select)
3123
                {
3124
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
3125
                    if (acc == 100) acc = 1;
3126
                    if (totalDdr == 0) totalDdr = acc;
3127
                    else totalDdr *= acc;
3128
                }
3129

    
3130
                totalDdr *= 100;
3131

    
3132
                if (totalDdr != 100)
3133
                {
3134
                    foreach (DataRow ddr in select)
3135
                    {
3136
                        ddr["IncludingVirtualData"] = "Yes";
3137
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
3138
                        ddr["IsValid"] = "Error";
3139
                    }
3140
                }
3141
                else
3142
                {
3143
                    foreach (DataRow ddr in select)
3144
                    {
3145
                        ddr["IncludingVirtualData"] = "No";
3146
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
3147
                    }
3148
                }
3149
            }
3150

    
3151
        }
3152

    
3153
        private void UpdateKeywordForPSN()
3154
        {
3155
            #region Keyword Info
3156
            KeywordInfo KeywordInfos = new KeywordInfo();
3157
            DataTable dtKeyword = DB.SelectKeywordsSetting();
3158
            foreach (DataRow row in dtKeyword.Rows)
3159
            {
3160
                int index = Convert.ToInt32(row["INDEX"]);
3161
                string name = row["NAME"].ToString();
3162
                string keyword = row["KEYWORD"].ToString();
3163

    
3164
                //KeywordInfo keywordInfo = new KeywordInfo();   
3165
                KeywordInfos.KeywordItems.Add(new KeywordItem()
3166
                {
3167
                    Index = index,
3168
                    Name = name,
3169
                    Keyword = keyword
3170
                });
3171
            }
3172
            #endregion
3173

    
3174
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
3175
            foreach (DataRow dataRow in endofHeaderRows)
3176
            {
3177
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3178

    
3179
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
3180
                {
3181
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3182
                    DataRow dr = pathItemRows.First();
3183
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
3184
                    dr["TYPE"] = "End";
3185
                    dr["ITEMTAG"] = "ENDOFHEADER";
3186
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3187
                }
3188

    
3189
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
3190
                {
3191
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3192
                    DataRow dr = pathItemRows.Last();
3193
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
3194
                    dr["TYPE"] = "End";
3195
                    dr["ITEMTAG"] = "ENDOFHEADER";
3196
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3197
                }
3198
            }
3199

    
3200
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3201
            {
3202
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
3203
                foreach (DataRow dataRow in keywordRows)
3204
                {
3205
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3206

    
3207
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
3208
                    {
3209
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3210

    
3211
                        //
3212
                        //if(.)
3213
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
3214
                        {
3215
                            DataRow dr = pathItemRows.First();
3216
                            //dr["CLASS"] = ""; //Type
3217
                            dr["TYPE"] = "End";
3218
                            dr["ITEMTAG"] = keyitem.Keyword;
3219
                            dr["DESCRIPTION"] = keyitem.Keyword;
3220
                        }
3221

    
3222
                    }
3223

    
3224
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
3225
                    {
3226
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3227

    
3228
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
3229
                        {
3230
                            DataRow dr = pathItemRows.Last();
3231
                            //dr["CLASS"] = ""; //Type
3232
                            dr["TYPE"] = "End";
3233
                            dr["ITEMTAG"] = keyitem.Keyword;
3234
                            dr["DESCRIPTION"] = keyitem.Keyword;
3235
                            //dr.Field<string>("Type")
3236
                        }
3237

    
3238
                    }
3239
                }
3240
            }
3241
        }
3242

    
3243
        private void UpdateErrorForPSN()
3244
        {
3245
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
3246
            foreach (DataRow dataRow in errorRows)
3247
            {
3248
                try
3249
                {
3250
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3251
                   
3252
                    bool change = false;
3253
                    bool bCheck = false;
3254
                    if (!PSNItem.EnableType(PSNItem.StartType))
3255
                    {
3256
                        change = true;
3257
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3258
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3259

    
3260
                        Item item = PSNItem.Groups.First().Items.First();
3261
                        try
3262
                        {
3263
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3264

    
3265
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3266
                            {
3267
                                loopRow["FROM_DATA"] = FROM_DATA;
3268
                                if (item.ItemType == ItemType.Line)
3269
                                {
3270
                                    if (loopRow.Field<string>("OrderNumber") == "0")
3271
                                    {
3272
                                        string status = loopRow.Field<string>("Status");
3273
                                        //string isvali
3274
                                        if (string.IsNullOrEmpty(status))
3275
                                            status = "Line Disconnected";
3276
                                        else if (!status.Contains("Line Disconnected"))
3277
                                            status += ", Line Disconnected";
3278
                                        loopRow["Status"] = status;
3279
                                        if (!string.IsNullOrEmpty(status))
3280
                                            loopRow["IsValid"] = "Error";
3281
                                    }
3282
                                }
3283
                            }
3284

    
3285
                            tieInPointIndex++;
3286

    
3287
                            if (item.ItemType == ItemType.Line)
3288
                            {
3289
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);                                
3290
                            }
3291
                            else
3292
                            {
3293
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
3294
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
3295

    
3296
                                bCheck = true;
3297
                            }
3298

    
3299
                            PSNItem.StartType = PSNType.Equipment;
3300
                        }
3301
                        catch (Exception ex)
3302
                        {
3303
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3304
                            return;
3305
                        }
3306
                    }
3307

    
3308
                    if (!PSNItem.EnableType(PSNItem.EndType))
3309
                    {                        
3310
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3311
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
3312
                        DataRow dr = pathItemRows.Last();
3313
                        if (change)
3314
                        {
3315
                            if(bCheck)
3316
                                dr = pathItemRows[pathItemRows.Count() - 3];
3317
                            else
3318
                            {
3319
                                dr = pathItemRows[pathItemRows.Count() - 2];
3320
                            }
3321
                        }
3322

    
3323
                        change = true;
3324
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3325

    
3326
                        Item item = PSNItem.Groups.Last().Items.Last();
3327
                        try
3328
                        {
3329
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3330

    
3331
                            
3332
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3333
                            {
3334
                                loopRow["TO_DATA"] = TO_DATA;
3335
                                if (item.ItemType == ItemType.Line)
3336
                                {
3337
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
3338
                                    {
3339
                                        string status = loopRow.Field<string>("Status");
3340
                                        if (string.IsNullOrEmpty(status))
3341
                                            status = "Line Disconnected";
3342
                                        else if (!status.Contains("Line Disconnected"))
3343
                                            status += ", Line Disconnected";
3344
                                        loopRow["Status"] = status;
3345
                                        if (!string.IsNullOrEmpty(status))
3346
                                            loopRow["IsValid"] = "Error";
3347
                                    }
3348
                                }
3349

    
3350
                            }                            
3351

    
3352
                            tieInPointIndex++;
3353

    
3354
                            if (item.ItemType == ItemType.Line)
3355
                            {
3356
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3357
                            }
3358
                            else
3359
                            {
3360
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3361
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
3362
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
3363
                               
3364
                            }
3365

    
3366
                            PSNItem.EndType = PSNType.Equipment;
3367
                        }
3368
                        catch (Exception ex)
3369
                        {
3370
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3371
                            return;
3372
                        }
3373
                    }
3374

    
3375
                    dataRow["Type"] = PSNItem.GetPSNType();
3376
                    if (change)
3377
                    {
3378
                        int rowIndex = 0;
3379
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3380
                        {
3381
                            DataRow row = PathItems.Rows[i];
3382
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
3383
                                continue;
3384
                            string sequenceData = row["SequenceData_OID"].ToString();
3385
                            string[] split = sequenceData.Split(new char[] { '_' });
3386

    
3387
                            StringBuilder sb = new StringBuilder();
3388
                            for (int j = 0; j < split.Length - 1; j++)
3389
                                sb.Append(split[j] + "_");
3390
                            sb.Append(rowIndex++);
3391
                            row["SequenceData_OID"] = sb.ToString();
3392

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

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

    
3398
                            if (seqItemRows == null)
3399
                            {
3400
                                DataRow newRow = SequenceData.NewRow();
3401
                                newRow["OID"] = sb.ToString();
3402
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3403
                                newRow["PathItem_OID"] = row["OID"];
3404
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3405
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3406
                            }
3407
                            else
3408
                            {
3409
                                seqItemRows["OID"] = sb.ToString();
3410
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3411
                                seqItemRows["PathItem_OID"] = row["OID"];
3412
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3413
                            }
3414
                        }
3415
                    }
3416

    
3417
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
3418
                    {
3419
                        DataRow newRow = PathItems.NewRow();
3420
                        newRow["OID"] = Guid.NewGuid().ToString();
3421
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3422
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3423
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3424
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3425
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
3426
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
3427
                        newRow["DESCRIPTION"] = DATA;
3428
                        newRow["Class"] = "End of line terminator";
3429
                        newRow["SubClass"] = "End of line terminator";
3430
                        newRow["TYPE"] = "End";
3431
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3432
                        newRow["NPD"] = itemRow["NPD"];
3433
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3434
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3435
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3436
                        newRow["EGTConnectedPoint"] = "0";
3437
                        return newRow;
3438
                    }
3439

    
3440
                    DataRow createLineRow(DataRow itemRow)
3441
                    {
3442
                        DataRow newRow = PathItems.NewRow();
3443
                        newRow["OID"] = Guid.NewGuid().ToString();
3444
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3445
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3446
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3447
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3448
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
3449
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3450
                        newRow["Class"] = itemRow["Class"];
3451
                        newRow["SubClass"] = itemRow["SubClass"];
3452
                        newRow["TYPE"] = itemRow["TYPE"];
3453
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3454
                        newRow["NPD"] = itemRow["NPD"];
3455
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3456
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3457
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3458
                        newRow["EGTConnectedPoint"] = "0";
3459
                        return newRow;
3460
                    }
3461
                }
3462
                catch (Exception ex)
3463
                {
3464

    
3465
                }
3466
            }
3467
        }
3468

    
3469
        private void InsertTeePSN()
3470
        {
3471
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
3472
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
3473
            bool change = false;
3474
            foreach (DataRow dataRow in branchRows)
3475
            {
3476
                try
3477
                {
3478
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3479
                    change = false;
3480

    
3481
                    if (PSNItem.StartType == PSNType.Branch)
3482
                    {
3483
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3484
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3485
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3486
                        try
3487
                        {
3488
                            if (Teeitem.ItemType == ItemType.Line)
3489
                            {
3490
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3491
                                {
3492
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3493
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3494
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3495
                                    change = true;
3496
                                }
3497

    
3498
                            }
3499
                        }
3500
                        catch (Exception ex)
3501
                        {
3502
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3503
                            return;
3504
                        }
3505
                    }
3506

    
3507
                    if (PSNItem.EndType == PSNType.Branch)
3508
                    {
3509
                        //change = true;
3510
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3511

    
3512
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3513

    
3514
                        DataRow dr = pathItemRows.Last();
3515
                        if (change)
3516
                            dr = pathItemRows[pathItemRows.Count() - 2];
3517

    
3518
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3519

    
3520
                        try
3521
                        {
3522
                            if (Teeitem.ItemType == ItemType.Line)
3523
                            {
3524
                                if (dr.Field<string>("SubClass") != "Tee")
3525
                                {
3526
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3527
                                    change = true;
3528
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3529
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3530
                                }
3531

    
3532
                            }
3533
                        }
3534
                        catch (Exception ex)
3535
                        {
3536
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3537
                            return;
3538
                        }
3539
                    }
3540

    
3541
                    if (change)
3542
                    {
3543
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3544
                        int rowIndex = 0;
3545
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3546
                        {
3547
                            DataRow row = PathItems.Rows[i];
3548
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3549
                                continue;
3550
                            string sequenceData = row["SequenceData_OID"].ToString();
3551
                            string[] split = sequenceData.Split(new char[] { '_' });
3552

    
3553
                            StringBuilder sb = new StringBuilder();
3554
                            for (int j = 0; j < split.Length - 1; j++)
3555
                                sb.Append(split[j] + "_");
3556
                            sb.Append(rowIndex++);
3557
                            row["SequenceData_OID"] = sb.ToString();
3558

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

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

    
3564
                            if (seqItemRows == null)
3565
                            {
3566
                                DataRow newRow = SequenceData.NewRow();
3567
                                newRow["OID"] = sb.ToString();
3568
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3569
                                newRow["PathItem_OID"] = row["OID"];
3570
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3571
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3572
                            }
3573
                            else
3574
                            {
3575
                                seqItemRows["OID"] = sb.ToString();
3576
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3577
                                seqItemRows["PathItem_OID"] = row["OID"];
3578
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3579
                            }
3580
                        }
3581
                    }
3582

    
3583
                    DataRow createTeeRow(DataRow itemRow)
3584
                    {
3585
                        DataRow newRow = PathItems.NewRow();
3586
                        newRow["OID"] = Guid.NewGuid().ToString();
3587
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3588
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3589
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3590
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3591
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3592
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3593
                        newRow["DESCRIPTION"] = "";
3594
                        newRow["Class"] = "Branch";
3595
                        newRow["SubClass"] = "Tee";
3596
                        newRow["TYPE"] = itemRow["TYPE"];
3597
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3598
                        newRow["NPD"] = itemRow["NPD"];
3599
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3600
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3601
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3602
                      
3603
                        newRow["EGTConnectedPoint"] = 0;
3604
                        return newRow;
3605
                    }
3606
                }
3607
                catch (Exception ex)
3608
                {
3609

    
3610
                }
3611
            }
3612
        }
3613
    }
3614

    
3615
    public class PSNItem
3616
    {
3617
        public PSNItem(int count, int Revision)
3618
        {
3619
            Groups = new List<Group>();
3620
            Topologies = new List<Topology>();
3621

    
3622
            Index = count + 1;
3623
            this.Revision = Revision;
3624
        }
3625

    
3626
        private int Revision;
3627
        public string UID { get; set; }
3628
        public List<Group> Groups { get; set; }
3629
        public List<Topology> Topologies { get; set; }
3630
        public PSNType StartType { get; set; }
3631
        public PSNType EndType { get; set; }
3632
        public int Index { get; set; }
3633
        public string IsValid { get; set; }
3634
        public bool IsKeyword { get; set; }
3635
        public string Status { get; set; }
3636
        public string IncludingVirtualData { get; set; }
3637
        public string PSNAccuracy { get; set; }
3638
        public KeywordInfo KeywordInfos = new KeywordInfo();
3639
        public DataTable Nozzle = new DataTable();
3640

    
3641
        public string PSN_OID()
3642
        {
3643
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
3644
        }
3645

    
3646
        public string GetPSNType()
3647
        {
3648
            string result = string.Empty;
3649

    
3650
            if (EnableType(StartType) && EnableType(EndType))
3651
            {
3652
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
3653
                    result = "E2E";
3654
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
3655
                    result = "B2B";
3656
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
3657
                    result = "HD2";
3658

    
3659
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
3660
                    result = "E2B";
3661
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
3662
                    result = "B2E";
3663

    
3664
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
3665
                    result = "HDB";
3666
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
3667
                    result = "HDB";
3668

    
3669
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
3670
                    result = "HDE";
3671
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
3672
                    result = "HDE";
3673
                else
3674
                    result = "Error";
3675
            }
3676
            else
3677
                result = "Error";
3678

    
3679
            return result;
3680

    
3681

    
3682
        }
3683

    
3684
        public bool EnableType(PSNType type)
3685
        {
3686
            bool result = false;
3687

    
3688
            if (type == PSNType.Branch ||
3689
                type == PSNType.Equipment ||
3690
                type == PSNType.Header)
3691
            {
3692
                result = true;
3693
            }
3694

    
3695
            return result;
3696
        }
3697

    
3698
        public bool IsBypass { get; set; }
3699

    
3700
        public string GetFromData(ref string Type, ref Item item)
3701
        {
3702
            Status = string.Empty;
3703
            string result = string.Empty;
3704
            if (IsKeyword)
3705
                IsKeyword = false;
3706
            try
3707
            {
3708
                item = Groups.First().Items.First();
3709

    
3710
                if (StartType == PSNType.Header)
3711
                    result = "ENDOFHEADER";
3712
                else if (StartType == PSNType.Branch)
3713
                {
3714
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3715
                    {
3716
                        result = item.Relations.First().Item.LineNumber.Name;
3717
                        if (item.Relations.First().Item.LineNumber.MissingLineNumber2)
3718
                        {
3719
                            Status += ", Missing LineNumber_2";
3720
                            IsValid = "Error";
3721
                        }
3722
                        if (item.Relations.First().Item.LineNumber.MissingLineNumber1)
3723
                        {
3724
                            Status += ", Missing LineNumber_1";
3725
                            IsValid = "Error";
3726
                        }
3727
                    }
3728
                    else
3729
                    {
3730
                        IsValid = "Error";
3731
                        result = "Empty LineNumber";
3732
                    }
3733
                }
3734
                else if (StartType == PSNType.Equipment)
3735
                {
3736
                    if (Groups.First().Items.First().Equipment != null)
3737
                        result = Groups.First().Items.First().Equipment.ItemTag;
3738
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
3739

    
3740
                    if (drNozzle != null)
3741
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3742
                }
3743
                else
3744
                {
3745
                    
3746
                    item = Groups.First().Items.First();
3747
                    if (item.ItemType == ItemType.Symbol)
3748
                    {
3749
                        string keyword = string.Empty;
3750
                        keyword = GetFromKeywordData(ref Type, item);
3751

    
3752
                        if (string.IsNullOrEmpty(keyword))
3753
                        {
3754
                            if (item.ID2DBType.Contains("OPC's"))
3755
                                Status += ", OPC Disconnected";
3756
                            else
3757
                                Status += ", Missing ItemTag or Description";
3758

    
3759
                            result = item.ID2DBName;
3760
                            IsValid = "Error";
3761
                        }
3762
                        else
3763
                        {
3764
                            result = keyword;
3765
                            IsKeyword = true;
3766
                        }
3767

    
3768
                    }
3769
                    else if (item.ItemType == ItemType.Line)
3770
                    {
3771
                        if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
3772
                        {
3773
                            result = item.LineNumber.Name;
3774
                            if (item.LineNumber.MissingLineNumber2)
3775
                            {
3776
                                Status += ", Missing LineNumber_2";
3777
                                IsValid = "Error";
3778
                            }
3779
                            if (item.LineNumber.MissingLineNumber1)
3780
                            {
3781
                                Status += ", Missing LineNumber_1";
3782
                                IsValid = "Error";
3783
                            }
3784
                        }
3785
                        else
3786
                        {
3787
                            IsValid = "Error";
3788
                            result = "Empty LineNumber";
3789
                        }
3790
                    }
3791
                    else
3792
                        result = "Unknown";
3793
                }
3794
            }
3795
            catch (Exception ex)
3796
            {
3797

    
3798
            }
3799

    
3800
            return result;
3801
        }
3802

    
3803
        public string GetFromKeywordData(ref string Type, Item item)
3804
        {
3805
            string result = string.Empty;
3806

    
3807
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3808
            {
3809
                if (keyitem.Name.Equals(item.Name))
3810
                {
3811
                    result = keyitem.Keyword;
3812
                    Type = item.ID2DBType;
3813
                    break;
3814
                }
3815
            }
3816

    
3817
            return result;
3818
        }
3819

    
3820
        public string GetToKeywordData(ref string Type, Item item)
3821
        {
3822
            string result = string.Empty;
3823

    
3824
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3825
            {
3826
                if (keyitem.Name.Equals(item.Name))
3827
                {
3828
                    result = keyitem.Keyword;
3829
                    Type = item.ID2DBType;
3830
                    break;
3831
                }
3832
            }
3833
            return result;
3834
        }
3835

    
3836
        public string GetToData(ref string ToType, ref Item item)
3837
        {
3838
            string result = string.Empty;
3839
            Status = string.Empty;
3840

    
3841
            if (IsKeyword)
3842
                IsKeyword = false;
3843

    
3844
            item = Groups.Last().Items.Last();
3845

    
3846
            if (EndType == PSNType.Header)
3847
                result = "ENDOFHEADER";
3848
            else if (EndType == PSNType.Branch)
3849
            {
3850
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3851
                {
3852
                    result = item.Relations.Last().Item.LineNumber.Name;
3853
                    if (item.Relations.Last().Item.LineNumber.MissingLineNumber2)
3854
                    {
3855
                        Status += ", Missing LineNumber_2";
3856
                        IsValid = "Error";
3857
                    }
3858
                    if (item.Relations.Last().Item.LineNumber.MissingLineNumber1)
3859
                    {
3860
                        Status += ", Missing LineNumber_1";
3861
                        IsValid = "Error";
3862
                    }
3863
                }
3864
                else
3865
                {
3866
                    IsValid = "Error";
3867
                    result = "Empty LineNumber";
3868
                }                
3869
            }
3870
            else if (EndType == PSNType.Equipment)
3871
            {
3872
                if (Groups.Last().Items.Last().Equipment != null)
3873
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3874

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

    
3877
                if (drNozzle != null)
3878
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3879
            }
3880
            else
3881
            {
3882
                
3883
                item = Groups.Last().Items.Last();
3884
                if (item.ItemType == ItemType.Symbol)
3885
                {
3886
                    string keyword = string.Empty;
3887
                    keyword = GetToKeywordData(ref ToType, item);
3888

    
3889
                    if (string.IsNullOrEmpty(keyword))
3890
                    {
3891
                        if (item.ID2DBType.Contains("OPC's"))
3892
                            Status += ", OPC Disconnected";
3893
                        else
3894
                            Status += ", Missing ItemTag or Description";
3895

    
3896
                        result = item.ID2DBName;
3897
                        IsValid = "Error";
3898
                    }
3899
                    else
3900
                    {
3901
                        result = keyword;
3902
                        IsKeyword = true;
3903
                    }
3904

    
3905
                }
3906
                else if (item.ItemType == ItemType.Line)
3907
                {
3908
                    if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
3909
                    {
3910
                        result = item.LineNumber.Name;
3911
                        if (item.LineNumber.MissingLineNumber2)
3912
                        {
3913
                            Status += ", Missing LineNumber_2";
3914
                            IsValid = "Error";
3915
                        }
3916
                        if (item.LineNumber.MissingLineNumber1)
3917
                        {
3918
                            Status += ", Missing LineNumber_1";
3919
                            IsValid = "Error";
3920
                        }
3921
                    }
3922
                    else
3923
                    {
3924
                        IsValid = "Error";
3925
                        result = "Empty LineNumber";
3926
                    }
3927
                }
3928
                else
3929
                    result = "Unknown";
3930
            }
3931
            return result;
3932
        }
3933

    
3934
        public string GetPBSData()
3935
        {
3936
            string result = string.Empty;
3937
            List<string> PBSList = new List<string>();
3938
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3939
            {
3940
                string attrValue = Settings.Default.PBSSettingValue;
3941

    
3942
                foreach (Group group in Groups)
3943
                {
3944
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3945
                    foreach (LineNumber lineNumber in lineNumbers)
3946
                    {
3947
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3948
                        if (attribute != null)
3949
                        {
3950
                            string value = attribute.Value;
3951
                            if (!PBSList.Contains(value))
3952
                                PBSList.Add(value);
3953
                        }
3954
                    }
3955
                }
3956
            }
3957
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3958
            {
3959
                string attrValue = Settings.Default.PBSSettingValue;
3960

    
3961
                foreach (Group group in Groups)
3962
                {
3963
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3964
                    foreach (Item item in items)
3965
                    {
3966
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3967
                        if (!PBSList.Contains(value))
3968
                            PBSList.Add(value);
3969
                    }
3970
                }
3971
            }
3972
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3973
            {
3974
                string attrValue = Settings.Default.PBSSettingValue;
3975

    
3976
                foreach (Group group in Groups)
3977
                {
3978
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3979
                    foreach (Document document in documents)
3980
                    {
3981
                        string name = document.DrawingName;
3982

    
3983
                        int startIndex = Settings.Default.PBSSettingStartValue;
3984
                        int endIndex = Settings.Default.PBSSettingEndValue;
3985

    
3986
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3987
                        if (!PBSList.Contains(subStr))
3988
                            PBSList.Add(subStr);
3989
                    }
3990
                }
3991
            }
3992
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3993
            {
3994
                foreach (Group group in Groups)
3995
                {
3996
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3997
                    foreach (Document document in documents)
3998
                    {
3999
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
4000
                        foreach (TextInfo textInfo in textInfos)
4001
                        {
4002
                            if (!PBSList.Contains(textInfo.Value))
4003
                                PBSList.Add(textInfo.Value);
4004
                        }
4005
                    }
4006
                }
4007
            }
4008

    
4009
            foreach (var item in PBSList)
4010
            {
4011
                if (string.IsNullOrEmpty(result))
4012
                    result = item;
4013
                else
4014
                    result += ", " + item;
4015
            }
4016
            return result;
4017
        }
4018
    }
4019
}
클립보드 이미지 추가 (최대 크기: 500 MB)