프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ 0eefef3d

이력 | 보기 | 이력해설 | 다운로드 (148 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
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
277
                    List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
278
                    //ViewPipeSystemNetwork_OID
279
                    string MainLineTag = "";
280
                    if (dataRow["Type"].ToString() == "E2E")
281
                    {
282
                        MainLineTag = "M";
283
                         dataRow["AFC"] = "P3";
284
                    }
285
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
286
                    {
287
                        int bCount = 0;
288
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
289
                        {
290
                            if (viewOID == dataRow["OID"].ToString())
291
                                continue;
292

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

    
312
                            }
313
                        }
314
                        
315
                        if(bCount == 1)
316
                        {
317
                            MainLineTag = "M";
318
                           // dataRow["AFC"] = "P3";
319
                        }
320
                            
321
                    }
322

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

    
357
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains("ViewPipeSystemNetwork_OID"))
358
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
359
                                }
360
                            }
361
                            
362
                        }
363

    
364
                        while(lstpsn.Count() != 0)
365
                        {
366
                            foreach(string psn in lstpsn)
367
                            {
368
                                DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", psn));
369
                                foreach (DataRow dr in rule4pathItems)
370
                                {
371
                                    dr["EqpGroupTag"] = EqpGroupTag;
372

    
373
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains("ViewPipeSystemNetwork_OID"))
374
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
375
                                }
376

    
377
                                lstpsn.Remove(psn);
378
                            }                        
379

    
380
                        }
381
                    }
382
                    
383
                }
384

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

    
414
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).Length == 0)
415
                                    continue;
416

    
417
                                DataRow rows = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P1'", viewpsn)).First();
418
                                if(rows != null)
419
                                {
420
                                    lastP1 = viewpsn;
421
                                }
422
                            }
423

    
424
                            if(!string.IsNullOrEmpty(lastP1))
425
                            {
426
                                bool bCheck = false;
427
                                foreach (DataRow dataRow in pathItemRows)
428
                                {
429
                                    if (bCheck)
430
                                        dataRow["EqpGroupTag"] = string.Empty;
431

    
432
                                    if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
433
                                    {
434
                                        bCheck = true;
435
                                        dataRow["EGTConnectedPoint"] = 1;
436
                                    }                       
437
                                }
438
                            }
439
                        }
440
                    }
441
                }
442
            }
443
            catch (Exception ex)
444
            {
445
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
446
            }
447
            //}
448
        }
449

    
450
        private void UpdateValveGrouping()
451
        {
452
            try
453
            {
454
                #region ValveGrouping Info
455
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
456
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
457
                foreach (DataRow row in dtValveGroupung.Rows)
458
                {
459
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
460
                    {
461
                        OID = row["OID"].ToString(),
462
                        GroupType = row["GroupType"].ToString(),
463
                        TagIdentifier = row["TagIdentifier"].ToString(),
464
                        AttributeName = row["AttributeName"].ToString(),
465
                        SppidSymbolName = row["SppidSymbolName"].ToString()
466
                    });
467
                }
468
                #endregion
469

    
470

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

    
484
                    //bool bCheck = false;
485
                    List<DataRow> lstitem = new List<DataRow>();
486
                    foreach (DataRow dr in pathItemRows)
487
                    {
488
                        //if (!string.IsNullOrEmpty(dr["GROUPTAG"].ToString()))
489
                        //    break;
490

    
491
                       if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
492
                        {
493
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
494
                            if (dr["GROUPTAG"].ToString() == "Scope Break")
495
                            {
496
                                dr["GROUPTAG"] = string.Empty;
497
                                break;
498
                            }
499

    
500
                            if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
501
                            {
502
                               // bCheck = true;
503
                                lstitem.Add(dr);
504
                                keyValuePairs.Add(bCnt, lstitem.ToList());
505
                                bCnt++;
506
                                lstitem.Clear();
507
                            }
508
                            else
509
                                lstitem.Add(dr);
510
                        }
511
                        else
512
                            lstitem.Add(dr);
513
                    }
514

    
515
                    if (lstitem.Count > 0)
516
                    {
517
                        keyValuePairs.Add(bCnt, lstitem);
518
                        //bCnt++;
519
                    }
520

    
521
                    if (keyValuePairs.Count() == 0)
522
                        continue;
523

    
524
                    string VGTag = string.Empty;
525
                    if (valveitem.AttributeName == "NoSelection")
526
                    {
527
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
528
                        vgTagNum++;
529
                    }
530
                    else
531
                    {
532
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
533
                    }
534

    
535
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
536
                    {
537
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
538
                        {
539
                            foreach (DataRow dr in keyValuePair.Value)
540
                            {
541
                                dr["GROUPTAG"] = VGTag;
542
                            }
543
                        }
544
                    }
545

    
546
                    if(valveitem.GroupType.Contains("PSV"))
547
                    {
548
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
549
                        foreach (DataRow row in psnRows)
550
                            row["Pocket"] = "Yes";
551
                    }                    
552
                }
553

    
554

    
555
            }
556
            catch (Exception ex)
557
            {
558
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
559
            }
560
            //}
561
        }
562

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

    
590
                prevLineNumber = null;
591
                for (int i = group.Items.Count - 1; i > -1; i--)
592
                {
593
                    Item item = group.Items[i];
594
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
595
                    if (lineNumber == null)
596
                    {
597
                        if (prevLineNumber != null)
598
                        {
599
                            if (!prevLineNumber.IsCopy)
600
                            {
601
                                prevLineNumber = prevLineNumber.Copy();
602
                                item.Document.LineNumbers.Add(prevLineNumber);
603
                                item.MissingLineNumber1 = true;
604
                            }
605

    
606
                            item.Owner = prevLineNumber.UID;
607
                        }
608
                    }
609
                    else
610
                        prevLineNumber = lineNumber;
611
                }
612

    
613
                if (prevLineNumber == null)
614
                {
615
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
616
                    Random random = new Random();
617
                    int index = random.Next(lineNumbers.Count - 1);
618

    
619
                    // Copy
620
                    LineNumber cLineNumber = lineNumbers[index].Copy();
621
                    group.Document.LineNumbers.Add(cLineNumber);
622

    
623
                    foreach (Item item in group.Items)
624
                    {
625
                        item.Owner = cLineNumber.UID;
626
                        item.MissingLineNumber2 = true;
627
                    }
628
                }
629
            }
630

    
631
            foreach (Document document in Documents)
632
            {
633
                foreach (Item item in document.Items)
634
                {
635
                    item.TopologyData = string.Empty;
636
                    item.PSNPipeLineID = string.Empty;
637
                    List<string> pipeLineID = new List<string>();
638
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
639
                    if (lineNumber != null)
640
                    {
641
                        item.LineNumber = lineNumber;
642

    
643
                        foreach (DataRow row in topologyRuleDT.Rows)
644
                        {
645
                            string uid = row["UID"].ToString();
646
                            //if (uid == "-")
647
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
648
                            if (uid != "-")
649
                            {
650
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
651

    
652
                                Attribute attribute = lineNumber.Attributes.Find(x => x.Name == uid);
653
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
654
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
655
                            }
656
                        }
657

    
658
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
659
                        {
660
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
661
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
662
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
663
                                                                 //else
664
                                                                 //    item.PSNPipeLineID = item.TopologyData;
665
                        }
666

    
667
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
668
                        item.TopologyData = string.Join("-", pipeLineID);
669

    
670
                    }
671
                    else
672
                    {
673
                        item.TopologyData = "Empty LineNumber";
674
                        item.LineNumber = new LineNumber();
675
                    }
676
                }
677
            }
678

    
679
            int emptyIndex = 1;
680
            foreach (Group group in groups)
681
            {
682
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
683
                if (groupItems.Count > 0)
684
                {
685
                    foreach (var item in groupItems)
686
                        item.TopologyData += string.Format("-{0}", emptyIndex);
687
                    emptyIndex++;
688
                }
689
            }
690

    
691
        }
692

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

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

    
732
        private void SetPSNItem()
