프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ c3b48db0

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

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

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

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

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

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

    
53
        int tieInPointIndex = 1;
54

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

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

    
63
        ID2Info id2Info = ID2Info.GetInstance();
64

    
65

    
66

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

    
70
        public PSN()
71
        {
72

    
73
        }
74

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

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

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

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

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

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

    
251
        private void UpdateAirFinCooler()
252
        {
253
            try
254
            {
255
                int afcTagNum = 0;
256

    
257
                #region EquipmentAirFinCooler Info
258
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
259
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
260
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
261
                {
262
                    //pump type도 마찬가지?
263
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
264
                    {
265
                        Type = row["Type"].ToString(),
266
                        Name = row["Name"].ToString()
267
                    });
268
                }
269
                #endregion
270

    
271
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC = 'P1'");
272
                foreach (DataRow dataRow in airFinCoolerRows)
273
                {
274
                    afcTagNum++;
275
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
276
                    string EGFlowDirection = string.Empty;
277
                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => dataRow["From_Data"].ToString().Contains(x.Name)).Count() > 0)
278
                        EGFlowDirection = "O";
279
                    else if(EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => dataRow["To_Data"].ToString().Contains(x.Name)).Count() > 0)
280
                        EGFlowDirection = "I";
281

    
282
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
283
                    List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
284
                    //ViewPipeSystemNetwork_OID
285
                    string MainLineTag = "";
286
                    if (dataRow["Type"].ToString() == "E2E")
287
                    {
288
                        MainLineTag = "M";
289
                         dataRow["AFC"] = "P3";
290
                    }
291
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
292
                    {
293
                        int bCount = 0;
294
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
295
                        {
296
                            if (viewOID == dataRow["OID"].ToString())
297
                                continue;
298

    
299
                            DataRow dr = PipeSystemNetwork.Select(string.Format("OID = '{0}'", viewOID)).First();
300
                            if (dr.Field<string>("AFC") != "P1")
301
                            {
302
                                bCount++;
303
                                string[] arr = dr.Field<string>("AFC").Split('_');
304
                                if (arr.Length == 1)
305
                                    dr["AFC"] = arr[0] + "_1";
306
                                else
307
                                {
308
                                    dr["AFC"] = arr[0] + "_" + Convert.ToInt32(arr[1]) + 1;
309
                                    afcTagNum++;
310
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID));
311
                                    foreach (DataRow viewdr in viewpathItemRows)
312
                                    {
313
                                        viewdr["EqpGroupTag"] = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));  //ATG Sequence No Rule 여쭤봐야함.
314
                                        viewdr["MainLineTag"] = "M";
315
                                    }
316
                                }
317

    
318
                            }
319
                        }
320
                        
321
                        if(bCount == 1)
322
                        {
323
                            MainLineTag = "M";
324
                           // dataRow["AFC"] = "P3";
325
                        }
326
                            
327
                    }
328

    
329
                    foreach (DataRow dr in pathItemRows)
330
                    {
331
                        dr["EqpGroupTag"] = "AFC" + string.Format("-{0}", string.Format("{0:D3}", afcTagNum));  //ATG Sequence No Rule 여쭤봐야함.
332
                        dr["MainLineTag"] = MainLineTag; 
333
                        dr["EGFlowDirection"] = EGFlowDirection; 
334
                    }
335
                }
336
                
337
                foreach (DataRow dataRow in airFinCoolerRows)
338
                {
339
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = ''", dataRow["OID"].ToString()));
340
                    //ML이 공란인 PSN - P1이 있다면 해당 Pathitem에 P3인 psn이 있는지 확인 : 해당 값은 전부 돌린후 확인 가능하기 때문에 다시 조회
341
                    if (pathItemRows.Count() > 0)
342
                    {
343
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
344
                        List<string> lstpsn = new List<string>();
345
                        string EqpGroupTag = string.Empty;
346
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
347
                        {
348
                            if (dataRow["OID"].ToString() == viewOID)
349
                            {
350
                                //lstViewPipeSystemNetwork_OID.Remove(viewOID);
351
                                continue;
352
                            }
353
                            DataRow viewPSN = null;
354
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
355
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
356
                            
357
                            if (viewPSN != null)
358
                            {
359
                                EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
360
                                foreach (DataRow dr in pathItemRows)
361
                                {
362
                                    dr["EqpGroupTag"] = EqpGroupTag;
363

    
364
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains("ViewPipeSystemNetwork_OID"))
365
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
366
                                }
367
                            }
368
                            
369
                        }
370

    
371
                        while(lstpsn.Count() != 0)
372
                        {
373
                            foreach(string psn in lstpsn)
374
                            {
375
                                DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", psn));
376
                                foreach (DataRow dr in rule4pathItems)
377
                                {
378
                                    dr["EqpGroupTag"] = EqpGroupTag;
379

    
380
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains("ViewPipeSystemNetwork_OID"))
381
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
382
                                }
383

    
384
                                lstpsn.Remove(psn);
385
                            }                        
386

    
387
                        }
388
                    }
389
                    
390
                }
391

    
392
                //DataRow[]  = PipeSystemNetwork.Select("AFC = 'P1'");
393
                foreach(DataRow dr in PipeSystemNetwork.Rows)
394
                {
395
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
396
                    if(pathItemRows.Count() > 0)
397
                    {
398
                        if(dr["Type"].ToString() == "HD2")
399
                        {
400
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
401
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
402
                            {                              
403
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
404
                                {
405
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
406
                                    {
407
                                        dataRow["EGTConnectedPoint"] = "1";
408
                                    }
409
                                }
410
                            }
411
                        }
412
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
413
                        {
414
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
415
                            string lastP1 = string.Empty;
416
                            foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
417
                            {
418
                                if (viewpsn == dr["OID"].ToString())
419
                                    continue;
420

    
421
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).Length == 0)
422
                                    continue;
423

    
424
                                DataRow rows = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).First();
425
                                if(rows != null)
426
                                {
427
                                    lastP1 = viewpsn;
428
                                }
429
                            }
430

    
431
                            if(!string.IsNullOrEmpty(lastP1))
432
                            {
433
                                bool bCheck = false;
434
                                foreach (DataRow dataRow in pathItemRows)
435
                                {
436
                                    if (bCheck)
437
                                        dataRow["EqpGroupTag"] = string.Empty;
438

    
439
                                    if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
440
                                    {
441
                                        bCheck = true;
442
                                        dataRow["EGTConnectedPoint"] = 1;
443
                                    }                       
444
                                }
445
                            }
446
                        }
447
                    }
448
                }
449
            }
450
            catch (Exception ex)
451
            {
452
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
453
            }
454
            //}
455
        }
456

    
457
        private void UpdateValveGrouping()
458
        {
459
            try
460
            {
461
                #region ValveGrouping Info
462
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
463
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
464
                foreach (DataRow row in dtValveGroupung.Rows)
465
                {
466
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
467
                    {
468
                        OID = row["OID"].ToString(),
469
                        GroupType = row["GroupType"].ToString(),
470
                        TagIdentifier = row["TagIdentifier"].ToString(),
471
                        AttributeName = row["AttributeName"].ToString(),
472
                        SppidSymbolName = row["SppidSymbolName"].ToString()
473
                    });
474
                }
475
                #endregion
476

    
477

    
478
                int vgTagNum = 1;
479
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
480
                foreach (DataRow drPathitem in tagpathItemRows)
481
                {
482
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
483
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
484
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
485
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
486
                        continue;
487
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
488
                    List<Item> valveGroupingItem = new List<Item>();
489
                    int bCnt = 0;
490

    
491
                    //bool bCheck = false;
492
                    List<DataRow> lstitem = new List<DataRow>();
493
                    foreach (DataRow dr in pathItemRows)
494
                    {
495
                        //if (!string.IsNullOrEmpty(dr["GROUPTAG"].ToString()))
496
                        //    break;
497

    
498
                       if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
499
                        {
500
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
501
                            if (dr["GROUPTAG"].ToString() == "Scope Break")
502
                            {
503
                                dr["GROUPTAG"] = string.Empty;
504
                                break;
505
                            }
506

    
507
                            if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
508
                            {
509
                               // bCheck = true;
510
                                lstitem.Add(dr);
511
                                keyValuePairs.Add(bCnt, lstitem.ToList());
512
                                bCnt++;
513
                                lstitem.Clear();
514
                            }
515
                            else
516
                                lstitem.Add(dr);
517
                        }
518
                        else
519
                            lstitem.Add(dr);
520
                    }
521

    
522
                    if (lstitem.Count > 0)
523
                    {
524
                        keyValuePairs.Add(bCnt, lstitem);
525
                        //bCnt++;
526
                    }
527

    
528
                    if (keyValuePairs.Count() == 0)
529
                        continue;
530

    
531
                    string VGTag = string.Empty;
532
                    if (valveitem.AttributeName == "NoSelection")
533
                    {
534
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
535
                        vgTagNum++;
536
                    }
537
                    else
538
                    {
539
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
540
                    }
541

    
542
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
543
                    {
544
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
545
                        {
546
                            foreach (DataRow dr in keyValuePair.Value)
547
                            {
548
                                dr["GROUPTAG"] = VGTag;
549
                            }
550
                        }
551
                    }
552

    
553
                    if(valveitem.GroupType.Contains("PSV"))
554
                    {
555
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
556
                        foreach (DataRow row in psnRows)
557
                            row["Pocket"] = "Yes";
558
                    }                    
559
                }
560

    
561

    
562
            }
563
            catch (Exception ex)
564
            {
565
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
566
            }
567
            //}
568
        }
569

    
570
        private void SetTopologyData()