733
        {
734
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
735
            foreach (Group group in groups)
736
                groupDic.Add(group, Guid.NewGuid().ToString());
737

    
738
            foreach (Group group in groups)
739
            {
740
                string groupKey = groupDic[group];
741
                if (group.StartGroup != null)
742
                {
743
                    string otherKey = groupDic[group.StartGroup];
744
                    ChangeGroupID(otherKey, groupKey);
745
                }
746
            }
747

    
748
            // PSN 정리
749
            foreach (var item in groupDic)
750
            {
751
                Group group = item.Key;
752
                string uid = item.Value;
753
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
754
                if (PSNItem == null)
755
                {
756
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
757
                    PSNItems.Add(PSNItem);
758
                }
759
                PSNItem.Groups.Add(group);
760
                foreach (Item groupItem in group.Items)
761
                    groupItem.PSNItem = PSNItem;
762
            }
763

    
764
            // Sort PSN
765
            foreach (PSNItem PSNItem in PSNItems)
766
            {
767
                List<Group> _groups = new List<Group>();
768

    
769
                Stack<Group> stacks = new Stack<Group>();
770
                stacks.Push(PSNItem.Groups.First());
771
                while (stacks.Count > 0)
772
                {
773
                    Group stack = stacks.Pop();
774
                    if (_groups.Contains(stack))
775
                        continue;
776

    
777
                    if (_groups.Count == 0)
778
                        _groups.Add(stack);
779
                    else
780
                    {
781
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
782
                        {
783
                            int index = _groups.IndexOf(stack.StartGroup);
784
                            _groups.Insert(index + 1, stack);
785
                        }
786
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
787
                        {
788
                            int index = _groups.IndexOf(stack.EndGroup);
789
                            _groups.Insert(index, stack);
790
                        }
791
                    }
792

    
793
                    if (stack.StartGroup != null)
794
                        stacks.Push(stack.StartGroup);
795
                    if (stack.EndGroup != null)
796
                        stacks.Push(stack.EndGroup);
797
                }
798

    
799
                PSNItem.Groups.Clear();
800
                PSNItem.Groups.AddRange(_groups);
801
            }
802

    
803
            void ChangeGroupID(string from, string to)
804
            {
805
                if (from.Equals(to))
806
                    return;
807

    
808
                List<Group> changeItems = new List<Group>();
809
                foreach (var _item in groupDic)
810
                    if (_item.Value.Equals(from))
811
                        changeItems.Add(_item.Key);
812
                foreach (var _item in changeItems)
813
                    groupDic[_item] = to;
814
            }
815
        }
816

    
817
        private void SetPSNType()
818
        {
819
            foreach (PSNItem PSNItem in PSNItems)
820
            {
821
                Group firstGroup = PSNItem.Groups.First();
822
                Group lastGroup = PSNItem.Groups.Last();
823

    
824
                Item firstItem = firstGroup.Items.First();
825
                Item lastItem = lastGroup.Items.Last();
826

    
827
                PSNItem.StartType = GetPSNType(firstItem, true);
828
                PSNItem.EndType = GetPSNType(lastItem, false);
829
            }
830

    
831
            PSNType GetPSNType(Item item, bool bFirst = true)
832
            {
833
                PSNType type = PSNType.None;
834

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

    
865
                return type;
866
            }
867
        }
868

    
869
        private void SetBranchInfo()
870
        {
871
            foreach (Document document in Documents)
872
            {
873
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
874
                foreach (Item line in lines)
875
                {
876
                    double[] point = line.Relations[0].Point;
877
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
878
                    connLines.Sort(SortBranchLine);
879
                    line.BranchItems.AddRange(connLines);
880

    
881
                    int SortBranchLine(Item a, Item b)
882
                    {
883
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
884
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
885

    
886
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
887
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
888

    
889
                        // 내림차순
890
                        return distanceA.CompareTo(distanceB);
891
                    }
892
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
893
                    {
894
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
895
                    }
896
                }
897
            }
898
        }
899

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

    
924
                                    if (!PSNItem.Topologies.Contains(topology))
925
                                        PSNItem.Topologies.Add(topology);
926
                                }
927
                                else
928
                                {
929
                                    if (topology.ID != item.TopologyData)
930
                                    {
931
                                        topology = new Topology()
932
                                        {
933
                                            ID = item.TopologyData
934
                                        };
935
                                        Topologies.Add(topology);
936

    
937
                                        if (!PSNItem.Topologies.Contains(topology))
938
                                            PSNItem.Topologies.Add(topology);
939
                                    }
940
                                }
941

    
942
                                item.Topology = topology;
943
                                topology.Items.Add(item);
944
                            }
945
                        }
946
                    }
947
                }
948
                #endregion
949

    
950
                #region Type
951
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
952
                foreach (string id in ids)
953
                {
954
                    try
955
                    {
956

    
957

    
958
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
959

    
960
                        // Main
961
                        List<Topology> mainTopologies = FindMainTopology(topologies);
962
                        foreach (Topology topology in mainTopologies)
963
                            topology.Type = "M";
964

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

    
984
        }
985

    
986
        private void SetTopologyIndex()
987
        {
988
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
989
            foreach (string id in ids)
990
            {
991
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
992

    
993
                // Main
994
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
995
                foreach (Topology topology in mainTopologies)
996
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
997

    
998
                // Branch
999
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1000
                foreach (Topology topology in branchToplogies)
1001
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1002
            }
1003
        }
1004

    
1005
        private void SetPSNBypass()
1006
        {
1007
            foreach (PSNItem PSNItem in PSNItems)
1008
                PSNItem.IsBypass = IsBypass(PSNItem);
1009
        }
1010

    
1011
        private List<Topology> FindMainTopology(List<Topology> data)
1012
        {
1013
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1014
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1015
            //2021.11.17 안쓰네 JY
1016
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1017

    
1018
            List<Topology> main = new List<Topology>();
1019
            main.AddRange(data);
1020
            //
1021
            main = GetNozzleTopology(data);
1022
            if (main.Count == 1)
1023
                return main;
1024
            else
1025
            {
1026
                if (main.Count > 0)
1027
                    main = GetPMCTopology(main);
1028
                else
1029
                    main = GetPMCTopology(data);
1030

    
1031
                if (main.Count == 1)
1032
                    return main;
1033
                else
1034
                {
1035
                    if (main.Count > 0)
1036
                        main = GetDiaTopology(main);
1037
                    else
1038
                        main = GetDiaTopology(data);
1039

    
1040

    
1041
                    if (main.Count == 1)
1042
                        return main;
1043
                    else
1044
                    {
1045
                        if (main.Count > 0)
1046
                            main = GetItemTopology(main);
1047
                        else
1048
                            main = GetItemTopology(data);
1049
                    }
1050
                }
1051
            }
1052

    
1053
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1054
            {
1055
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1056
            }
1057

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

    
1079
                    if (result.Count > 0)
1080
                        break;
1081
                }
1082

    
1083
                return result;
1084
            }
1085

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

    
1108
                    if (result.Count > 0)
1109
                        break;
1110
                }
1111

    
1112
                return result;
1113
            }
1114

    
1115
            List<Topology> GetItemTopology(List<Topology> topologies)
1116
            {
1117
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1118
            }
1119

    
1120
            return main;
1121
        }
1122

    
1123
        private DataTable GetOPCInfo()
1124
        {
1125
            DataTable opc = DB.SelectOPCRelations();
1126
            DataTable drawing = DB.AllDrawings();
1127

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

    
1150
                        DataRow newRow = dt.NewRow();
1151
                        newRow["FromDrawing"] = fromDrawingName;
1152
                        newRow["FromDrawingUID"] = fromDrawingUID;
1153
                        newRow["FromOPCUID"] = fromOPCUID;
1154
                        newRow["ToDrawing"] = toDrawingName;
1155
                        newRow["ToDrawingUID"] = toDrawingUID;
1156
                        newRow["ToOPCUID"] = toOPCUID;
1157

    
1158
                        dt.Rows.Add(newRow);
1159
                    }
1160
                }
1161
            }
1162

    
1163
            return dt;
1164
        }
1165

    
1166
        private DataTable GetTopologyRule()
1167
        {
1168
            DataTable dt = DB.SelectTopologyRule();
1169

    
1170
            return dt;
1171
        }
1172

    
1173
        private bool IsConnected(Item item1, Item item2)
1174
        {
1175
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
1176
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
1177
                return true;
1178
            else
1179
                return false;
1180
        }
1181

    
1182
        private void SaveNozzleAndEquipment()
1183
        {
1184
            List<Item> nozzles = new List<Item>();
1185
            List<Equipment> equipments = new List<Equipment>();
1186
            foreach (Document document in Documents)
1187
            {
1188
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1189
                equipments.AddRange(document.Equipments);
1190
            }
1191

    
1192

    
1193
            DataTable nozzleDT = new DataTable();
1194
            nozzleDT.Columns.Add("OID", typeof(string));
1195
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1196
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1197
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1198
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1199
            nozzleDT.Columns.Add("FLUID", typeof(string));
1200
            nozzleDT.Columns.Add("NPD", typeof(string));
1201
            nozzleDT.Columns.Add("PMC", typeof(string));
1202
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1203
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1204

    
1205
            foreach (Item item in nozzles)
1206
            {
1207
                DataRow row = nozzleDT.NewRow();
1208
                row["OID"] = item.UID;
1209

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

    
1228
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1229
                if (angle >= Math.PI * 2)
1230
                    angle = angle - Math.PI * 2;
1231
                row["ROTATION"] = angle.ToString();
1232

    
1233
                if (item.Topology.Items.First().Equals(item))
1234
                    row["FlowDirection"] = "Outlet";
1235
                else if (item.Topology.Items.Last().Equals(item))
1236
                    row["FlowDirection"] = "Inlet";
1237
                else
1238
                    row["FlowDirection"] = string.Empty;
1239

    
1240
                nozzleDT.Rows.Add(row);
1241
            }
1242

    
1243
            DataTable equipDT = new DataTable();
1244
            equipDT.Columns.Add("OID", typeof(string));
1245
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1246
            equipDT.Columns.Add("XCOORDS", typeof(string));
1247
            equipDT.Columns.Add("YCOORDS", typeof(string));
1248

    
1249
            foreach (Equipment equipment in equipments)
1250
            {
1251
                DataRow row = equipDT.NewRow();
1252
                row["OID"] = equipment.UID;
1253
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
1254
                {
1255
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
1256
                    if (attribute != null)
1257
                        equipment.ItemTag = attribute.Value;
1258
                }
1259
                else
1260
                    equipment.ItemTag = equipment.Name;
1261

    
1262
                row["ITEMTAG"] = equipment.ItemTag;
1263
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
1264
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
1265

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

    
1269
                equipDT.Rows.Add(row);
1270
            }
1271

    
1272
            Equipment = equipDT;
1273
            Nozzle = nozzleDT;
1274
        }
1275

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

    
1304
                DataTable sequenceDataDT = new DataTable();
1305
                sequenceDataDT.Columns.Add("OID", typeof(string));
1306
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
1307
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
1308
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1309

    
1310
                DataTable pipeSystemNetworkDT = new DataTable();
1311
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
1312
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
1313
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
1314
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
1315
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
1316
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
1317
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1318
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
1319
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
1320
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
1321
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
1322
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
1323
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
1324
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
1325
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
1326
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
1327

    
1328
                DataTable topologySetDT = new DataTable();
1329
                topologySetDT.Columns.Add("OID", typeof(string));
1330
                topologySetDT.Columns.Add("Type", typeof(string));
1331
                topologySetDT.Columns.Add("SubType", typeof(string));
1332
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
1333
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
1334
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
1335
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
1336

    
1337
                DataTable pipelineDT = new DataTable();
1338
                pipelineDT.Columns.Add("OID", typeof(string));
1339
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
1340
                pipelineDT.Columns.Add("FLUID", typeof(string));
1341
                pipelineDT.Columns.Add("PMC", typeof(string));
1342
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
1343
                pipelineDT.Columns.Add("INSULATION", typeof(string));
1344
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
1345
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
1346
                pipelineDT.Columns.Add("Unit", typeof(string));
1347

    
1348
                DataTable pipesystemDT = new DataTable();
1349
                pipesystemDT.Columns.Add("OID", typeof(string));
1350
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
1351
                pipesystemDT.Columns.Add("FLUID", typeof(string));
1352
                pipesystemDT.Columns.Add("PMC", typeof(string));
1353
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
1354
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
1355

    
1356
                // Set Vent/Drain Info
1357
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1358
                DataTable dt = DB.SelectVentDrainSetting();
1359
                foreach (DataRow row in dt.Rows)
1360
                {
1361
                    string groupID = row["GROUP_ID"].ToString();
1362
                    string desc = row["DESCRIPTION"].ToString();
1363
                    int index = Convert.ToInt32(row["INDEX"]);
1364
                    string name = row["NAME"].ToString();
1365

    
1366
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1367
                    if (ventDrainInfo == null)
1368
                    {
1369
                        ventDrainInfo = new VentDrainInfo(groupID);
1370
                        ventDrainInfo.Description = desc;
1371
                        VentDrainInfos.Add(ventDrainInfo);
1372
                    }
1373

    
1374
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1375
                    {
1376
                        Index = index,
1377
                        Name = name
1378
                    });
1379
                }
1380
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1381
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
1382

    
1383
                #region Keyword Info
1384
                KeywordInfo KeywordInfos = new KeywordInfo();
1385
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1386
                foreach (DataRow row in dtKeyword.Rows)
1387
                {
1388
                    int index = Convert.ToInt32(row["INDEX"]);
1389
                    string name = row["NAME"].ToString();
1390
                    string keyword = row["KEYWORD"].ToString();
1391

    
1392
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1393
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1394
                    {
1395
                        Index = index,
1396
                        Name = name,
1397
                        Keyword = keyword
1398
                    });
1399
                }
1400
                #endregion
1401

    
1402
                #region ValveGrouping Info
1403
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1404
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1405
                foreach (DataRow row in dtValveGroupung.Rows)
1406
                {
1407
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1408
                    {
1409
                        OID = row["OID"].ToString(),
1410
                        GroupType = row["GroupType"].ToString(),
1411
                        TagIdentifier = row["TagIdentifier"].ToString(),
1412
                        AttributeName = row["AttributeName"].ToString(),
1413
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1414
                    });
1415
                }
1416
                #endregion
1417

    
1418
                #region EquipmentNoPocket Info
1419
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
1420
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
1421
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
1422
                {
1423
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
1424
                    {
1425
                        Index = Convert.ToInt32(row["INDEX"]),
1426
                        Type = row["TYPE"].ToString(),
1427
                        Name = row["NAME"].ToString()
1428
                    });
1429
                }
1430
                #endregion
1431

    
1432
                #region EquipmentAirFinCooler Info
1433
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
1434
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
1435
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
1436
                {
1437
                    //pump type도 마찬가지?
1438
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
1439
                    {
1440
                        Type = row["Type"].ToString(),
1441
                        Name = row["Name"].ToString()
1442
                    });
1443
                }
1444
                #endregion
1445

    
1446
                // key = 미입력 branch
1447
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1448
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1449
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
1450
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
1451
                foreach (PSNItem PSNItem in PSNItems)