571
        {
572
            // 13번 excel
573
            foreach (Group group in groups)
574
            {
575
                LineNumber prevLineNumber = null;
576
                for (int i = 0; i < group.Items.Count; i++)
577
                {
578
                    Item item = group.Items[i];
579
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
580
                    if (lineNumber == null)
581
                    {
582
                        if (prevLineNumber != null)
583
                        {
584
                            if (!prevLineNumber.IsCopy)
585
                            {
586
                                prevLineNumber = prevLineNumber.Copy();
587
                                item.Document.LineNumbers.Add(prevLineNumber);
588
                                item.MissingLineNumber1 = true;
589
                            }
590
                            item.Owner = prevLineNumber.UID;
591
                        }
592
                    }
593
                    else
594
                        prevLineNumber = lineNumber;
595
                }
596

    
597
                prevLineNumber = null;
598
                for (int i = group.Items.Count - 1; i > -1; i--)
599
                {
600
                    Item item = group.Items[i];
601
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
602
                    if (lineNumber == null)
603
                    {
604
                        if (prevLineNumber != null)
605
                        {
606
                            if (!prevLineNumber.IsCopy)
607
                            {
608
                                prevLineNumber = prevLineNumber.Copy();
609
                                item.Document.LineNumbers.Add(prevLineNumber);
610
                                item.MissingLineNumber1 = true;
611
                            }
612

    
613
                            item.Owner = prevLineNumber.UID;
614
                        }
615
                    }
616
                    else
617
                        prevLineNumber = lineNumber;
618
                }
619

    
620
                if (prevLineNumber == null)
621
                {
622
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
623
                    Random random = new Random();
624
                    int index = random.Next(lineNumbers.Count - 1);
625

    
626
                    // Copy
627
                    LineNumber cLineNumber = lineNumbers[index].Copy();
628
                    group.Document.LineNumbers.Add(cLineNumber);
629

    
630
                    foreach (Item item in group.Items)
631
                    {
632
                        item.Owner = cLineNumber.UID;
633
                        item.MissingLineNumber2 = true;
634
                    }
635
                }
636
            }
637

    
638
            foreach (Document document in Documents)
639
            {
640
                foreach (Item item in document.Items)
641
                {
642
                    item.TopologyData = string.Empty;
643
                    item.PSNPipeLineID = string.Empty;
644
                    List<string> pipeLineID = new List<string>();
645
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
646
                    if (lineNumber != null)
647
                    {
648
                        item.LineNumber = lineNumber;
649

    
650
                        foreach (DataRow row in topologyRuleDT.Rows)
651
                        {
652
                            string uid = row["UID"].ToString();
653
                            //if (uid == "-")
654
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
655
                            if (uid != "-")
656
                            {
657
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
658

    
659
                                Attribute attribute = lineNumber.Attributes.Find(x => x.Name == uid);
660
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
661
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
662
                            }
663
                        }
664

    
665
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
666
                        {
667
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
668
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
669
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
670
                                                                 //else
671
                                                                 //    item.PSNPipeLineID = item.TopologyData;
672
                        }
673

    
674
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
675
                        item.TopologyData = string.Join("-", pipeLineID);
676

    
677
                    }
678
                    else
679
                    {
680
                        item.TopologyData = "Empty LineNumber";
681
                        item.LineNumber = new LineNumber();
682
                    }
683
                }
684
            }
685

    
686
            int emptyIndex = 1;
687
            foreach (Group group in groups)
688
            {
689
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
690
                if (groupItems.Count > 0)
691
                {
692
                    foreach (var item in groupItems)
693
                        item.TopologyData += string.Format("-{0}", emptyIndex);
694
                    emptyIndex++;
695
                }
696
            }
697

    
698
        }
699

    
700
        private void ConnectByOPC()
701
        {
702
            try
703
            {
704
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
705
                {
706
                    Item opcItem = group.Items.Last();
707
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
708
                    if (fromRows.Length.Equals(1))
709
                    {
710
                        DataRow opcRow = fromRows.First();
711
                        string toDrawing = opcRow["ToDrawing"].ToString();
712
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
713

    
714
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
715
                        if (toDocument != null)
716
                        {
717
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
718
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
719
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
720
                            if (toRows.Length > 1)
721
                            {
722
                                //throw new Exception("OPC error(multi connect)");
723
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
724
                                return;
725
                            }
726
                            group.EndGroup = toGroup;
727
                            toGroup.StartGroup = group;
728
                        }
729
                    }
730
                }
731
            }
732
            catch (Exception ex)
733
            {
734
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
735
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
736
            }
737
        }
738

    
739
        private void SetPSNItem()
740
        {
741
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
742
            foreach (Group group in groups)
743
                groupDic.Add(group, Guid.NewGuid().ToString());
744

    
745
            foreach (Group group in groups)
746
            {
747
                string groupKey = groupDic[group];
748
                if (group.StartGroup != null)
749
                {
750
                    string otherKey = groupDic[group.StartGroup];
751
                    ChangeGroupID(otherKey, groupKey);
752
                }
753
            }
754

    
755
            // PSN 정리
756
            foreach (var item in groupDic)
757
            {
758
                Group group = item.Key;
759
                string uid = item.Value;
760
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
761
                if (PSNItem == null)
762
                {
763
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
764
                    PSNItems.Add(PSNItem);
765
                }
766
                PSNItem.Groups.Add(group);
767
                foreach (Item groupItem in group.Items)
768
                    groupItem.PSNItem = PSNItem;
769
            }
770

    
771
            // Sort PSN
772
            foreach (PSNItem PSNItem in PSNItems)
773
            {
774
                List<Group> _groups = new List<Group>();
775

    
776
                Stack<Group> stacks = new Stack<Group>();
777
                stacks.Push(PSNItem.Groups.First());
778
                while (stacks.Count > 0)
779
                {
780
                    Group stack = stacks.Pop();
781
                    if (_groups.Contains(stack))
782
                        continue;
783

    
784
                    if (_groups.Count == 0)
785
                        _groups.Add(stack);
786
                    else
787
                    {
788
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
789
                        {
790
                            int index = _groups.IndexOf(stack.StartGroup);
791
                            _groups.Insert(index + 1, stack);
792
                        }
793
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
794
                        {
795
                            int index = _groups.IndexOf(stack.EndGroup);
796
                            _groups.Insert(index, stack);
797
                        }
798
                    }
799

    
800
                    if (stack.StartGroup != null)
801
                        stacks.Push(stack.StartGroup);
802
                    if (stack.EndGroup != null)
803
                        stacks.Push(stack.EndGroup);
804
                }
805

    
806
                PSNItem.Groups.Clear();
807
                PSNItem.Groups.AddRange(_groups);
808
            }
809

    
810
            void ChangeGroupID(string from, string to)
811
            {
812
                if (from.Equals(to))
813
                    return;
814

    
815
                List<Group> changeItems = new List<Group>();
816
                foreach (var _item in groupDic)
817
                    if (_item.Value.Equals(from))
818
                        changeItems.Add(_item.Key);
819
                foreach (var _item in changeItems)
820
                    groupDic[_item] = to;
821
            }
822
        }
823

    
824
        private void SetPSNType()
825
        {
826
            foreach (PSNItem PSNItem in PSNItems)
827
            {
828
                Group firstGroup = PSNItem.Groups.First();
829
                Group lastGroup = PSNItem.Groups.Last();
830

    
831
                Item firstItem = firstGroup.Items.First();
832
                Item lastItem = lastGroup.Items.Last();
833

    
834
                PSNItem.StartType = GetPSNType(firstItem, true);
835
                PSNItem.EndType = GetPSNType(lastItem, false);
836
            }
837

    
838
            PSNType GetPSNType(Item item, bool bFirst = true)
839
            {
840
                PSNType type = PSNType.None;
841

    
842
                if (item.ItemType == ItemType.Line)
843
                {
844
                    Group group = groups.Find(x => x.Items.Contains(item));
845
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
846
                    {
847
                        Item connItem = item.Relations[0].Item;
848
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
849
                            type = PSNType.Branch;
850
                        else if (connItem.ItemType == ItemType.Symbol)
851
                            type = PSNType.Symbol;
852
                    }
853
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
854
                    {
855
                        Item connItem = item.Relations[1].Item;
856
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
857
                            type = PSNType.Branch;
858
                        else if (connItem.ItemType == ItemType.Symbol)
859
                            type = PSNType.Symbol;
860
                    }
861
                }
862
                else if (item.ItemType == ItemType.Symbol)
863
                {
864
                    if (item.SubItemType == SubItemType.Nozzle)
865
                        type = PSNType.Equipment;
866
                    else if (item.SubItemType == SubItemType.Header)
867
                        type = PSNType.Header;
868
                    else if (item.SubItemType == SubItemType.OPC)
869
                        type = PSNType.OPC;
870
                }
871

    
872
                return type;
873
            }
874
        }
875

    
876
        private void SetBranchInfo()
877
        {
878
            foreach (Document document in Documents)
879
            {
880
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
881
                foreach (Item line in lines)
882
                {
883
                    double[] point = line.Relations[0].Point;
884
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
885
                    connLines.Sort(SortBranchLine);
886
                    line.BranchItems.AddRange(connLines);
887

    
888
                    int SortBranchLine(Item a, Item b)
889
                    {
890
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
891
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
892

    
893
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
894
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
895

    
896
                        // 내림차순
897
                        return distanceA.CompareTo(distanceB);
898
                    }
899
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
900
                    {
901
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
902
                    }
903
                }
904
            }
905
        }
906

    
907
        private void SetTopology()
908
        {
909
            try
910
            {
911
                #region 기본 topology 정리
912
                foreach (PSNItem PSNItem in PSNItems)
913
                {
914
                    Topology topology = null;
915
                    foreach (Group group in PSNItem.Groups)
916
                    {
917
                        foreach (Item item in group.Items)
918
                        {
919
                            if (string.IsNullOrEmpty(item.TopologyData))
920
                                topology = null;
921
                            else
922
                            {
923
                                if (topology == null)
924
                                {
925
                                    topology = new Topology()
926
                                    {
927
                                        ID = item.TopologyData
928
                                    };
929
                                    Topologies.Add(topology);
930

    
931
                                    if (!PSNItem.Topologies.Contains(topology))
932
                                        PSNItem.Topologies.Add(topology);
933
                                }
934
                                else
935
                                {
936
                                    if (topology.ID != item.TopologyData)
937
                                    {
938
                                        topology = new Topology()
939
                                        {
940
                                            ID = item.TopologyData
941
                                        };
942
                                        Topologies.Add(topology);
943

    
944
                                        if (!PSNItem.Topologies.Contains(topology))
945
                                            PSNItem.Topologies.Add(topology);
946
                                    }
947
                                }
948

    
949
                                item.Topology = topology;
950
                                topology.Items.Add(item);
951
                            }
952
                        }
953
                    }
954
                }
955
                #endregion
956

    
957
                #region Type
958
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
959
                foreach (string id in ids)
960
                {
961
                    try
962
                    {
963

    
964

    
965
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
966

    
967
                        // Main
968
                        List<Topology> mainTopologies = FindMainTopology(topologies);
969
                        foreach (Topology topology in mainTopologies)
970
                            topology.Type = "M";
971

    
972
                        // Branch
973
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
974
                        foreach (Topology topology in branchToplogies)
975
                            topology.Type = "B";
976
                    }
977
                    catch (Exception ex)
978
                    {
979
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
980
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
981
                    }
982
                }
983
                #endregion
984
            }
985
            catch (Exception ex)
986
            {
987
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
988
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
989
            }
990

    
991
        }