1452
                {
1453
                    try
1454
                    {
1455
                        int psnOrder = 0;
1456
                        int index = 0;
1457
                        bool bPSNStart = true;
1458
                        string sPSNData = string.Empty;
1459
                        bool bVentDrain = false;
1460

    
1461
                        List<Group> Groups = PSNItem.Groups;
1462
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
1463
                        List<Item> valveGroupingItem = new List<Item>();
1464

    
1465
                        //VentDrain 검사
1466
                        if (PSNItem.Groups.Count.Equals(1))
1467
                        {
1468
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1469
                            for (int g = 0; g < Groups.Count; g++)
1470
                            {
1471
                                Group group = Groups[g];
1472
                                for (int i = 0; i < group.Items.Count; i++)
1473
                                {
1474
                                    Item item = group.Items[i];
1475
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1476
                                    {
1477
                                        if (endInfos.Contains(ventDrainInfo))
1478
                                            continue;
1479

    
1480
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1481
                                        {
1482
                                            endInfos.Add(ventDrainInfo);
1483
                                            continue;
1484
                                        }
1485

    
1486
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1487
                                        {
1488
                                            bVentDrain = true;
1489
                                            break;
1490
                                        }
1491
                                    }
1492

    
1493
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1494
                                        break;
1495
                                }
1496

    
1497
                                if (!bVentDrain)
1498
                                {
1499
                                    endInfos = new List<VentDrainInfo>();
1500
                                    for (int i = 0; i < group.Items.Count; i++)
1501
                                    {
1502
                                        Item item = group.Items[group.Items.Count - i - 1];
1503
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1504
                                        {
1505
                                            if (endInfos.Contains(ventDrainInfo))
1506
                                                continue;
1507

    
1508
                                            if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1509
                                            {
1510
                                                endInfos.Add(ventDrainInfo);
1511
                                                continue;
1512
                                            }
1513

    
1514
                                            if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1515
                                            {
1516
                                                bVentDrain = true;
1517
                                                break;
1518
                                            }
1519
                                        }
1520

    
1521
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1522
                                            break;
1523
                                    }
1524
                                }
1525
                            }
1526
                        }
1527

    
1528
                        try
1529
                        {
1530
                            foreach (Group group in PSNItem.Groups)
1531
                            {
1532
                                foreach (Item item in group.Items)
1533
                                {
1534
                                    string VgTag = string.Empty;
1535
                                    
1536
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
1537
                                    {
1538
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
1539
                                        string value = string.Empty;
1540

    
1541
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection")
1542
                                            value = "NoSelection";
1543
                                        else
1544
                                            value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
1545

    
1546
                                        if (valveitem.GroupType == "Scope Break")
1547
                                            VgTag = "Scope Break";
1548
                                        else
1549
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
1550

    
1551
                                    }
1552

    
1553
                                    string PathitemUID = string.Empty;
1554
                                    if (item.BranchItems.Count == 0)
1555
                                    {
1556
                                        PathitemUID = item.UID;
1557
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1558
                                        CreateSequenceDataDataRow(PathitemUID);
1559
                                        index++;
1560
                                    }
1561
                                    else
1562
                                    {
1563
                                        PathitemUID = item.UID + "_L1";
1564
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1565
                                        CreateSequenceDataDataRow(PathitemUID);
1566
                                        index++;
1567
                                        for (int i = 0; i < item.BranchItems.Count; i++)
1568
                                        {
1569
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1570
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1571
                                            index++;
1572

    
1573
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1574
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1575
                                            index++;
1576

    
1577
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1578
                                                startBranchDic.Add(item.BranchItems[i], item);
1579
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1580
                                                endBranchDic.Add(item.BranchItems[i], item);
1581
                                        }
1582
                                    }
1583

    
1584
                                    if (bPSNStart)
1585
                                    {
1586
                                        CreatePipeSystemNetworkDataRow();
1587
                                        sPSNData = item.TopologyData;
1588
                                        psnOrder++;
1589
                                        bPSNStart = false;
1590
                                    }
1591
                                    else
1592
                                    {
1593
                                        if (item.TopologyData != sPSNData)
1594
                                        {
1595
                                            CreatePipeSystemNetworkDataRow();
1596
                                            sPSNData = item.TopologyData;
1597
                                            psnOrder++;
1598
                                        }
1599
                                    }
1600

    
1601
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
1602
                                    {
1603
                                        DataRow newRow = pathItemsDT.NewRow();
1604

    
1605
                                        if (itemType == "Nozzles")
1606
                                        {
1607
                                            newRow["Equipment_OID"] = item.Equipment.UID;
1608
                                        }
1609

    
1610
                                        newRow["OID"] = itemOID;
1611
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1612
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
1613
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
1614
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
1615
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
1616
                                        newRow["ITEMTAG"] = GetItemTag(item);
1617
                                        newRow["Class"] = GetClass(item, itemOID);
1618
                                        string subClass = GetSubClass(item, itemOID);
1619
                                        newRow["SubClass"] = subClass;
1620

    
1621
                                        if (item.ItemType == ItemType.Symbol)
1622
                                            newRow["TYPE"] = item.ID2DBName;
1623
                                        else if (item.ItemType == ItemType.Line)
1624
                                            newRow["TYPE"] = item.ID2DBType;
1625
                                        newRow["PIDNAME"] = group.Document.DrawingName;
1626

    
1627
                                        // NPD
1628
                                        if (item.LineNumber != null)
1629
                                        {
1630
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1631
                                            if (attribute != null)
1632
                                                newRow["NPD"] = attribute.Value;
1633
                                        }
1634
                                        else
1635
                                            newRow["NPD"] = null;
1636

    
1637
                                        newRow["GROUPTAG"] = GROUPTAG;
1638
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1639
                                        if (branchItem == null)
1640
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1641
                                        else
1642
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
1643

    
1644
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
1645
                                        newRow["EGTConnectedPoint"] = 0;
1646
                                        pathItemsDT.Rows.Add(newRow);
1647
                                    }
1648

    
1649

    
1650
                                    void CreateSequenceDataDataRow(string itemOID)
1651
                                    {
1652
                                        DataRow newRow = sequenceDataDT.NewRow();
1653
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1654
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
1655
                                        newRow["PathItem_OID"] = itemOID;
1656
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1657

    
1658
                                        sequenceDataDT.Rows.Add(newRow);
1659
                                    }
1660

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

    
1679
                                                string PipeSystem_OID = string.Join("-", oid);
1680

    
1681
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
1682
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
1683

    
1684
                                                string OID = string.Join("-", oid);
1685
                                                string FluidCodeGL = string.Empty;
1686
                                                string PMCGL = string.Empty;
1687

    
1688

    
1689
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
1690
                                                {
1691
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
1692
                                                    newPipelineRow["OID"] = OID;
1693
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
1694
                                                    newPipelineRow["FLUID"] = FluidCode;
1695
                                                    newPipelineRow["PMC"] = PMC;
1696
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
1697
                                                    newPipelineRow["INSULATION"] = INSULATION;
1698
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
1699
                                                    newPipelineRow["TO_DATA"] = string.Empty;
1700
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
1701
                                                    pipelineDT.Rows.Add(newPipelineRow);
1702
                                                }
1703

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

    
1726
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
1727
                                                }
1728
                                            }
1729
                                        }
1730

    
1731
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
1732
                                        newRow["OID"] = PSNItem.PSN_OID();
1733

    
1734
                                        newRow["OrderNumber"] = psnOrder;
1735
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
1736
                                        PSNItem.KeywordInfos = KeywordInfos;
1737
                                        PSNItem.Nozzle = Nozzle;
1738

    
1739
                                        string FromType = string.Empty;
1740
                                        Item From_item = new Item();
1741

    
1742
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
1743
                                        string status = string.Empty;
1744
                                        if (psnOrder == 0)
1745
                                        {
1746
                                            status = PSNItem.Status;
1747
                                        }
1748

    
1749
                                        if (PSNItem.IsKeyword)
1750
                                        {
1751
                                            PSNItem.StartType = PSNType.Equipment;
1752
                                        }
1753
                                        string ToType = string.Empty;
1754
                                        Item To_item = new Item();
1755
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
1756
                                        if (PSNItem.IsKeyword)
1757
                                        {
1758
                                            PSNItem.EndType = PSNType.Equipment;
1759
                                        }
1760

    
1761
                                        //if (Groups.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
1762
                                        //{
1763
                                        if (!string.IsNullOrEmpty(PSNItem.Status))
1764
                                            status += PSNItem.Status;
1765
                                        //}
1766

    
1767
                                        newRow["FROM_DATA"] = FROM_DATA;
1768
                                        newRow["TO_DATA"] = TO_DATA;
1769
                                        newRow["Type"] = PSNItem.GetPSNType();
1770

    
1771
                                        if (psnOrder > 0)
1772
                                        {
1773
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
1774
                                            if (!string.IsNullOrEmpty(PSNItem.Status))
1775
                                            {//status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
1776
                                                if (dr["Status"].ToString().Contains(PSNItem.Status))
1777
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
1778
                                                else if (dr["Status"].ToString().Contains(PSNItem.Status.Remove(0, 2)))
1779
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
1780

    
1781
                                            }
1782

    
1783
                                            if (dr != null)
1784
                                            {
1785
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
1786
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
1787
                                                newRow["Type"] = dr.Field<string>("Type");
1788
                                            }
1789
                                        }
1790

    
1791
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
1792
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
1793
                                        {
1794
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
1795
                                            int cnt = matches.Count;
1796
                                            if (cnt > 1)
1797
                                                status.Replace(", Missing LineNumber_1", string.Empty);
1798
                                        }
1799
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1800
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1801

    
1802

    
1803
                                        newRow["IsValid"] = PSNItem.IsValid;
1804
                                        newRow["Status"] = status;
1805
                                        newRow["PBS"] = PSNItem.GetPBSData();
1806

    
1807
                                        List<string> drawingNames = new List<string>();
1808
                                        foreach (Group _group in PSNItem.Groups)
1809
                                        {
1810
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
1811
                                            {
1812
                                                if (drawingNames.Count == 0)
1813
                                                    newRow["Drawings"] = _group.Document.DrawingName;
1814
                                                else
1815
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
1816
                                                drawingNames.Add(_group.Document.DrawingName);
1817
                                            }
1818
                                        }
1819

    
1820
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
1821
                                        if (bVentDrain)
1822
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
1823
                                        else
1824
                                            newRow["IncludingVirtualData"] = "No";
1825
                                        //    return;
1826
                                        //newRow["IncludingVirtualData"] = "No";
1827
                                        newRow["PSNAccuracy"] = "100";
1828

    
1829
                                        string Pocket = "No";
1830
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
1831
                                        if (Condition.Equals("Flare"))
1832
                                            Pocket = "Yes";
1833

    
1834
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment) 
1835
                                        {
1836
                                          //  string itemName = From_item.Name;
1837
                                            Equipment Equipment = From_item.Equipment;
1838
                                      
1839
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
1840
                                          
1841

    
1842
                                            if (nopocket != null)
1843
                                            {
1844
                                                DataRow bNozzle = null;
1845
                                                if (nopocket.Type.Equals("Vertical Vessel"))
1846
                                                {
1847
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
1848
                                                    if (drNozzle != null)
1849
                                                    {
1850
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
1851
                                                        {
1852
                                                            bNozzle = drNozzle;
1853
                                                        }
1854

    
1855
                                                        if (bNozzle == null)
1856
                                                        {
1857
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
1858

    
1859
                                                            if (drNozzle != null)
1860
                                                            {
1861
                                                                bNozzle = drNozzle;
1862
                                                                foreach (DataRow it in nozzleRows)
1863
                                                                {
1864
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
1865
                                                                    {
1866
                                                                        bNozzle = null;
1867
                                                                        break;
1868
                                                                    }
1869
                                                                }
1870
                                                            }
1871
                                                        }
1872
                                                    }
1873

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

    
1900
                                                        if (bNozzle == null)
1901
                                                        {
1902
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
1903

    
1904
                                                            if (drNozzle != null)
1905
                                                            {
1906
                                                                bNozzle = drNozzle;
1907
                                                                foreach (DataRow it in nozzleRows)
1908
                                                                {
1909
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
1910
                                                                    {
1911
                                                                        bNozzle = null;
1912
                                                                        break;
1913
                                                                    }
1914
                                                                }
1915
                                                            }
1916
                                                        }
1917
                                                    }                                                   
1918

    
1919
                                                    if (bNozzle != null)
1920
                                                        Pocket = "Yes";
1921
                                                }
1922
                                                else
1923
                                                    Pocket = "Yes";
1924
                                            }
1925
                                        }
1926
                                        
1927
                                        newRow["Pocket"] = Pocket;
1928
                                        string AFC = "P2";
1929
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
1930
                                        {
1931
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
1932
                                                AFC = "P1";
1933
                                        }
1934

    
1935
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
1936
                                        {
1937
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
1938
                                                AFC = "P1";
1939
                                        }
1940

    
1941
                                        newRow["AFC"] = AFC;
1942
                                        pipeSystemNetworkDT.Rows.Add(newRow);
1943
                                    }
1944
                                }
1945

    
1946
                            }
1947
                        
1948

    
1949
                        }
1950
                        catch (Exception ex)
1951
                        {
1952
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1953
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1954
                        }
1955

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

    
1973
                    }
1974
                    catch (Exception ee)
1975
                    {
1976

    
1977
                    }
1978
                }
1979

    
1980

    
1981
                foreach (var item in startBranchDic)
1982
                {
1983
                    string uid = item.Key.UID;
1984
                    string topologyName = item.Value.Topology.FullName;
1985
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1986

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

    
2010
                        if (targetRow != null)
2011
                        {
2012
                            targetRow["BranchTopologySet_OID"] = topologyName;
2013
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2014
                        }
2015
                    }
2016
                }
2017

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

    
2046
                        if (targetRow != null)
2047
                        {
2048
                            targetRow["BranchTopologySet_OID"] = topologyName;
2049
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2050
                        }
2051
                    }
2052
                }
2053

    
2054
                PathItems = pathItemsDT;
2055
                SequenceData = sequenceDataDT;
2056
                PipeSystemNetwork = pipeSystemNetworkDT;
2057
                TopologySet = topologySetDT;
2058
                PipeLine = pipelineDT;
2059
                PipeSystem = pipesystemDT;
2060
            }
2061
            catch (Exception ex)
2062
            {
2063
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2064
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2065
            }
2066
        }
2067

    
2068
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2069
        {
2070
            foreach (double lacc in lstAcc)
2071
            {
2072
                acc *= lacc;
2073
            }
2074
            return acc;
2075
        }
2076

    
2077
        private void UpdateSubType()
2078
        {
2079
            try
2080
            {
2081
                foreach (PSNItem PSNItem in PSNItems)
2082
                {
2083
                    if (PSNItem.IsBypass)
2084
                    {
2085
                        foreach (Topology topology in PSNItem.Topologies)
2086
                        {
2087
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2088
                            if (rows.Length.Equals(1))
2089
                                rows.First()["SubType"] = "Bypass";
2090
                        }
2091
                    }
2092

    
2093
                    if (PSNItem.StartType == PSNType.Header)
2094
                    {
2095
                        Topology topology = PSNItem.Topologies.First();
2096
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2097
                        if (rows.Length.Equals(1))
2098
                            rows.First()["SubType"] = "Header";
2099
                    }
2100
                    else if (PSNItem.EndType == PSNType.Header)
2101
                    {
2102
                        Topology topology = PSNItem.Topologies.Last();
2103
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2104
                        if (rows.Length.Equals(1))
2105
                            rows.First()["SubType"] = "Header";
2106
                    }
2107
                }
2108

    
2109

    
2110
                foreach (Topology topology in Topologies)
2111
                {
2112
                    try
2113
                    {
2114
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2115

    
2116
                        if (rows.Count() > 0)
2117
                        {
2118
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2119
                            {
2120
                                if (topology.Items == null)
2121
                                    continue;
2122

    
2123
                                Item firstItem = topology.Items.First();
2124
                                Item lastItem = topology.Items.Last();
2125

    
2126
                                List<Relation> relations = new List<Relation>();
2127

    
2128
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2129
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2130

    
2131
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2132
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2133

    
2134
                                if (relations.Count > 0)
2135
                                    rows.First()["SubType"] = "OtherSystem";
2136
                            }
2137
                        }
2138
                    }
2139
                    catch (Exception ex)
2140
                    {
2141

    
2142
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2143
                    }
2144
                }
2145

    
2146
                foreach (DataRow row in TopologySet.Rows)
2147
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
2148
                        row["SubType"] = "Normal";
2149
            }
2150
            catch (Exception ex)
2151
            {
2152
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2153
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2154
            }
2155
        }
2156

    
2157
        private bool IsBypass(PSNItem PSNItem)