992

    
993
        private void SetTopologyIndex()
994
        {
995
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
996
            foreach (string id in ids)
997
            {
998
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
999

    
1000
                // Main
1001
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1002
                foreach (Topology topology in mainTopologies)
1003
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1004

    
1005
                // Branch
1006
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1007
                foreach (Topology topology in branchToplogies)
1008
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1009
            }
1010
        }
1011

    
1012
        private void SetPSNBypass()
1013
        {
1014
            foreach (PSNItem PSNItem in PSNItems)
1015
                PSNItem.IsBypass = IsBypass(PSNItem);
1016
        }
1017

    
1018
        private List<Topology> FindMainTopology(List<Topology> data)
1019
        {
1020
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1021
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1022
            //2021.11.17 안쓰네 JY
1023
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1024

    
1025
            List<Topology> main = new List<Topology>();
1026
            main.AddRange(data);
1027
            //
1028
            main = GetNozzleTopology(data);
1029
            if (main.Count == 1)
1030
                return main;
1031
            else
1032
            {
1033
                if (main.Count > 0)
1034
                    main = GetPMCTopology(main);
1035
                else
1036
                    main = GetPMCTopology(data);
1037

    
1038
                if (main.Count == 1)
1039
                    return main;
1040
                else
1041
                {
1042
                    if (main.Count > 0)
1043
                        main = GetDiaTopology(main);
1044
                    else
1045
                        main = GetDiaTopology(data);
1046

    
1047

    
1048
                    if (main.Count == 1)
1049
                        return main;
1050
                    else
1051
                    {
1052
                        if (main.Count > 0)
1053
                            main = GetItemTopology(main);
1054
                        else
1055
                            main = GetItemTopology(data);
1056
                    }
1057
                }
1058
            }
1059

    
1060
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1061
            {
1062
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1063
            }
1064

    
1065
            List<Topology> GetPMCTopology(List<Topology> topologies)
1066
            {
1067
                List<Topology> result = new List<Topology>();
1068
                foreach (DataRow row in PMCDT.Rows)
1069
                {
1070
                    string value = row["CODE"].ToString();
1071
                    foreach (Topology topology in topologies)
1072
                    {
1073
                        foreach (Item item in topology.Items)
1074
                        {
1075
                            if (item.LineNumber == null)
1076
                                continue;
1077
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1078
                            if (attribute != null && value == attribute.Value)
1079
                            {
1080
                                result.Add(topology);
1081
                                break;
1082
                            }
1083
                        }
1084
                    }
1085

    
1086
                    if (result.Count > 0)
1087
                        break;
1088
                }
1089

    
1090
                return result;
1091
            }
1092

    
1093
            List<Topology> GetDiaTopology(List<Topology> topologies)
1094
            {
1095
                List<Topology> result = new List<Topology>();
1096
                foreach (DataRow row in nominalDiameterDT.Rows)
1097
                {
1098
                    string inchValue = row["InchStr"].ToString();
1099
                    string metricValue = row["MetricStr"].ToString();
1100
                    foreach (Topology topology in topologies)
1101
                    {
1102
                        foreach (Item item in topology.Items)
1103
                        {
1104
                            if (item.LineNumber == null)
1105
                                continue;
1106
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1107
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1108
                            {
1109
                                result.Add(topology);
1110
                                break;
1111
                            }
1112
                        }
1113
                    }
1114

    
1115
                    if (result.Count > 0)
1116
                        break;
1117
                }
1118

    
1119
                return result;
1120
            }
1121

    
1122
            List<Topology> GetItemTopology(List<Topology> topologies)
1123
            {
1124
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1125
            }
1126

    
1127
            return main;
1128
        }
1129

    
1130
        private DataTable GetOPCInfo()
1131
        {
1132
            DataTable opc = DB.SelectOPCRelations();
1133
            DataTable drawing = DB.AllDrawings();
1134

    
1135
            DataTable dt = new DataTable();
1136
            dt.Columns.Add("FromDrawing", typeof(string));
1137
            dt.Columns.Add("FromDrawingUID", typeof(string));
1138
            dt.Columns.Add("FromOPCUID", typeof(string));
1139
            dt.Columns.Add("ToDrawing", typeof(string));
1140
            dt.Columns.Add("ToDrawingUID", typeof(string));
1141
            dt.Columns.Add("ToOPCUID", typeof(string));
1142
            foreach (DataRow row in opc.Rows)
1143
            {
1144
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1145
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1146
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1147
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1148
                if (!string.IsNullOrEmpty(toOPCUID))
1149
                {
1150
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
1151
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
1152
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
1153
                    {
1154
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
1155
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
1156

    
1157
                        DataRow newRow = dt.NewRow();
1158
                        newRow["FromDrawing"] = fromDrawingName;
1159
                        newRow["FromDrawingUID"] = fromDrawingUID;
1160
                        newRow["FromOPCUID"] = fromOPCUID;
1161
                        newRow["ToDrawing"] = toDrawingName;
1162
                        newRow["ToDrawingUID"] = toDrawingUID;
1163
                        newRow["ToOPCUID"] = toOPCUID;
1164

    
1165
                        dt.Rows.Add(newRow);
1166
                    }
1167
                }
1168
            }
1169

    
1170
            return dt;
1171
        }
1172

    
1173
        private DataTable GetTopologyRule()
1174
        {
1175
            DataTable dt = DB.SelectTopologyRule();
1176

    
1177
            return dt;
1178
        }
1179

    
1180
        private bool IsConnected(Item item1, Item item2)
1181
        {
1182
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
1183
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
1184
                return true;
1185
            else
1186
                return false;
1187
        }
1188

    
1189
        private void SaveNozzleAndEquipment()
1190
        {
1191
            List<Item> nozzles = new List<Item>();
1192
            List<Equipment> equipments = new List<Equipment>();
1193
            foreach (Document document in Documents)
1194
            {
1195
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1196
                equipments.AddRange(document.Equipments);
1197
            }
1198

    
1199

    
1200
            DataTable nozzleDT = new DataTable();
1201
            nozzleDT.Columns.Add("OID", typeof(string));
1202
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1203
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1204
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1205
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1206
            nozzleDT.Columns.Add("FLUID", typeof(string));
1207
            nozzleDT.Columns.Add("NPD", typeof(string));
1208
            nozzleDT.Columns.Add("PMC", typeof(string));
1209
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1210
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1211

    
1212
            foreach (Item item in nozzles)
1213
            {
1214
                DataRow row = nozzleDT.NewRow();
1215
                row["OID"] = item.UID;
1216

    
1217
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
1218
                if (relation != null)
1219
                {
1220
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
1221
                    equipment.Nozzles.Add(item);
1222
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
1223
                    row["Equipment_OID"] = equipment.UID;
1224
                    item.Equipment = equipment;
1225
                }
1226
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
1227
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
1228
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
1229
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
1230
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1231
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
1232
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1233
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
1234

    
1235
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1236
                if (angle >= Math.PI * 2)
1237
                    angle = angle - Math.PI * 2;
1238
                row["ROTATION"] = angle.ToString();
1239

    
1240
                if (item.Topology.Items.First().Equals(item))
1241
                    row["FlowDirection"] = "Outlet";
1242
                else if (item.Topology.Items.Last().Equals(item))
1243
                    row["FlowDirection"] = "Inlet";
1244
                else
1245
                    row["FlowDirection"] = string.Empty;
1246

    
1247
                nozzleDT.Rows.Add(row);
1248
            }
1249

    
1250
            DataTable equipDT = new DataTable();
1251
            equipDT.Columns.Add("OID", typeof(string));
1252
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1253
            equipDT.Columns.Add("XCOORDS", typeof(string));
1254
            equipDT.Columns.Add("YCOORDS", typeof(string));
1255

    
1256
            foreach (Equipment equipment in equipments)
1257
            {
1258
                DataRow row = equipDT.NewRow();
1259
                row["OID"] = equipment.UID;
1260
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
1261
                {
1262
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
1263
                    if (attribute != null)
1264
                        equipment.ItemTag = attribute.Value;
1265
                }
1266
                else
1267
                    equipment.ItemTag = equipment.Name;
1268

    
1269
                row["ITEMTAG"] = equipment.ItemTag;
1270
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
1271
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
1272

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

    
1276
                equipDT.Rows.Add(row);
1277
            }
1278

    
1279
            Equipment = equipDT;
1280
            Nozzle = nozzleDT;
1281
        }
1282

    
1283
        private void SavePSNData()
1284
        {
1285
            try
1286
            {
1287
                DataTable pathItemsDT = new DataTable();
1288
                pathItemsDT.Columns.Add("OID", typeof(string));
1289
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
1290
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
1291
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
1292
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
1293
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
1294
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
1295
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
1296
                pathItemsDT.Columns.Add("Class", typeof(string));
1297
                pathItemsDT.Columns.Add("SubClass", typeof(string));
1298
                pathItemsDT.Columns.Add("TYPE", typeof(string));
1299
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
1300
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
1301
                pathItemsDT.Columns.Add("NPD", typeof(string));
1302
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
1303
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
1304
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
1305
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
1306
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
1307
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
1308
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
1309
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
1310

    
1311
                DataTable sequenceDataDT = new DataTable();
1312
                sequenceDataDT.Columns.Add("OID", typeof(string));
1313
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
1314
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
1315
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1316

    
1317
                DataTable pipeSystemNetworkDT = new DataTable();
1318
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
1319
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
1320
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
1321
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
1322
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
1323
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
1324
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1325
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
1326
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
1327
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
1328
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
1329
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
1330
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
1331
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
1332
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
1333
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
1334

    
1335
                DataTable topologySetDT = new DataTable();
1336
                topologySetDT.Columns.Add("OID", typeof(string));
1337
                topologySetDT.Columns.Add("Type", typeof(string));
1338
                topologySetDT.Columns.Add("SubType", typeof(string));
1339
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
1340
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
1341
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
1342
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
1343

    
1344
                DataTable pipelineDT = new DataTable();
1345
                pipelineDT.Columns.Add("OID", typeof(string));
1346
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
1347
                pipelineDT.Columns.Add("FLUID", typeof(string));
1348
                pipelineDT.Columns.Add("PMC", typeof(string));
1349
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
1350
                pipelineDT.Columns.Add("INSULATION", typeof(string));
1351
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
1352
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
1353
                pipelineDT.Columns.Add("Unit", typeof(string));
1354

    
1355
                DataTable pipesystemDT = new DataTable();
1356
                pipesystemDT.Columns.Add("OID", typeof(string));
1357
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
1358
                pipesystemDT.Columns.Add("FLUID", typeof(string));
1359
                pipesystemDT.Columns.Add("PMC", typeof(string));
1360
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
1361
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
1362

    
1363
                // Set Vent/Drain Info
1364
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1365
                DataTable dt = DB.SelectVentDrainSetting();
1366
                foreach (DataRow row in dt.Rows)
1367
                {
1368
                    string groupID = row["GROUP_ID"].ToString();
1369
                    string desc = row["DESCRIPTION"].ToString();
1370
                    int index = Convert.ToInt32(row["INDEX"]);
1371
                    string name = row["NAME"].ToString();
1372

    
1373
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1374
                    if (ventDrainInfo == null)
1375
                    {
1376
                        ventDrainInfo = new VentDrainInfo(groupID);
1377
                        ventDrainInfo.Description = desc;
1378
                        VentDrainInfos.Add(ventDrainInfo);
1379
                    }
1380

    
1381
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1382
                    {
1383
                        Index = index,
1384
                        Name = name
1385
                    });
1386
                }
1387
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1388
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
1389

    
1390
                #region Keyword Info
1391
                KeywordInfo KeywordInfos = new KeywordInfo();
1392
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1393
                foreach (DataRow row in dtKeyword.Rows)
1394
                {
1395
                    int index = Convert.ToInt32(row["INDEX"]);
1396
                    string name = row["NAME"].ToString();
1397
                    string keyword = row["KEYWORD"].ToString();
1398

    
1399
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1400
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1401
                    {
1402
                        Index = index,
1403
                        Name = name,
1404
                        Keyword = keyword
1405
                    });
1406
                }
1407
                #endregion
1408

    
1409
                #region ValveGrouping Info
1410
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1411
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1412
                foreach (DataRow row in dtValveGroupung.Rows)
1413
                {
1414
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1415
                    {
1416
                        OID = row["OID"].ToString(),
1417
                        GroupType = row["GroupType"].ToString(),
1418
                        TagIdentifier = row["TagIdentifier"].ToString(),
1419
                        AttributeName = row["AttributeName"].ToString(),
1420
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1421
                    });
1422
                }
1423
                #endregion
1424

    
1425
                #region EquipmentNoPocket Info
1426
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
1427
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
1428
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
1429
                {
1430
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
1431
                    {
1432
                        Index = Convert.ToInt32(row["INDEX"]),
1433
                        Type = row["TYPE"].ToString(),
1434
                        Name = row["NAME"].ToString()
1435
                    });
1436
                }
1437
                #endregion
1438

    
1439
                #region EquipmentAirFinCooler Info
1440
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
1441
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
1442
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
1443
                {
1444
                    //pump type도 마찬가지?
1445
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
1446
                    {
1447
                        Type = row["Type"].ToString(),
1448
                        Name = row["Name"].ToString()
1449
                    });
1450
                }
1451
                #endregion
1452

    
1453
                // key = 미입력 branch
1454
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1455
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1456
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
1457
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
1458
                foreach (PSNItem PSNItem in PSNItems)