2158
        {
2159
            bool bResult = false;
2160

    
2161
            if (PSNItem.GetPSNType() == "B2B")
2162
            {
2163
                Group firstGroup = PSNItem.Groups.First();
2164
                Group lastGroup = PSNItem.Groups.Last();
2165
                Item firstItem = firstGroup.Items.First();
2166
                Item lastItem = lastGroup.Items.Last();
2167

    
2168
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
2169
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
2170

    
2171
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
2172
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
2173
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
2174
                    bResult = true;
2175
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
2176
                    bResult = true;
2177
            }
2178

    
2179
            Item GetConnectedItemByPSN(Item item)
2180
            {
2181
                Item result = null;
2182

    
2183
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
2184
                if (relation != null)
2185
                    result = relation.Item;
2186

    
2187

    
2188
                return result;
2189
            }
2190

    
2191
            return bResult;
2192
        }
2193

    
2194
        private void DeleteVentDrain()
2195
        {
2196
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
2197

    
2198
            foreach (DataRow dataRow in ventdrainRows)
2199
            {
2200
                dataRow.Delete();
2201
            }
2202
        }
2203

    
2204
        private void UpdateAccuracy()
2205
        {
2206
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
2207
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
2208
            List<double> lstAcc = null;
2209
            string Status = string.Empty;
2210

    
2211
            foreach (DataRow dataRow in statusRows)
2212
            {
2213
                lstAcc = new List<double>();
2214
                Status = dataRow.Field<string>("Status");
2215
                if (!string.IsNullOrEmpty(Status))
2216
                {
2217
                    string[] arrStatus = Status.Split(',');
2218
                    foreach (string arrstr in arrStatus)
2219
                    {
2220
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
2221
                            lstAcc.Add(0.75);
2222

    
2223
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2224
                            lstAcc.Add(0.7);
2225

    
2226
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2227
                            lstAcc.Add(0.5);
2228

    
2229
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2230
                            lstAcc.Add(0.65);
2231

    
2232
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2233
                            lstAcc.Add(0.6);
2234
                    }
2235
                }
2236

    
2237
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
2238
                if (PSNAccuracy == "100")
2239
                    PSNAccuracy = "1";
2240

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

    
2262
                totalDdr *= 100;
2263

    
2264
                if (totalDdr != 100)
2265
                {
2266
                    foreach (DataRow ddr in select)
2267
                    {
2268
                        ddr["IncludingVirtualData"] = "Yes";
2269
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2270
                    }
2271
                }
2272
                else
2273
                {
2274
                    foreach (DataRow ddr in select)
2275
                    {
2276
                        ddr["IncludingVirtualData"] = "No";
2277
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2278
                    }
2279
                }
2280
            }
2281

    
2282
        }
2283

    
2284
        private void UpdateKeywordForPSN()
2285
        {
2286
            #region Keyword Info
2287
            KeywordInfo KeywordInfos = new KeywordInfo();
2288
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2289
            foreach (DataRow row in dtKeyword.Rows)
2290
            {
2291
                int index = Convert.ToInt32(row["INDEX"]);
2292
                string name = row["NAME"].ToString();
2293
                string keyword = row["KEYWORD"].ToString();
2294

    
2295
                //KeywordInfo keywordInfo = new KeywordInfo();   
2296
                KeywordInfos.KeywordItems.Add(new KeywordItem()
2297
                {
2298
                    Index = index,
2299
                    Name = name,
2300
                    Keyword = keyword
2301
                });
2302
            }
2303
            #endregion
2304

    
2305
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
2306
            foreach (DataRow dataRow in endofHeaderRows)
2307
            {
2308
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2309

    
2310
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
2311
                {
2312
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2313
                    DataRow dr = pathItemRows.First();
2314
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
2315
                    dr["TYPE"] = "End";
2316
                    dr["ITEMTAG"] = "ENDOFHEADER";
2317
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2318
                }
2319

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

    
2331
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2332
            {
2333
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
2334
                foreach (DataRow dataRow in keywordRows)
2335
                {
2336
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2337

    
2338
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
2339
                    {
2340
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2341

    
2342
                        //
2343
                        //if(.)
2344
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
2345
                        {
2346
                            DataRow dr = pathItemRows.First();
2347
                            //dr["CLASS"] = ""; //Type
2348
                            dr["TYPE"] = "End";
2349
                            dr["ITEMTAG"] = keyitem.Keyword;
2350
                            dr["DESCRIPTION"] = keyitem.Keyword;
2351
                        }
2352

    
2353
                    }
2354

    
2355
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
2356
                    {
2357
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2358

    
2359
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
2360
                        {
2361
                            DataRow dr = pathItemRows.Last();
2362
                            //dr["CLASS"] = ""; //Type
2363
                            dr["TYPE"] = "End";
2364
                            dr["ITEMTAG"] = keyitem.Keyword;
2365
                            dr["DESCRIPTION"] = keyitem.Keyword;
2366
                            //dr.Field<string>("Type")
2367
                        }
2368

    
2369
                    }
2370
                }
2371
            }
2372
        }
2373

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

    
2392
                        Item item = PSNItem.Groups.First().Items.First();
2393
                        try
2394
                        {
2395
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2396

    
2397
                            tieInPointIndex++;
2398

    
2399

    
2400
                            if (item.ItemType == ItemType.Line)
2401
                            {
2402
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2403
                                bCount = 2;
2404

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

    
2426
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2427
                                bCount = 3;
2428
                            }
2429

    
2430
                            PSNItem.StartType = PSNType.Equipment;
2431
                        }
2432
                        catch (Exception ex)
2433
                        {
2434
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2435
                            return;
2436
                        }
2437
                    }
2438

    
2439
                    if (!PSNItem.EnableType(PSNItem.EndType))
2440
                    {
2441
                        change = true;
2442
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2443
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
2444

    
2445
                        Item item = PSNItem.Groups.Last().Items.Last();
2446
                        try
2447
                        {
2448
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2449

    
2450
                            if (item.ItemType == ItemType.Line)
2451
                            {
2452
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2453
                                {
2454
                                    loopRow["TO_DATA"] = TO_DATA;
2455
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
2456
                                    {
2457
                                        string status = loopRow.Field<string>("Status");
2458
                                        if (string.IsNullOrEmpty(status))
2459
                                            status = "Line Disconnected";
2460
                                        else if (!status.Contains("Line Disconnected"))
2461
                                            status += ", Line Disconnected";
2462
                                        loopRow["Status"] = status;
2463
                                        if (!string.IsNullOrEmpty(status))
2464
                                            loopRow["IsValid"] = "Error";
2465
                                    }
2466
                                }
2467
                            }
2468

    
2469
                            tieInPointIndex++;
2470

    
2471
                            if (!bCheck)
2472
                            {
2473
                                if (item.ItemType == ItemType.Line)
2474
                                {
2475
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
2476
                                }
2477
                                else
2478
                                {
2479
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
2480
                                    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);
2481
                                }
2482
                            }
2483
                            else
2484
                            {
2485
                                if (item.ItemType == ItemType.Line)
2486
                                {
2487
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
2488
                                }
2489
                                else
2490
                                {
2491
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
2492
                                    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);
2493
                                }
2494
                            }
2495

    
2496

    
2497
                            PSNItem.EndType = PSNType.Equipment;
2498
                        }
2499
                        catch (Exception ex)
2500
                        {
2501
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2502
                            return;
2503
                        }
2504
                    }
2505

    
2506
                    dataRow["Type"] = PSNItem.GetPSNType();
2507
                    if (change)
2508
                    {
2509
                        int rowIndex = 0;
2510
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2511
                        {
2512
                            DataRow row = PathItems.Rows[i];
2513
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
2514
                                continue;
2515
                            string sequenceData = row["SequenceData_OID"].ToString();
2516
                            string[] split = sequenceData.Split(new char[] { '_' });
2517

    
2518
                            StringBuilder sb = new StringBuilder();
2519
                            for (int j = 0; j < split.Length - 1; j++)
2520
                                sb.Append(split[j] + "_");
2521
                            sb.Append(rowIndex++);
2522
                            row["SequenceData_OID"] = sb.ToString();
2523

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

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

    
2529
                            if (seqItemRows == null)
2530
                            {
2531
                                DataRow newRow = SequenceData.NewRow();
2532
                                newRow["OID"] = sb.ToString();
2533
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2534
                                newRow["PathItem_OID"] = row["OID"];
2535
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2536
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2537
                            }
2538
                            else
2539
                            {
2540
                                seqItemRows["OID"] = sb.ToString();
2541
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2542
                                seqItemRows["PathItem_OID"] = row["OID"];
2543
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2544
                            }
2545
                        }
2546
                    }