1459
                {
1460
                    try
1461
                    {
1462
                        int psnOrder = 0;
1463
                        int index = 0;
1464
                        bool bPSNStart = true;
1465
                        string sPSNData = string.Empty;
1466
                        bool bVentDrain = false;
1467

    
1468
                        List<Group> Groups = PSNItem.Groups;
1469
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
1470
                        List<Item> valveGroupingItem = new List<Item>();
1471

    
1472
                        //VentDrain 검사
1473
                        if (PSNItem.Groups.Count.Equals(1))
1474
                        {
1475
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1476
                            for (int g = 0; g < Groups.Count; g++)
1477
                            {
1478
                                Group group = Groups[g];
1479
                                for (int i = 0; i < group.Items.Count; i++)
1480
                                {
1481
                                    Item item = group.Items[i];
1482
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1483
                                    {
1484
                                        if (endInfos.Contains(ventDrainInfo))
1485
                                            continue;
1486

    
1487
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1488
                                        {
1489
                                            endInfos.Add(ventDrainInfo);
1490
                                            continue;
1491
                                        }
1492

    
1493
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1494
                                        {
1495
                                            bVentDrain = true;
1496
                                            break;
1497
                                        }
1498
                                    }
1499

    
1500
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1501
                                        break;
1502
                                }
1503

    
1504
                                if (!bVentDrain)
1505
                                {
1506
                                    endInfos = new List<VentDrainInfo>();
1507
                                    for (int i = 0; i < group.Items.Count; i++)
1508
                                    {
1509
                                        Item item = group.Items[group.Items.Count - i - 1];
1510
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1511
                                        {
1512
                                            if (endInfos.Contains(ventDrainInfo))
1513
                                                continue;
1514

    
1515
                                            if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1516
                                            {
1517
                                                endInfos.Add(ventDrainInfo);
1518
                                                continue;
1519
                                            }
1520

    
1521
                                            if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1522
                                            {
1523
                                                bVentDrain = true;
1524
                                                break;
1525
                                            }
1526
                                        }
1527

    
1528
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1529
                                            break;
1530
                                    }
1531
                                }
1532
                            }
1533
                        }
1534

    
1535
                        try
1536
                        {
1537
                            foreach (Group group in PSNItem.Groups)
1538
                            {
1539
                                foreach (Item item in group.Items)
1540
                                {
1541
                                    string VgTag = string.Empty;
1542
                                    
1543
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
1544
                                    {
1545
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
1546
                                        string value = string.Empty;
1547

    
1548
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection")
1549
                                            value = "NoSelection";
1550
                                        else
1551
                                            value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
1552

    
1553
                                        if (valveitem.GroupType == "Scope Break")
1554
                                            VgTag = "Scope Break";
1555
                                        else
1556
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
1557

    
1558
                                    }
1559

    
1560
                                    string PathitemUID = string.Empty;
1561
                                    if (item.BranchItems.Count == 0)
1562
                                    {
1563
                                        PathitemUID = item.UID;
1564
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1565
                                        CreateSequenceDataDataRow(PathitemUID);
1566
                                        index++;
1567
                                    }
1568
                                    else
1569
                                    {
1570
                                        PathitemUID = item.UID + "_L1";
1571
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1572
                                        CreateSequenceDataDataRow(PathitemUID);
1573
                                        index++;
1574
                                        for (int i = 0; i < item.BranchItems.Count; i++)
1575
                                        {
1576
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1577
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1578
                                            index++;
1579

    
1580
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1581
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1582
                                            index++;
1583

    
1584
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1585
                                                startBranchDic.Add(item.BranchItems[i], item);
1586
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1587
                                                endBranchDic.Add(item.BranchItems[i], item);
1588
                                        }
1589
                                    }
1590

    
1591
                                    if (bPSNStart)
1592
                                    {
1593
                                        CreatePipeSystemNetworkDataRow();
1594
                                        sPSNData = item.TopologyData;
1595
                                        psnOrder++;
1596
                                        bPSNStart = false;
1597
                                    }
1598
                                    else
1599
                                    {
1600
                                        if (item.TopologyData != sPSNData)
1601
                                        {
1602
                                            CreatePipeSystemNetworkDataRow();
1603
                                            sPSNData = item.TopologyData;
1604
                                            psnOrder++;
1605
                                        }
1606
                                    }
1607

    
1608
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
1609
                                    {
1610
                                        DataRow newRow = pathItemsDT.NewRow();
1611

    
1612
                                        if (itemType == "Nozzles")
1613
                                        {
1614
                                            newRow["Equipment_OID"] = item.Equipment.UID;
1615
                                        }
1616

    
1617
                                        newRow["OID"] = itemOID;
1618
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1619
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
1620
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
1621
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
1622
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
1623
                                        newRow["ITEMTAG"] = GetItemTag(item);
1624
                                        newRow["Class"] = GetClass(item, itemOID);
1625
                                        string subClass = GetSubClass(item, itemOID);
1626
                                        newRow["SubClass"] = subClass;
1627

    
1628
                                        if (item.ItemType == ItemType.Symbol)
1629
                                            newRow["TYPE"] = item.ID2DBName;
1630
                                        else if (item.ItemType == ItemType.Line)
1631
                                            newRow["TYPE"] = item.ID2DBType;
1632
                                        newRow["PIDNAME"] = group.Document.DrawingName;
1633

    
1634
                                        // NPD
1635
                                        if (item.LineNumber != null)
1636
                                        {
1637
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1638
                                            if (attribute != null)
1639
                                                newRow["NPD"] = attribute.Value;
1640
                                        }
1641
                                        else
1642
                                            newRow["NPD"] = null;
1643

    
1644
                                        newRow["GROUPTAG"] = GROUPTAG;
1645
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1646
                                        if (branchItem == null)
1647
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1648
                                        else
1649
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
1650

    
1651
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
1652
                                        newRow["EGTConnectedPoint"] = 0;
1653
                                        pathItemsDT.Rows.Add(newRow);
1654
                                    }
1655

    
1656

    
1657
                                    void CreateSequenceDataDataRow(string itemOID)
1658
                                    {
1659
                                        DataRow newRow = sequenceDataDT.NewRow();
1660
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1661
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
1662
                                        newRow["PathItem_OID"] = itemOID;
1663
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1664

    
1665
                                        sequenceDataDT.Rows.Add(newRow);
1666
                                    }
1667

    
1668
                                    void CreatePipeSystemNetworkDataRow()
1669
                                    {
1670
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1671
                                        string FluidCode = string.Empty;
1672
                                        if (lineNumber != null)
1673
                                        {
1674
                                            List<Attribute> att = lineNumber.Attributes;
1675
                                            if (att != null)
1676
                                            {
1677
                                                List<string> oid = new List<string>();
1678
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
1679
                                                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;
1680
                                                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;
1681
                                                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;
1682
                                                //InsulationPurpose
1683
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
1684
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
1685

    
1686
                                                string PipeSystem_OID = string.Join("-", oid);
1687

    
1688
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
1689
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
1690

    
1691
                                                string OID = string.Join("-", oid);
1692
                                                string FluidCodeGL = string.Empty;
1693
                                                string PMCGL = string.Empty;
1694

    
1695

    
1696
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
1697
                                                {
1698
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
1699
                                                    newPipelineRow["OID"] = OID;
1700
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
1701
                                                    newPipelineRow["FLUID"] = FluidCode;
1702
                                                    newPipelineRow["PMC"] = PMC;
1703
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
1704
                                                    newPipelineRow["INSULATION"] = INSULATION;
1705
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
1706
                                                    newPipelineRow["TO_DATA"] = string.Empty;
1707
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
1708
                                                    pipelineDT.Rows.Add(newPipelineRow);
1709
                                                }
1710

    
1711
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
1712
                                                {
1713
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
1714
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
1715
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
1716
                                                    newPipesystemRow["FLUID"] = FluidCode;
1717
                                                    newPipesystemRow["PMC"] = PMC;
1718
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
1719
                                                    string GroundLevel = string.Empty;
1720
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
1721
                                                    {
1722
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
1723
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
1724
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
1725
                                                            GroundLevel = "AG";
1726
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
1727
                                                            GroundLevel = "UG";
1728
                                                        else
1729
                                                            GroundLevel = "AG_UG";
1730
                                                    }
1731
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
1732

    
1733
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
1734
                                                }
1735
                                            }
1736
                                        }
1737

    
1738
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
1739
                                        newRow["OID"] = PSNItem.PSN_OID();
1740

    
1741
                                        newRow["OrderNumber"] = psnOrder;
1742
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
1743
                                        PSNItem.KeywordInfos = KeywordInfos;
1744
                                        PSNItem.Nozzle = Nozzle;
1745

    
1746
                                        string FromType = string.Empty;
1747
                                        Item From_item = new Item();
1748

    
1749
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
1750
                                        string status = string.Empty;
1751
                                        if (psnOrder == 0)
1752
                                        {
1753
                                            status = PSNItem.Status;
1754
                                        }
1755

    
1756
                                        if (PSNItem.IsKeyword)
1757
                                        {
1758
                                            PSNItem.StartType = PSNType.Equipment;
1759
                                        }
1760
                                        string ToType = string.Empty;
1761
                                        Item To_item = new Item();
1762
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
1763
                                        if (PSNItem.IsKeyword)
1764
                                        {
1765
                                            PSNItem.EndType = PSNType.Equipment;
1766
                                        }
1767

    
1768
                                        //if (Groups.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
1769
                                        //{
1770
                                        if (!string.IsNullOrEmpty(PSNItem.Status))
1771
                                            status += PSNItem.Status;
1772
                                        //}
1773

    
1774
                                        newRow["FROM_DATA"] = FROM_DATA;
1775
                                        newRow["TO_DATA"] = TO_DATA;
1776
                                        newRow["Type"] = PSNItem.GetPSNType();
1777

    
1778
                                        if (psnOrder > 0)
1779
                                        {
1780
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
1781
                                            if (!string.IsNullOrEmpty(PSNItem.Status))
1782
                                            {//status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
1783
                                                if (dr["Status"].ToString().Contains(PSNItem.Status))
1784
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
1785
                                                else if (dr["Status"].ToString().Contains(PSNItem.Status.Remove(0, 2)))
1786
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
1787

    
1788
                                            }
1789

    
1790
                                            if (dr != null)
1791
                                            {
1792
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
1793
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
1794
                                                newRow["Type"] = dr.Field<string>("Type");
1795
                                            }
1796
                                        }
1797

    
1798
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
1799
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
1800
                                        {
1801
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
1802
                                            int cnt = matches.Count;
1803
                                            if (cnt > 1)
1804
                                                status.Replace(", Missing LineNumber_1", string.Empty);
1805
                                        }
1806
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1807
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1808

    
1809

    
1810
                                        newRow["IsValid"] = PSNItem.IsValid;
1811
                                        newRow["Status"] = status;
1812
                                        newRow["PBS"] = PSNItem.GetPBSData();
1813

    
1814
                                        List<string> drawingNames = new List<string>();
1815
                                        foreach (Group _group in PSNItem.Groups)
1816
                                        {
1817
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
1818
                                            {
1819
                                                if (drawingNames.Count == 0)
1820
                                                    newRow["Drawings"] = _group.Document.DrawingName;
1821
                                                else
1822
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
1823
                                                drawingNames.Add(_group.Document.DrawingName);
1824
                                            }
1825
                                        }
1826

    
1827
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
1828
                                        if (bVentDrain)
1829
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
1830
                                        else
1831
                                            newRow["IncludingVirtualData"] = "No";
1832
                                        //    return;
1833
                                        //newRow["IncludingVirtualData"] = "No";
1834
                                        newRow["PSNAccuracy"] = "100";
1835

    
1836
                                        string Pocket = "No";
1837
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
1838
                                        if (Condition.Equals("Flare"))
1839
                                            Pocket = "Yes";
1840

    
1841
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment) 
1842
                                        {
1843
                                          //  string itemName = From_item.Name;
1844
                                            Equipment Equipment = From_item.Equipment;
1845
                                      
1846
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
1847
                                          
1848

    
1849
                                            if (nopocket != null)
1850
                                            {
1851
                                                DataRow bNozzle = null;
1852
                                                if (nopocket.Type.Equals("Vertical Vessel"))
1853
                                                {
1854
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
1855
                                                    if (drNozzle != null)
1856
                                                    {
1857
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
1858
                                                        {
1859
                                                            bNozzle = drNozzle;
1860
                                                        }
1861

    
1862
                                                        if (bNozzle == null)
1863
                                                        {
1864
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
1865

    
1866
                                                            if (drNozzle != null)
1867
                                                            {
1868
                                                                bNozzle = drNozzle;
1869
                                                                foreach (DataRow it in nozzleRows)
1870
                                                                {
1871
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
1872
                                                                    {
1873
                                                                        bNozzle = null;
1874
                                                                        break;
1875
                                                                    }
1876
                                                                }
1877
                                                            }
1878
                                                        }
1879
                                                    }
1880

    
1881
                                                    if (bNozzle != null)
1882
                                                        Pocket = "Yes";
1883
                                                }
1884
                                                else
1885
                                                    Pocket = "Yes";
1886
                                            }
1887
                                        }
1888
                                        
1889
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment) //To는 전체
1890
                                        {
1891
                                           // string itemName = To_item.Name;
1892
                                            Equipment Equipment = To_item.Equipment;
1893
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
1894
                                            if (nopocket != null)
1895
                                            {
1896
                                                DataRow bNozzle = null;
1897
                                                if (nopocket.Type.Equals("Vertical Vessel"))
1898
                                                {
1899
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
1900
                                                    if(drNozzle != null)
1901
                                                    {
1902
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
1903
                                                        {
1904
                                                            bNozzle = drNozzle;
1905
                                                        }
1906

    
1907
                                                        if (bNozzle == null)
1908
                                                        {
1909
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
1910

    
1911
                                                            if (drNozzle != null)
1912
                                                            {
1913
                                                                bNozzle = drNozzle;
1914
                                                                foreach (DataRow it in nozzleRows)
1915
                                                                {
1916
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
1917
                                                                    {
1918
                                                                        bNozzle = null;
1919
                                                                        break;
1920
                                                                    }
1921
                                                                }
1922
                                                            }
1923
                                                        }
1924
                                                    }                                                   
1925

    
1926
                                                    if (bNozzle != null)
1927
                                                        Pocket = "Yes";
1928
                                                }
1929
                                                else
1930
                                                    Pocket = "Yes";
1931
                                            }
1932
                                        }
1933
                                        
1934
                                        newRow["Pocket"] = Pocket;
1935
                                        string AFC = "P2";
1936
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
1937
                                        {
1938
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
1939
                                                AFC = "P1";
1940
                                        }
1941

    
1942
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
1943
                                        {
1944
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
1945
                                                AFC = "P1";
1946
                                        }
1947

    
1948
                                        newRow["AFC"] = AFC;
1949
                                        pipeSystemNetworkDT.Rows.Add(newRow);
1950
                                    }
1951
                                }
1952

    
1953
                            }
1954
                        
1955

    
1956
                        }
1957
                        catch (Exception ex)
1958
                        {
1959
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1960
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1961
                        }
1962

    
1963
                        //TopologySet 관련
1964
                        foreach (Topology topology in PSNItem.Topologies)
1965
                        {
1966
                            DataRow newRow = topologySetDT.NewRow();
1967
                            newRow["OID"] = topology.FullName;
1968
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1969
                            if (bVentDrain)
1970
                                newRow["SubType"] = "Vent_Drain";
1971
                            else
1972
                                newRow["SubType"] = null;
1973
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1974
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1975
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
1976
                            newRow["TailItemSPID"] = topology.Items.First().UID;
1977
                            topologySetDT.Rows.Add(newRow);
1978
                        }
1979

    
1980
                    }
1981
                    catch (Exception ee)
1982
                    {
1983

    
1984
                    }
1985
                }
1986

    
1987

    
1988
                foreach (var item in startBranchDic)
1989
                {
1990
                    string uid = item.Key.UID;
1991
                    string topologyName = item.Value.Topology.FullName;
1992
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1993

    
1994
                    if (rows.Length == 1)
1995
                    {
1996
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1997
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1998
                    }
1999
                    else if (rows.Length > 1)
2000
                    {
2001
                        DataRow targetRow = null;
2002
                        int index = int.MaxValue;
2003
                        foreach (DataRow row in rows)
2004
                        {
2005
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2006
                            if (split.StartsWith("L"))
2007
                            {
2008
                                int num = Convert.ToInt32(split.Remove(0, 1));
2009
                                if (index > num)
2010
                                {
2011
                                    index = num;
2012
                                    targetRow = row;
2013
                                }
2014
                            }
2015
                        }
2016

    
2017
                        if (targetRow != null)
2018
                        {
2019
                            targetRow["BranchTopologySet_OID"] = topologyName;
2020
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2021
                        }
2022
                    }
2023
                }
2024

    
2025
                foreach (var item in endBranchDic)
2026
                {
2027
                    string uid = item.Key.UID;
2028
                    string topologyName = item.Value.Topology.FullName;
2029
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2030
                    if (rows.Length == 1)
2031
                    {
2032
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2033
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2034
                    }
2035
                    else if (rows.Length > 1)
2036
                    {
2037
                        DataRow targetRow = null;
2038
                        int index = int.MinValue;
2039
                        foreach (DataRow row in rows)
2040
                        {
2041
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2042
                            if (split.StartsWith("L"))
2043
                            {
2044
                                int num = Convert.ToInt32(split.Remove(0, 1));
2045
                                if (index < num)
2046
                                {
2047
                                    index = num;
2048
                                    targetRow = row;
2049
                                }
2050
                            }
2051
                        }
2052

    
2053
                        if (targetRow != null)
2054
                        {
2055
                            targetRow["BranchTopologySet_OID"] = topologyName;
2056
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2057
                        }
2058
                    }
2059
                }
2060

    
2061
                PathItems = pathItemsDT;
2062
                SequenceData = sequenceDataDT;
2063
                PipeSystemNetwork = pipeSystemNetworkDT;
2064
                TopologySet = topologySetDT;
2065
                PipeLine = pipelineDT;
2066
                PipeSystem = pipesystemDT;
2067
            }
2068
            catch (Exception ex)
2069
            {
2070
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2071
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2072
            }
2073
        }
2074

    
2075
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2076
        {
2077
            foreach (double lacc in lstAcc)
2078
            {
2079
                acc *= lacc;
2080
            }
2081
            return acc;
2082
        }
2083

    
2084
        private void UpdateSubType()
2085
        {
2086
            try
2087
            {
2088
                foreach (PSNItem PSNItem in PSNItems)
2089
                {
2090
                    if (PSNItem.IsBypass)
2091
                    {
2092
                        foreach (Topology topology in PSNItem.Topologies)
2093
                        {
2094
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2095
                            if (rows.Length.Equals(1))
2096
                                rows.First()["SubType"] = "Bypass";
2097
                        }
2098
                    }
2099

    
2100
                    if (PSNItem.StartType == PSNType.Header)
2101
                    {
2102
                        Topology topology = PSNItem.Topologies.First();
2103
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2104
                        if (rows.Length.Equals(1))
2105
                            rows.First()["SubType"] = "Header";
2106
                    }
2107
                    else if (PSNItem.EndType == PSNType.Header)
2108
                    {
2109
                        Topology topology = PSNItem.Topologies.Last();
2110
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2111
                        if (rows.Length.Equals(1))
2112
                            rows.First()["SubType"] = "Header";
2113
                    }
2114
                }
2115

    
2116

    
2117
                foreach (Topology topology in Topologies)
2118
                {
2119
                    try
2120
                    {
2121
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2122

    
2123
                        if (rows.Count() > 0)
2124
                        {
2125
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2126
                            {
2127
                                if (topology.Items == null)
2128
                                    continue;
2129

    
2130
                                Item firstItem = topology.Items.First();
2131
                                Item lastItem = topology.Items.Last();
2132

    
2133
                                List<Relation> relations = new List<Relation>();
2134

    
2135
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2136
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2137

    
2138
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2139
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2140

    
2141
                                if (relations.Count > 0)
2142
                                    rows.First()["SubType"] = "OtherSystem";
2143
                            }
2144
                        }
2145
                    }
2146
                    catch (Exception ex)
2147
                    {
2148

    
2149
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2150
                    }
2151
                }
2152

    
2153
                foreach (DataRow row in TopologySet.Rows)
2154
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
2155
                        row["SubType"] = "Normal";
2156
            }
2157
            catch (Exception ex)
2158
            {
2159
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2160
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2161
            }
2162
        }
2163

    
2164
        private bool IsBypass(PSNItem PSNItem)
2165
        {
2166
            bool bResult = false;
2167

    
2168
            if (PSNItem.GetPSNType() == "B2B")
2169
            {
2170
                Group firstGroup = PSNItem.Groups.First();
2171
                Group lastGroup = PSNItem.Groups.Last();
2172
                Item firstItem = firstGroup.Items.First();
2173
                Item lastItem = lastGroup.Items.Last();
2174

    
2175
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
2176
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
2177

    
2178
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
2179
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
2180
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
2181
                    bResult = true;
2182
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
2183
                    bResult = true;
2184
            }
2185

    
2186
            Item GetConnectedItemByPSN(Item item)
2187
            {
2188
                Item result = null;
2189

    
2190
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
2191
                if (relation != null)
2192
                    result = relation.Item;
2193

    
2194

    
2195
                return result;
2196
            }
2197

    
2198
            return bResult;
2199
        }
2200

    
2201
        private void DeleteVentDrain()
2202
        {
2203
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
2204

    
2205
            foreach (DataRow dataRow in ventdrainRows)
2206
            {
2207
                dataRow.Delete();
2208
            }
2209
        }
2210

    
2211
        private void UpdateAccuracy()
2212
        {
2213
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
2214
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
2215
            List<double> lstAcc = null;
2216
            string Status = string.Empty;
2217

    
2218
            foreach (DataRow dataRow in statusRows)
2219
            {
2220
                lstAcc = new List<double>();
2221
                Status = dataRow.Field<string>("Status");
2222
                if (!string.IsNullOrEmpty(Status))
2223
                {
2224
                    string[] arrStatus = Status.Split(',');
2225
                    foreach (string arrstr in arrStatus)
2226
                    {
2227
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
2228
                            lstAcc.Add(0.75);
2229

    
2230
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2231
                            lstAcc.Add(0.7);
2232

    
2233
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2234
                            lstAcc.Add(0.5);
2235

    
2236
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2237
                            lstAcc.Add(0.65);
2238

    
2239
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2240
                            lstAcc.Add(0.6);
2241
                    }
2242
                }
2243

    
2244
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
2245
                if (PSNAccuracy == "100")
2246
                    PSNAccuracy = "1";
2247

    
2248
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
2249
                //if (PSNAccuracy != "100")
2250
                //{
2251
                //    //dataRow["IncludingVirtualData"] = "No";
2252
                dataRow["PSNAccuracy"] = PSNAccuracy;
2253
                //}
2254
            }
2255
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
2256
            foreach (DataRow dr in dt.Rows)
2257
            {
2258
                string oid = dr.Field<string>("OID");
2259
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
2260
                double totalDdr = 0;
2261
                foreach (DataRow ddr in select)
2262
                {
2263
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
2264
                    if (acc == 100) acc = 1;
2265
                    if (totalDdr == 0) totalDdr = acc;
2266
                    else totalDdr *= acc;
2267
                }
2268

    
2269
                totalDdr *= 100;
2270

    
2271
                if (totalDdr != 100)
2272
                {
2273
                    foreach (DataRow ddr in select)
2274
                    {
2275
                        ddr["IncludingVirtualData"] = "Yes";
2276
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2277
                    }
2278
                }
2279
                else
2280
                {
2281
                    foreach (DataRow ddr in select)
2282
                    {
2283
                        ddr["IncludingVirtualData"] = "No";
2284
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2285
                    }
2286
                }
2287
            }
2288

    
2289
        }
2290

    
2291
        private void UpdateKeywordForPSN()
2292
        {
2293
            #region Keyword Info
2294
            KeywordInfo KeywordInfos = new KeywordInfo();
2295
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2296
            foreach (DataRow row in dtKeyword.Rows)
2297
            {
2298
                int index = Convert.ToInt32(row["INDEX"]);
2299
                string name = row["NAME"].ToString();
2300
                string keyword = row["KEYWORD"].ToString();
2301

    
2302
                //KeywordInfo keywordInfo = new KeywordInfo();   
2303
                KeywordInfos.KeywordItems.Add(new KeywordItem()
2304
                {
2305
                    Index = index,
2306
                    Name = name,
2307
                    Keyword = keyword
2308
                });
2309
            }
2310
            #endregion
2311

    
2312
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
2313
            foreach (DataRow dataRow in endofHeaderRows)
2314
            {
2315
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2316

    
2317
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
2318
                {
2319
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2320
                    DataRow dr = pathItemRows.First();
2321
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
2322
                    dr["TYPE"] = "End";
2323
                    dr["ITEMTAG"] = "ENDOFHEADER";
2324
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2325
                }
2326

    
2327
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
2328
                {
2329
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2330
                    DataRow dr = pathItemRows.Last();
2331
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
2332
                    dr["TYPE"] = "End";
2333
                    dr["ITEMTAG"] = "ENDOFHEADER";
2334
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2335
                }
2336
            }
2337

    
2338
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2339
            {
2340
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
2341
                foreach (DataRow dataRow in keywordRows)
2342
                {
2343
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2344

    
2345
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
2346
                    {
2347
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2348

    
2349
                        //
2350
                        //if(.)
2351
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
2352
                        {
2353
                            DataRow dr = pathItemRows.First();
2354
                            //dr["CLASS"] = ""; //Type
2355
                            dr["TYPE"] = "End";
2356
                            dr["ITEMTAG"] = keyitem.Keyword;
2357
                            dr["DESCRIPTION"] = keyitem.Keyword;
2358
                        }
2359

    
2360
                    }
2361

    
2362
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
2363
                    {
2364
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2365

    
2366
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
2367
                        {
2368
                            DataRow dr = pathItemRows.Last();
2369
                            //dr["CLASS"] = ""; //Type
2370
                            dr["TYPE"] = "End";
2371
                            dr["ITEMTAG"] = keyitem.Keyword;
2372
                            dr["DESCRIPTION"] = keyitem.Keyword;
2373
                            //dr.Field<string>("Type")
2374
                        }
2375

    
2376
                    }
2377
                }
2378
            }
2379
        }
2380

    
2381
        private void UpdateErrorForPSN()