2547

    
2548
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
2549
                    {
2550
                        DataRow newRow = PathItems.NewRow();
2551
                        newRow["OID"] = Guid.NewGuid().ToString();
2552
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2553
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2554
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2555
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2556
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
2557
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
2558
                        newRow["DESCRIPTION"] = DATA;
2559
                        newRow["Class"] = "End of line terminator";
2560
                        newRow["SubClass"] = "End of line terminator";
2561
                        newRow["TYPE"] = "End";
2562
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2563
                        newRow["NPD"] = itemRow["NPD"];
2564
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2565
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2566
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2567

    
2568
                        return newRow;
2569
                    }
2570

    
2571
                    DataRow createLineRow(DataRow itemRow)
2572
                    {
2573
                        DataRow newRow = PathItems.NewRow();
2574
                        newRow["OID"] = Guid.NewGuid().ToString();
2575
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2576
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2577
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2578
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2579
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
2580
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2581
                        newRow["Class"] = itemRow["Class"];
2582
                        newRow["SubClass"] = itemRow["SubClass"];
2583
                        newRow["TYPE"] = itemRow["TYPE"];
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

    
2590
                        return newRow;
2591
                    }
2592
                }
2593
                catch (Exception ex)
2594
                {
2595

    
2596
                }
2597
            }
2598
        }
2599

    
2600
        private void InsertTeePSN()
2601
        {
2602
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
2603
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
2604
            bool change = false;
2605
            foreach (DataRow dataRow in branchRows)
2606
            {
2607
                try
2608
                {
2609
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2610
                    change = false;
2611

    
2612
                    if (PSNItem.StartType == PSNType.Branch)
2613
                    {
2614
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2615
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2616
                        Item Teeitem = PSNItem.Groups.First().Items.First();
2617
                        try
2618
                        {
2619
                            if (Teeitem.ItemType == ItemType.Line)
2620
                            {
2621
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
2622
                                {
2623
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
2624
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
2625
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2626
                                    change = true;
2627
                                }
2628

    
2629
                            }
2630
                        }
2631
                        catch (Exception ex)
2632
                        {
2633
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2634
                            return;
2635
                        }
2636
                    }
2637

    
2638
                    if (PSNItem.EndType == PSNType.Branch)
2639
                    {
2640
                        //change = true;
2641
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2642

    
2643
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
2644

    
2645
                        DataRow dr = pathItemRows.Last();
2646
                        if (change)
2647
                            dr = pathItemRows[pathItemRows.Count() - 2];
2648

    
2649
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2650

    
2651
                        try
2652
                        {
2653
                            if (Teeitem.ItemType == ItemType.Line)
2654
                            {
2655
                                if (dr.Field<string>("SubClass") != "Tee")
2656
                                {
2657
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
2658
                                    change = true;
2659
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
2660
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2661
                                }
2662

    
2663
                            }
2664
                        }
2665
                        catch (Exception ex)
2666
                        {
2667
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2668
                            return;
2669
                        }
2670
                    }
2671

    
2672
                    if (change)
2673
                    {
2674
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2675
                        int rowIndex = 0;
2676
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2677
                        {
2678
                            DataRow row = PathItems.Rows[i];
2679
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
2680
                                continue;
2681
                            string sequenceData = row["SequenceData_OID"].ToString();
2682
                            string[] split = sequenceData.Split(new char[] { '_' });
2683

    
2684
                            StringBuilder sb = new StringBuilder();
2685
                            for (int j = 0; j < split.Length - 1; j++)
2686
                                sb.Append(split[j] + "_");
2687
                            sb.Append(rowIndex++);
2688
                            row["SequenceData_OID"] = sb.ToString();
2689

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

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

    
2695
                            if (seqItemRows == null)
2696
                            {
2697
                                DataRow newRow = SequenceData.NewRow();
2698
                                newRow["OID"] = sb.ToString();
2699
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2700
                                newRow["PathItem_OID"] = row["OID"];
2701
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2702
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2703
                            }
2704
                            else
2705
                            {
2706
                                seqItemRows["OID"] = sb.ToString();
2707
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2708
                                seqItemRows["PathItem_OID"] = row["OID"];
2709
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2710
                            }
2711
                        }
2712
                    }
2713

    
2714
                    DataRow createTeeRow(DataRow itemRow)
2715
                    {
2716
                        DataRow newRow = PathItems.NewRow();
2717
                        newRow["OID"] = Guid.NewGuid().ToString();
2718
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2719
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2720
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2721
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2722
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
2723
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2724
                        newRow["DESCRIPTION"] = "";
2725
                        newRow["Class"] = "Branch";
2726
                        newRow["SubClass"] = "Tee";
2727
                        newRow["TYPE"] = itemRow["TYPE"];
2728
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2729
                        newRow["NPD"] = itemRow["NPD"];
2730
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2731
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2732
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2733
                      
2734
                        newRow["EGTConnectedPoint"] = 0;
2735
                        return newRow;
2736
                    }
2737
                }
2738
                catch (Exception ex)
2739
                {
2740

    
2741
                }
2742
            }
2743
        }
2744
    }
2745

    
2746
    public class PSNItem
2747
    {
2748
        public PSNItem(int count, int Revision)
2749
        {
2750
            Groups = new List<Group>();
2751
            Topologies = new List<Topology>();
2752

    
2753
            Index = count + 1;
2754
            this.Revision = Revision;
2755
        }
2756

    
2757
        private int Revision;
2758
        public string UID { get; set; }
2759
        public List<Group> Groups { get; set; }
2760
        public List<Topology> Topologies { get; set; }
2761
        public PSNType StartType { get; set; }
2762
        public PSNType EndType { get; set; }
2763
        public int Index { get; set; }
2764
        public string IsValid { get; set; }
2765
        public bool IsKeyword { get; set; }
2766
        public string Status { get; set; }
2767
        public string IncludingVirtualData { get; set; }
2768
        public string PSNAccuracy { get; set; }
2769
        public KeywordInfo KeywordInfos = new KeywordInfo();
2770
        public DataTable Nozzle = new DataTable();
2771

    
2772
        public string PSN_OID()
2773
        {
2774
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
2775
        }
2776

    
2777
        public string GetPSNType()
2778
        {
2779
            string result = string.Empty;
2780

    
2781
            if (EnableType(StartType) && EnableType(EndType))
2782
            {
2783
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
2784
                    result = "E2E";
2785
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
2786
                    result = "B2B";
2787
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
2788
                    result = "HD2";
2789

    
2790
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
2791
                    result = "E2B";
2792
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
2793
                    result = "B2E";
2794

    
2795
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
2796
                    result = "HDB";
2797
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
2798
                    result = "HDB";
2799

    
2800
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
2801
                    result = "HDE";
2802
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
2803
                    result = "HDE";
2804
                else
2805
                    result = "Error";
2806
            }
2807
            else
2808
                result = "Error";
2809

    
2810
            return result;
2811

    
2812

    
2813
        }
2814

    
2815
        public bool EnableType(PSNType type)
2816
        {
2817
            bool result = false;
2818

    
2819
            if (type == PSNType.Branch ||
2820
                type == PSNType.Equipment ||
2821
                type == PSNType.Header)
2822
            {
2823
                result = true;
2824
            }
2825

    
2826
            return result;
2827
        }
2828

    
2829
        public bool IsBypass { get; set; }
2830

    
2831
        public string GetFromData(ref string Type, ref Item item)
2832
        {
2833
            Status = string.Empty;
2834
            string result = string.Empty;
2835
            if (IsKeyword)
2836
                IsKeyword = false;
2837
            try
2838
            {
2839
                item = Groups.First().Items.First();
2840

    
2841
                if (StartType == PSNType.Header)
2842
                    result = "ENDOFHEADER";
2843
                else if (StartType == PSNType.Branch)
2844
                {
2845
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2846
                    if (!item.MissingLineNumber2 && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2847
                        result = item.Relations.First().Item.LineNumber.Name;
2848
                    else
2849
                    {
2850
                        IsValid = "Error";
2851
                        Status += ", Missing LineNumber_2";
2852
                        result = "Empty LineNumber";
2853
                    }
2854

    
2855
                    //if (item.MissingLineNumber1)
2856
                    //{
2857
                    //    Status += ", Missing LineNumber_1";
2858
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2859

    
2860
                    //}
2861
                }
2862
                else if (StartType == PSNType.Equipment)
2863
                {
2864
                    if (Groups.First().Items.First().Equipment != null)
2865
                        result = Groups.First().Items.First().Equipment.ItemTag;
2866
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
2867

    
2868
                    if (drNozzle != null)
2869
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2870
                }
2871
                else
2872
                {
2873
                    IsValid = "Error";
2874
                    item = Groups.First().Items.First();
2875
                    if (item.ItemType == ItemType.Symbol)
2876
                    {
2877

    
2878
                        string keyword = string.Empty;
2879
                        keyword = GetFromKeywordData(ref Type, item);
2880

    
2881
                        if (string.IsNullOrEmpty(keyword))
2882
                        {
2883
                            if (item.ID2DBType.Contains("OPC's"))
2884
                                Status += ", OPC Disconnected";
2885
                            else
2886
                                Status += ", Missing ItemTag or Description";
2887

    
2888
                            result = item.ID2DBName;
2889
                        }
2890
                        else
2891
                        {
2892
                            result = keyword;
2893
                            IsKeyword = true;
2894
                            IsValid = string.Empty;
2895
                        }
2896

    
2897
                    }
2898
                    else if (item.ItemType == ItemType.Line)
2899
                    {
2900

    
2901
                        if (item.MissingLineNumber1)
2902
                        {
2903
                            IsValid = "Error";
2904
                            Status += ", Missing LineNumber_1";
2905
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2906
                        }
2907
                    }
2908
                    else
2909
                        result = "Unknown";
2910

    
2911
                }
2912
            }
2913
            catch (Exception ex)
2914
            {
2915

    
2916
            }
2917

    
2918
            return result;
2919
        }
2920

    
2921
        public string GetFromKeywordData(ref string Type, Item item)
2922
        {
2923
            string result = string.Empty;
2924

    
2925
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2926
            {
2927
                if (keyitem.Name.Equals(item.Name))
2928
                {
2929
                    result = keyitem.Keyword;
2930
                    Type = item.ID2DBType;
2931
                    break;
2932
                }
2933
            }
2934

    
2935
            return result;
2936
        }
2937

    
2938
        public string GetToKeywordData(ref string Type, Item item)
2939
        {
2940
            string result = string.Empty;
2941

    
2942
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2943
            {
2944
                if (keyitem.Name.Equals(item.Name))
2945
                {
2946
                    result = keyitem.Keyword;
2947
                    Type = item.ID2DBType;
2948
                    break;
2949
                }
2950
            }
2951
            return result;
2952
        }
2953

    
2954
        public string GetToData(ref string ToType, ref Item item)
2955
        {
2956
            string result = string.Empty;
2957
            Status = string.Empty;
2958

    
2959
            if (IsKeyword)
2960
                IsKeyword = false;
2961

    
2962
            item = Groups.Last().Items.Last();
2963

    
2964
            if (EndType == PSNType.Header)
2965
                result = "ENDOFHEADER";
2966
            else if (EndType == PSNType.Branch)
2967
            {
2968
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2969
                if (!item.MissingLineNumber2 && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2970
                    result = item.Relations.Last().Item.LineNumber.Name;
2971
                else
2972
                {
2973
                    IsValid = "Error";
2974
                    Status += ", Missing LineNumber_2";
2975
                    result = "Empty LineNumber";
2976
                }
2977

    
2978
                //if (item.MissingLineNumber1)
2979
                //{
2980
                //    Status += ", Missing LineNumber_1";
2981
                //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2982

    
2983
                //}
2984
            }
2985
            else if (EndType == PSNType.Equipment)
2986
            {
2987
                if (Groups.Last().Items.Last().Equipment != null)
2988
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
2989

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

    
2992
                if (drNozzle != null)
2993
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2994
            }
2995
            else
2996
            {
2997
                IsValid = "Error";
2998
                item = Groups.Last().Items.Last();
2999
                if (item.ItemType == ItemType.Symbol)
3000
                {
3001
                    string keyword = string.Empty;
3002
                    keyword = GetToKeywordData(ref ToType, item);
3003

    
3004
                    if (string.IsNullOrEmpty(keyword))
3005
                    {
3006
                        if (item.ID2DBType.Contains("OPC's"))
3007
                            Status += ", OPC Disconnected";
3008
                        else
3009
                            Status += ", Missing ItemTag or Description";
3010

    
3011
                        result = item.ID2DBName;
3012
                    }
3013
                    else
3014
                    {
3015
                        result = keyword;
3016
                        IsValid = string.Empty;
3017
                        IsKeyword = true;
3018
                    }
3019

    
3020
                }
3021
                else if (item.ItemType == ItemType.Line)
3022
                {
3023
                    if (item.MissingLineNumber1)
3024
                    {
3025
                        IsValid = "Error";
3026
                        Status += ", Missing LineNumber_1";
3027
                        result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
3028
                    }
3029
                }
3030
                else
3031
                    result = "Unknown";
3032

    
3033

    
3034
            }
3035

    
3036

    
3037

    
3038
            return result;
3039
        }
3040

    
3041
        public string GetPBSData()
3042
        {
3043
            string result = string.Empty;
3044
            List<string> PBSList = new List<string>();
3045
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3046
            {
3047
                string attrValue = Settings.Default.PBSSettingValue;
3048

    
3049
                foreach (Group group in Groups)
3050
                {
3051
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3052
                    foreach (LineNumber lineNumber in lineNumbers)
3053
                    {
3054
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3055
                        if (attribute != null)
3056
                        {
3057
                            string value = attribute.Value;
3058
                            if (!PBSList.Contains(value))
3059
                                PBSList.Add(value);
3060
                        }
3061
                    }
3062
                }
3063
            }
3064
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3065
            {
3066
                string attrValue = Settings.Default.PBSSettingValue;
3067

    
3068
                foreach (Group group in Groups)
3069
                {
3070
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3071
                    foreach (Item item in items)
3072
                    {
3073
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3074
                        if (!PBSList.Contains(value))
3075
                            PBSList.Add(value);
3076
                    }
3077
                }
3078
            }
3079
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3080
            {
3081
                string attrValue = Settings.Default.PBSSettingValue;
3082

    
3083
                foreach (Group group in Groups)
3084
                {
3085
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3086
                    foreach (Document document in documents)
3087
                    {
3088
                        string name = document.DrawingName;
3089

    
3090
                        int startIndex = Settings.Default.PBSSettingStartValue;
3091
                        int endIndex = Settings.Default.PBSSettingEndValue;
3092

    
3093
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3094
                        if (!PBSList.Contains(subStr))
3095
                            PBSList.Add(subStr);
3096
                    }
3097
                }
3098
            }
3099
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3100
            {
3101
                foreach (Group group in Groups)
3102
                {
3103
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3104
                    foreach (Document document in documents)
3105
                    {
3106
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
3107
                        foreach (TextInfo textInfo in textInfos)
3108
                        {
3109
                            if (!PBSList.Contains(textInfo.Value))
3110
                                PBSList.Add(textInfo.Value);
3111
                        }
3112
                    }
3113
                }
3114
            }
3115

    
3116
            foreach (var item in PBSList)
3117
            {
3118
                if (string.IsNullOrEmpty(result))
3119
                    result = item;
3120
                else
3121
                    result += ", " + item;
3122
            }
3123
            return result;
3124
        }
3125
    }
3126
}
클립보드 이미지 추가 (최대 크기: 500 MB)