2382
        {
2383
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
2384
            foreach (DataRow dataRow in errorRows)
2385
            {
2386
                try
2387
                {
2388
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2389
                    bool change = false;
2390
                    bool bCheck = false;
2391
                    int bCount = 0;
2392
                    if (!PSNItem.EnableType(PSNItem.StartType))
2393
                    {
2394
                        change = true;
2395
                        bCheck = change;
2396
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2397
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2398

    
2399
                        Item item = PSNItem.Groups.First().Items.First();
2400
                        try
2401
                        {
2402
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2403

    
2404
                            tieInPointIndex++;
2405

    
2406

    
2407
                            if (item.ItemType == ItemType.Line)
2408
                            {
2409
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2410
                                bCount = 2;
2411

    
2412
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2413
                                {
2414
                                    loopRow["FROM_DATA"] = FROM_DATA;
2415
                                    if (loopRow.Field<string>("OrderNumber") == "0")
2416
                                    {
2417
                                        string status = loopRow.Field<string>("Status");
2418
                                        //string isvali
2419
                                        if (string.IsNullOrEmpty(status))
2420
                                            status = "Line Disconnected";
2421
                                        else if (!status.Contains("Line Disconnected"))
2422
                                            status += ", Line Disconnected";
2423
                                        loopRow["Status"] = status;
2424
                                        if (!string.IsNullOrEmpty(status))
2425
                                            loopRow["IsValid"] = "Error";
2426
                                    }
2427
                                }
2428
                            }
2429
                            else
2430
                            {
2431
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
2432

    
2433
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2434
                                bCount = 3;
2435
                            }
2436

    
2437
                            PSNItem.StartType = PSNType.Equipment;
2438
                        }
2439
                        catch (Exception ex)
2440
                        {
2441
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2442
                            return;
2443
                        }
2444
                    }
2445

    
2446
                    if (!PSNItem.EnableType(PSNItem.EndType))
2447
                    {
2448
                        change = true;
2449
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2450
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
2451
                        DataRow dr = pathItemRows.Last();
2452
                        if (change)
2453
                            dr = pathItemRows[pathItemRows.Count() - bCount];
2454

    
2455
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2456

    
2457
                        Item item = PSNItem.Groups.Last().Items.Last();
2458
                        try
2459
                        {
2460
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2461

    
2462
                            if (item.ItemType == ItemType.Line)
2463
                            {
2464
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2465
                                {
2466
                                    loopRow["TO_DATA"] = TO_DATA;
2467
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
2468
                                    {
2469
                                        string status = loopRow.Field<string>("Status");
2470
                                        if (string.IsNullOrEmpty(status))
2471
                                            status = "Line Disconnected";
2472
                                        else if (!status.Contains("Line Disconnected"))
2473
                                            status += ", Line Disconnected";
2474
                                        loopRow["Status"] = status;
2475
                                        if (!string.IsNullOrEmpty(status))
2476
                                            loopRow["IsValid"] = "Error";
2477
                                    }
2478
                                }
2479
                            }
2480

    
2481
                            tieInPointIndex++;
2482

    
2483
                            if (item.ItemType == ItemType.Line)
2484
                            {
2485
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
2486
                            }
2487
                            else
2488
                            {
2489
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
2490
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
2491
                            }
2492

    
2493
                            //if (!bCheck)
2494
                            //{
2495
                            //    if (item.ItemType == ItemType.Line)
2496
                            //    {
2497
                            //        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
2498
                            //    }
2499
                            //    else
2500
                            //    {
2501
                            //        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
2502
                            //        PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex + 1);
2503
                            //    }
2504
                            //}
2505
                            //else
2506
                            //{
2507
                            //    if (item.ItemType == ItemType.Line)
2508
                            //    {
2509
                            //        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
2510
                            //    }
2511
                            //    else
2512
                            //    {
2513
                            //        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
2514
                            //        PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex + 1);
2515
                            //    }
2516
                            //}
2517

    
2518

    
2519
                            PSNItem.EndType = PSNType.Equipment;
2520
                        }
2521
                        catch (Exception ex)
2522
                        {
2523
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2524
                            return;
2525
                        }
2526
                    }
2527

    
2528
                    dataRow["Type"] = PSNItem.GetPSNType();
2529
                    if (change)
2530
                    {
2531
                        int rowIndex = 0;
2532
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2533
                        {
2534
                            DataRow row = PathItems.Rows[i];
2535
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
2536
                                continue;
2537
                            string sequenceData = row["SequenceData_OID"].ToString();
2538
                            string[] split = sequenceData.Split(new char[] { '_' });
2539

    
2540
                            StringBuilder sb = new StringBuilder();
2541
                            for (int j = 0; j < split.Length - 1; j++)
2542
                                sb.Append(split[j] + "_");
2543
                            sb.Append(rowIndex++);
2544
                            row["SequenceData_OID"] = sb.ToString();
2545

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

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

    
2551
                            if (seqItemRows == null)
2552
                            {
2553
                                DataRow newRow = SequenceData.NewRow();
2554
                                newRow["OID"] = sb.ToString();
2555
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2556
                                newRow["PathItem_OID"] = row["OID"];
2557
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2558
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2559
                            }
2560
                            else
2561
                            {
2562
                                seqItemRows["OID"] = sb.ToString();
2563
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2564
                                seqItemRows["PathItem_OID"] = row["OID"];
2565
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2566
                            }
2567
                        }
2568
                    }
2569

    
2570
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
2571
                    {
2572
                        DataRow newRow = PathItems.NewRow();
2573
                        newRow["OID"] = Guid.NewGuid().ToString();
2574
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2575
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2576
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2577
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2578
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
2579
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
2580
                        newRow["DESCRIPTION"] = DATA;
2581
                        newRow["Class"] = "End of line terminator";
2582
                        newRow["SubClass"] = "End of line terminator";
2583
                        newRow["TYPE"] = "End";
2584
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2585
                        newRow["NPD"] = itemRow["NPD"];
2586
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2587
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2588
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2589
                        newRow["EGTConnectedPoint"] = "0";
2590
                        return newRow;
2591
                    }
2592

    
2593
                    DataRow createLineRow(DataRow itemRow)
2594
                    {
2595
                        DataRow newRow = PathItems.NewRow();
2596
                        newRow["OID"] = Guid.NewGuid().ToString();
2597
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2598
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2599
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2600
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2601
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
2602
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2603
                        newRow["Class"] = itemRow["Class"];
2604
                        newRow["SubClass"] = itemRow["SubClass"];
2605
                        newRow["TYPE"] = itemRow["TYPE"];
2606
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2607
                        newRow["NPD"] = itemRow["NPD"];
2608
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2609
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2610
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2611
                        newRow["EGTConnectedPoint"] = "0";
2612
                        return newRow;
2613
                    }
2614
                }
2615
                catch (Exception ex)
2616
                {
2617

    
2618
                }
2619
            }
2620
        }
2621

    
2622
        private void InsertTeePSN()
2623
        {
2624
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
2625
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
2626
            bool change = false;
2627
            foreach (DataRow dataRow in branchRows)
2628
            {
2629
                try
2630
                {
2631
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2632
                    change = false;
2633

    
2634
                    if (PSNItem.StartType == PSNType.Branch)
2635
                    {
2636
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2637
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2638
                        Item Teeitem = PSNItem.Groups.First().Items.First();
2639
                        try
2640
                        {
2641
                            if (Teeitem.ItemType == ItemType.Line)
2642
                            {
2643
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
2644
                                {
2645
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
2646
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
2647
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2648
                                    change = true;
2649
                                }
2650

    
2651
                            }
2652
                        }
2653
                        catch (Exception ex)
2654
                        {
2655
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2656
                            return;
2657
                        }
2658
                    }
2659

    
2660
                    if (PSNItem.EndType == PSNType.Branch)
2661
                    {
2662
                        //change = true;
2663
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2664

    
2665
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
2666

    
2667
                        DataRow dr = pathItemRows.Last();
2668
                        if (change)
2669
                            dr = pathItemRows[pathItemRows.Count() - 2];
2670

    
2671
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2672

    
2673
                        try
2674
                        {
2675
                            if (Teeitem.ItemType == ItemType.Line)
2676
                            {
2677
                                if (dr.Field<string>("SubClass") != "Tee")
2678
                                {
2679
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
2680
                                    change = true;
2681
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
2682
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2683
                                }
2684

    
2685
                            }
2686
                        }
2687
                        catch (Exception ex)
2688
                        {
2689
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2690
                            return;
2691
                        }
2692
                    }
2693

    
2694
                    if (change)
2695
                    {
2696
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2697
                        int rowIndex = 0;
2698
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2699
                        {
2700
                            DataRow row = PathItems.Rows[i];
2701
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
2702
                                continue;
2703
                            string sequenceData = row["SequenceData_OID"].ToString();
2704
                            string[] split = sequenceData.Split(new char[] { '_' });
2705

    
2706
                            StringBuilder sb = new StringBuilder();
2707
                            for (int j = 0; j < split.Length - 1; j++)
2708
                                sb.Append(split[j] + "_");
2709
                            sb.Append(rowIndex++);
2710
                            row["SequenceData_OID"] = sb.ToString();
2711

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

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

    
2717
                            if (seqItemRows == null)
2718
                            {
2719
                                DataRow newRow = SequenceData.NewRow();
2720
                                newRow["OID"] = sb.ToString();
2721
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2722
                                newRow["PathItem_OID"] = row["OID"];
2723
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2724
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2725
                            }
2726
                            else
2727
                            {
2728
                                seqItemRows["OID"] = sb.ToString();
2729
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2730
                                seqItemRows["PathItem_OID"] = row["OID"];
2731
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2732
                            }
2733
                        }
2734
                    }
2735

    
2736
                    DataRow createTeeRow(DataRow itemRow)
2737
                    {
2738
                        DataRow newRow = PathItems.NewRow();
2739
                        newRow["OID"] = Guid.NewGuid().ToString();
2740
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2741
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2742
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2743
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2744
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
2745
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2746
                        newRow["DESCRIPTION"] = "";
2747
                        newRow["Class"] = "Branch";
2748
                        newRow["SubClass"] = "Tee";
2749
                        newRow["TYPE"] = itemRow["TYPE"];
2750
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2751
                        newRow["NPD"] = itemRow["NPD"];
2752
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2753
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2754
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2755
                      
2756
                        newRow["EGTConnectedPoint"] = 0;
2757
                        return newRow;
2758
                    }
2759
                }
2760
                catch (Exception ex)
2761
                {
2762

    
2763
                }
2764
            }
2765
        }
2766
    }
2767

    
2768
    public class PSNItem
2769
    {
2770
        public PSNItem(int count, int Revision)
2771
        {
2772
            Groups = new List<Group>();
2773
            Topologies = new List<Topology>();
2774

    
2775
            Index = count + 1;
2776
            this.Revision = Revision;
2777
        }
2778

    
2779
        private int Revision;
2780
        public string UID { get; set; }
2781
        public List<Group> Groups { get; set; }
2782
        public List<Topology> Topologies { get; set; }
2783
        public PSNType StartType { get; set; }
2784
        public PSNType EndType { get; set; }
2785
        public int Index { get; set; }
2786
        public string IsValid { get; set; }
2787
        public bool IsKeyword { get; set; }
2788
        public string Status { get; set; }
2789
        public string IncludingVirtualData { get; set; }
2790
        public string PSNAccuracy { get; set; }
2791
        public KeywordInfo KeywordInfos = new KeywordInfo();
2792
        public DataTable Nozzle = new DataTable();
2793

    
2794
        public string PSN_OID()
2795
        {
2796
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
2797
        }
2798

    
2799
        public string GetPSNType()
2800
        {
2801
            string result = string.Empty;
2802

    
2803
            if (EnableType(StartType) && EnableType(EndType))
2804
            {
2805
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
2806
                    result = "E2E";
2807
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
2808
                    result = "B2B";
2809
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
2810
                    result = "HD2";
2811

    
2812
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
2813
                    result = "E2B";
2814
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
2815
                    result = "B2E";
2816

    
2817
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
2818
                    result = "HDB";
2819
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
2820
                    result = "HDB";
2821

    
2822
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
2823
                    result = "HDE";
2824
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
2825
                    result = "HDE";
2826
                else
2827
                    result = "Error";
2828
            }
2829
            else
2830
                result = "Error";
2831

    
2832
            return result;
2833

    
2834

    
2835
        }
2836

    
2837
        public bool EnableType(PSNType type)
2838
        {
2839
            bool result = false;
2840

    
2841
            if (type == PSNType.Branch ||
2842
                type == PSNType.Equipment ||
2843
                type == PSNType.Header)
2844
            {
2845
                result = true;
2846
            }
2847

    
2848
            return result;
2849
        }
2850

    
2851
        public bool IsBypass { get; set; }
2852

    
2853
        public string GetFromData(ref string Type, ref Item item)
2854
        {
2855
            Status = string.Empty;
2856
            string result = string.Empty;
2857
            if (IsKeyword)
2858
                IsKeyword = false;
2859
            try
2860
            {
2861
                item = Groups.First().Items.First();
2862

    
2863
                if (StartType == PSNType.Header)
2864
                    result = "ENDOFHEADER";
2865
                else if (StartType == PSNType.Branch)
2866
                {
2867
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2868
                    if (!item.MissingLineNumber2 && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2869
                        result = item.Relations.First().Item.LineNumber.Name;
2870
                    else
2871
                    {
2872
                        IsValid = "Error";
2873
                        Status += ", Missing LineNumber_2";
2874
                        result = "Empty LineNumber";
2875
                    }
2876

    
2877
                    //if (item.MissingLineNumber1)
2878
                    //{
2879
                    //    Status += ", Missing LineNumber_1";
2880
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2881

    
2882
                    //}
2883
                }
2884
                else if (StartType == PSNType.Equipment)
2885
                {
2886
                    if (Groups.First().Items.First().Equipment != null)
2887
                        result = Groups.First().Items.First().Equipment.ItemTag;
2888
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
2889

    
2890
                    if (drNozzle != null)
2891
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2892
                }
2893
                else
2894
                {
2895
                    IsValid = "Error";
2896
                    item = Groups.First().Items.First();
2897
                    if (item.ItemType == ItemType.Symbol)
2898
                    {
2899

    
2900
                        string keyword = string.Empty;
2901
                        keyword = GetFromKeywordData(ref Type, item);
2902

    
2903
                        if (string.IsNullOrEmpty(keyword))
2904
                        {
2905
                            if (item.ID2DBType.Contains("OPC's"))
2906
                                Status += ", OPC Disconnected";
2907
                            else
2908
                                Status += ", Missing ItemTag or Description";
2909

    
2910
                            result = item.ID2DBName;
2911
                        }
2912
                        else
2913
                        {
2914
                            result = keyword;
2915
                            IsKeyword = true;
2916
                            IsValid = string.Empty;
2917
                        }
2918

    
2919
                    }
2920
                    else if (item.ItemType == ItemType.Line)
2921
                    {
2922

    
2923
                        if (item.MissingLineNumber1)
2924
                        {
2925
                            IsValid = "Error";
2926
                            Status += ", Missing LineNumber_1";
2927
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2928
                        }
2929
                        else
2930
                            result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2931
                    }
2932
                    else
2933
                        result = "Unknown";
2934

    
2935
                }
2936
            }
2937
            catch (Exception ex)
2938
            {
2939

    
2940
            }
2941

    
2942
            return result;
2943
        }
2944

    
2945
        public string GetFromKeywordData(ref string Type, Item item)
2946
        {
2947
            string result = string.Empty;
2948

    
2949
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2950
            {
2951
                if (keyitem.Name.Equals(item.Name))
2952
                {
2953
                    result = keyitem.Keyword;
2954
                    Type = item.ID2DBType;
2955
                    break;
2956
                }
2957
            }
2958

    
2959
            return result;
2960
        }
2961

    
2962
        public string GetToKeywordData(ref string Type, Item item)
2963
        {
2964
            string result = string.Empty;
2965

    
2966
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2967
            {
2968
                if (keyitem.Name.Equals(item.Name))
2969
                {
2970
                    result = keyitem.Keyword;
2971
                    Type = item.ID2DBType;
2972
                    break;
2973
                }
2974
            }
2975
            return result;
2976
        }
2977

    
2978
        public string GetToData(ref string ToType, ref Item item)
2979
        {
2980
            string result = string.Empty;
2981
            Status = string.Empty;
2982

    
2983
            if (IsKeyword)
2984
                IsKeyword = false;
2985

    
2986
            item = Groups.Last().Items.Last();
2987

    
2988
            if (EndType == PSNType.Header)
2989
                result = "ENDOFHEADER";
2990
            else if (EndType == PSNType.Branch)
2991
            {
2992
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2993
                if (!item.MissingLineNumber2 && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2994
                    result = item.Relations.Last().Item.LineNumber.Name;
2995
                else
2996
                {
2997
                    IsValid = "Error";
2998
                    Status += ", Missing LineNumber_2";
2999
                    result = "Empty LineNumber";
3000
                }
3001

    
3002
                //if (item.MissingLineNumber1)
3003
                //{
3004
                //    Status += ", Missing LineNumber_1";
3005
                //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3006

    
3007
                //}
3008
            }
3009
            else if (EndType == PSNType.Equipment)
3010
            {
3011
                if (Groups.Last().Items.Last().Equipment != null)
3012
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3013

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

    
3016
                if (drNozzle != null)
3017
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3018
            }
3019
            else
3020
            {
3021
                IsValid = "Error";
3022
                item = Groups.Last().Items.Last();
3023
                if (item.ItemType == ItemType.Symbol)
3024
                {
3025
                    string keyword = string.Empty;
3026
                    keyword = GetToKeywordData(ref ToType, item);
3027

    
3028
                    if (string.IsNullOrEmpty(keyword))
3029
                    {
3030
                        if (item.ID2DBType.Contains("OPC's"))
3031
                            Status += ", OPC Disconnected";
3032
                        else
3033
                            Status += ", Missing ItemTag or Description";
3034

    
3035
                        result = item.ID2DBName;
3036
                    }
3037
                    else
3038
                    {
3039
                        result = keyword;
3040
                        IsValid = string.Empty;
3041
                        IsKeyword = true;
3042
                    }
3043

    
3044
                }
3045
                else if (item.ItemType == ItemType.Line)
3046
                {
3047
                    if (item.MissingLineNumber1)
3048
                    {
3049
                        IsValid = "Error";
3050
                        Status += ", Missing LineNumber_1";
3051
                        result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3052
                    }
3053
                    else
3054
                        result = !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3055
                }
3056
                else
3057
                    result = "Unknown";
3058

    
3059

    
3060
            }
3061

    
3062

    
3063

    
3064
            return result;
3065
        }
3066

    
3067
        public string GetPBSData()
3068
        {
3069
            string result = string.Empty;
3070
            List<string> PBSList = new List<string>();
3071
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3072
            {
3073
                string attrValue = Settings.Default.PBSSettingValue;
3074

    
3075
                foreach (Group group in Groups)
3076
                {
3077
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3078
                    foreach (LineNumber lineNumber in lineNumbers)
3079
                    {
3080
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3081
                        if (attribute != null)
3082
                        {
3083
                            string value = attribute.Value;
3084
                            if (!PBSList.Contains(value))
3085
                                PBSList.Add(value);
3086
                        }
3087
                    }
3088
                }
3089
            }
3090
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3091
            {
3092
                string attrValue = Settings.Default.PBSSettingValue;
3093

    
3094
                foreach (Group group in Groups)
3095
                {
3096
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3097
                    foreach (Item item in items)
3098
                    {
3099
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3100
                        if (!PBSList.Contains(value))
3101
                            PBSList.Add(value);
3102
                    }
3103
                }
3104
            }
3105
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3106
            {
3107
                string attrValue = Settings.Default.PBSSettingValue;
3108

    
3109
                foreach (Group group in Groups)
3110
                {
3111
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3112
                    foreach (Document document in documents)
3113
                    {
3114
                        string name = document.DrawingName;
3115

    
3116
                        int startIndex = Settings.Default.PBSSettingStartValue;
3117
                        int endIndex = Settings.Default.PBSSettingEndValue;
3118

    
3119
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3120
                        if (!PBSList.Contains(subStr))
3121
                            PBSList.Add(subStr);
3122
                    }
3123
                }
3124
            }
3125
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3126
            {
3127
                foreach (Group group in Groups)
3128
                {
3129
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3130
                    foreach (Document document in documents)
3131
                    {
3132
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
3133
                        foreach (TextInfo textInfo in textInfos)
3134
                        {
3135
                            if (!PBSList.Contains(textInfo.Value))
3136
                                PBSList.Add(textInfo.Value);
3137
                        }
3138
                    }
3139
                }
3140
            }
3141

    
3142
            foreach (var item in PBSList)
3143
            {
3144
                if (string.IsNullOrEmpty(result))
3145
                    result = item;
3146
                else
3147
                    result += ", " + item;
3148
            }
3149
            return result;
3150
        }
3151
    }
3152
}
클립보드 이미지 추가 (최대 크기: 500 MB)