프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ 48870200

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

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

    
52
        int tieInPointIndex = 1;
53

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

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

    
62
        ID2Info id2Info = ID2Info.GetInstance();
63

    
64
        
65

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

    
69
        public PSN()
70
        {
71
            
72
        }
73

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

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

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

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

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

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

    
246
        private void SetTopologyData()
247
        {
248
            // 13번 excel
249
            foreach (Group group in groups)
250
            {
251
                LineNumber prevLineNumber = null;
252
                for (int i = 0; i < group.Items.Count; i++)
253
                {
254
                    Item item = group.Items[i];
255
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
256
                    if (lineNumber == null)
257
                    {
258
                        if (prevLineNumber != null)
259
                        {
260
                            if (!prevLineNumber.IsCopy)
261
                            {
262
                                prevLineNumber = prevLineNumber.Copy();
263
                                item.Document.LineNumbers.Add(prevLineNumber);
264
                                item.MissingLineNumber1 = true;
265
                            }
266
                            item.Owner = prevLineNumber.UID;
267
                        }
268
                    }
269
                    else
270
                        prevLineNumber = lineNumber;
271
                }
272

    
273
                prevLineNumber = null;
274
                for (int i = group.Items.Count - 1; i > -1; i--)
275
                {
276
                    Item item = group.Items[i];
277
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
278
                    if (lineNumber == null)
279
                    {
280
                        if (prevLineNumber != null)
281
                        {
282
                            if (!prevLineNumber.IsCopy)
283
                            {
284
                                prevLineNumber = prevLineNumber.Copy();
285
                                item.Document.LineNumbers.Add(prevLineNumber);
286
                                item.MissingLineNumber1 = true;
287
                            }
288

    
289
                            item.Owner = prevLineNumber.UID;
290
                        }
291
                    }
292
                    else
293
                        prevLineNumber = lineNumber;
294
                }
295

    
296
                if (prevLineNumber == null)
297
                {
298
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
299
                    Random random = new Random();
300
                    int index = random.Next(lineNumbers.Count - 1);
301

    
302
                    // Copy
303
                    LineNumber cLineNumber = lineNumbers[index].Copy();
304
                    group.Document.LineNumbers.Add(cLineNumber);
305
                    
306
                    foreach (Item item in group.Items)
307
                    {
308
                        item.Owner = cLineNumber.UID;
309
                        item.MissingLineNumber2 = true;
310
                    }                    
311
                }
312
            }
313

    
314
            foreach (Document document in Documents)
315
            {
316
                foreach (Item item in document.Items)
317
                {
318
                    item.TopologyData = string.Empty;
319
                    item.PSNPipeLineID = string.Empty;
320
                    List<string> pipeLineID = new List<string>();
321
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
322
                    if (lineNumber != null)
323
                    {
324
                        item.LineNumber = lineNumber;
325

    
326
                        foreach (DataRow row in topologyRuleDT.Rows)
327
                        {
328
                            string uid = row["UID"].ToString();
329
                            //if (uid == "-")
330
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
331
                            if (uid != "-")
332
                            {
333
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
334

    
335
                                Attribute attribute = lineNumber.Attributes.Find(x => x.Name == uid);
336
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
337
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
338
                            }
339
                        }
340

    
341
                        if(topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
342
                        {
343
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
344
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
345
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
346
                                                                 //else
347
                                                                 //    item.PSNPipeLineID = item.TopologyData;
348
                        }
349

    
350
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
351
                        item.TopologyData = string.Join("-", pipeLineID);
352
                        
353
                    }
354
                    else
355
                    {
356
                        item.TopologyData = "Empty LineNumber";
357
                        item.LineNumber = new LineNumber();
358
                    }
359
                }
360
            }
361

    
362
            int emptyIndex = 1;
363
            foreach (Group group in groups)
364
            {
365
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
366
                if (groupItems.Count > 0)
367
                {
368
                    foreach (var item in groupItems)
369
                        item.TopologyData += string.Format("-{0}", emptyIndex);
370
                    emptyIndex++;
371
                }
372
            }
373

    
374
        }
375

    
376
        
377
        private void ConnectByOPC()
378
        {
379
            try
380
            {
381
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
382
                {
383
                    Item opcItem = group.Items.Last();
384
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
385
                    if (fromRows.Length.Equals(1))
386
                    {
387
                        DataRow opcRow = fromRows.First();
388
                        string toDrawing = opcRow["ToDrawing"].ToString();
389
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
390

    
391
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
392
                        if (toDocument != null)
393
                        {
394
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
395
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
396
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
397
                            if (toRows.Length > 1)
398
                            {
399
                                //throw new Exception("OPC error(multi connect)");
400
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
401
                                return;
402
                            }
403
                            group.EndGroup = toGroup;
404
                            toGroup.StartGroup = group;
405
                        }
406
                    }
407
                }
408
            }
409
            catch (Exception ex)
410
            {
411
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
412
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
413
            }
414
        }
415

    
416
        private void SetPSNItem()
417
        {
418
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>(); 
419
            foreach (Group group in groups)
420
                groupDic.Add(group, Guid.NewGuid().ToString());
421

    
422
            foreach (Group group in groups)
423
            {
424
                string groupKey = groupDic[group];
425
                if (group.StartGroup != null)
426
                {
427
                    string otherKey = groupDic[group.StartGroup];
428
                    ChangeGroupID(otherKey, groupKey);
429
                }
430
            }
431

    
432
            // PSN 정리
433
            foreach (var item in groupDic)
434
            {
435
                Group group = item.Key;
436
                string uid = item.Value;
437
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
438
                if (PSNItem == null)
439
                {
440
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
441
                    PSNItems.Add(PSNItem);
442
                }
443
                PSNItem.Groups.Add(group);
444
                foreach (Item groupItem in group.Items)
445
                    groupItem.PSNItem = PSNItem;
446
            }
447

    
448
            // Sort PSN
449
            foreach (PSNItem PSNItem in PSNItems)
450
            {
451
                List<Group> _groups = new List<Group>();
452

    
453
                Stack<Group> stacks = new Stack<Group>();
454
                stacks.Push(PSNItem.Groups.First());
455
                while (stacks.Count > 0)
456
                {
457
                    Group stack = stacks.Pop();
458
                    if (_groups.Contains(stack))
459
                        continue;
460

    
461
                    if (_groups.Count == 0)
462
                        _groups.Add(stack);
463
                    else
464
                    {
465
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
466
                        {
467
                            int index = _groups.IndexOf(stack.StartGroup);
468
                            _groups.Insert(index + 1, stack);
469
                        }
470
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
471
                        {
472
                            int index = _groups.IndexOf(stack.EndGroup);
473
                            _groups.Insert(index, stack);
474
                        }
475
                    }
476

    
477
                    if (stack.StartGroup != null)
478
                        stacks.Push(stack.StartGroup);
479
                    if (stack.EndGroup != null)
480
                        stacks.Push(stack.EndGroup);
481
                }
482

    
483
                PSNItem.Groups.Clear();
484
                PSNItem.Groups.AddRange(_groups);
485
            }
486

    
487
            void ChangeGroupID(string from, string to)
488
            {
489
                if (from.Equals(to))
490
                    return;
491

    
492
                List<Group> changeItems = new List<Group>();
493
                foreach (var _item in groupDic)
494
                    if (_item.Value.Equals(from))
495
                        changeItems.Add(_item.Key);
496
                foreach (var _item in changeItems)
497
                    groupDic[_item] = to;
498
            }
499
        }
500

    
501
        private void SetPSNType()
502
        {
503
            foreach (PSNItem PSNItem in PSNItems)
504
            {
505
                Group firstGroup = PSNItem.Groups.First();
506
                Group lastGroup = PSNItem.Groups.Last();
507

    
508
                Item firstItem = firstGroup.Items.First();
509
                Item lastItem = lastGroup.Items.Last();
510

    
511
                PSNItem.StartType = GetPSNType(firstItem, true);
512
                PSNItem.EndType = GetPSNType(lastItem, false);
513
            }
514

    
515
            PSNType GetPSNType(Item item, bool bFirst = true)
516
            {
517
                PSNType type = PSNType.None;
518

    
519
                if (item.ItemType == ItemType.Line)
520
                {
521
                    Group group = groups.Find(x => x.Items.Contains(item));
522
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
523
                    {
524
                        Item connItem = item.Relations[0].Item;
525
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
526
                            type = PSNType.Branch;
527
                        else if (connItem.ItemType == ItemType.Symbol)
528
                            type = PSNType.Symbol;
529
                    }
530
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
531
                    {
532
                        Item connItem = item.Relations[1].Item;
533
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
534
                            type = PSNType.Branch;
535
                        else if (connItem.ItemType == ItemType.Symbol)
536
                            type = PSNType.Symbol;
537
                    }
538
                }
539
                else if (item.ItemType == ItemType.Symbol)
540
                {
541
                    if (item.SubItemType == SubItemType.Nozzle)
542
                        type = PSNType.Equipment;
543
                    else if (item.SubItemType == SubItemType.Header)
544
                        type = PSNType.Header;
545
                    else if (item.SubItemType == SubItemType.OPC)
546
                        type = PSNType.OPC;
547
                }
548

    
549
                return type;
550
            }
551
        }
552

    
553
        private void SetBranchInfo()
554
        {
555
            foreach (Document document in Documents)
556
            {
557
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
558
                foreach (Item line in lines)
559
                {
560
                    double[] point = line.Relations[0].Point;
561
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
562
                    connLines.Sort(SortBranchLine);
563
                    line.BranchItems.AddRange(connLines);
564

    
565
                    int SortBranchLine(Item a, Item b)
566
                    {
567
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
568
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
569

    
570
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
571
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
572

    
573
                        // 내림차순
574
                        return distanceA.CompareTo(distanceB);
575
                    }
576
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
577
                    {
578
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
579
                    }
580
                }
581
            }
582
        }
583

    
584
        private void SetTopology()
585
        {
586
            try
587
            {
588
                #region 기본 topology 정리
589
                foreach (PSNItem PSNItem in PSNItems)
590
                {
591
                    Topology topology = null;
592
                    foreach (Group group in PSNItem.Groups)
593
                    {
594
                        foreach (Item item in group.Items)
595
                        {
596
                            if (string.IsNullOrEmpty(item.TopologyData))
597
                                topology = null;
598
                            else
599
                            {
600
                                if (topology == null)
601
                                {
602
                                    topology = new Topology()
603
                                    {
604
                                        ID = item.TopologyData
605
                                    };
606
                                    Topologies.Add(topology);
607

    
608
                                    if (!PSNItem.Topologies.Contains(topology))
609
                                        PSNItem.Topologies.Add(topology);
610
                                }
611
                                else
612
                                {
613
                                    if (topology.ID != item.TopologyData)
614
                                    {
615
                                        topology = new Topology()
616
                                        {
617
                                            ID = item.TopologyData
618
                                        };
619
                                        Topologies.Add(topology);
620

    
621
                                        if (!PSNItem.Topologies.Contains(topology))
622
                                            PSNItem.Topologies.Add(topology);
623
                                    }
624
                                }
625

    
626
                                item.Topology = topology;
627
                                topology.Items.Add(item);
628
                            }
629
                        }
630
                    }
631
                }
632
                #endregion
633

    
634
                #region Type
635
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
636
                foreach (string id in ids)
637
                {
638
                    try
639
                    {
640

    
641

    
642
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
643

    
644
                        // Main
645
                        List<Topology> mainTopologies = FindMainTopology(topologies);
646
                        foreach (Topology topology in mainTopologies)
647
                            topology.Type = "M";
648

    
649
                        // Branch
650
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
651
                        foreach (Topology topology in branchToplogies)
652
                            topology.Type = "B";
653
                    }
654
                    catch (Exception ex)
655
                    {
656
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
657
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
658
                    }
659
                }
660
                #endregion
661
            }
662
            catch (Exception ex)
663
            {
664
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
665
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
666
            }
667

    
668
        }
669

    
670
        private void SetTopologyIndex()
671
        {
672
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
673
            foreach (string id in ids)
674
            {
675
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
676

    
677
                // Main
678
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
679
                foreach (Topology topology in mainTopologies)
680
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
681

    
682
                // Branch
683
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
684
                foreach (Topology topology in branchToplogies)
685
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
686
            }
687
        }
688

    
689
        private void SetPSNBypass()
690
        {
691
            foreach (PSNItem PSNItem in PSNItems)
692
                PSNItem.IsBypass = IsBypass(PSNItem);
693
        }
694

    
695
        private List<Topology> FindMainTopology(List<Topology> data)
696
        {
697
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
698
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
699
            //2021.11.17 안쓰네 JY
700
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
701

    
702
            List<Topology> main = new List<Topology>();
703
            main.AddRange(data);
704
            //
705
            main = GetNozzleTopology(data);
706
            if (main.Count == 1)
707
                return main;
708
            else
709
            {
710
                if (main.Count > 0)
711
                    main = GetPMCTopology(main);
712
                else
713
                    main = GetPMCTopology(data);
714

    
715
                if (main.Count == 1)
716
                    return main;
717
                else
718
                {
719
                    if (main.Count > 0)
720
                        main = GetDiaTopology(main);
721
                    else
722
                        main = GetDiaTopology(data);
723

    
724

    
725
                    if (main.Count == 1)
726
                        return main;
727
                    else
728
                    {
729
                        if (main.Count > 0)
730
                            main = GetItemTopology(main);
731
                        else
732
                            main = GetItemTopology(data);
733
                    }
734
                }
735
            }
736

    
737
            List<Topology> GetNozzleTopology(List<Topology> topologies)
738
            {
739
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
740
            }
741

    
742
            List<Topology> GetPMCTopology(List<Topology> topologies)
743
            {
744
                List<Topology> result = new List<Topology>();
745
                foreach (DataRow row in PMCDT.Rows)
746
                {
747
                    string value = row["CODE"].ToString();
748
                    foreach (Topology topology in topologies)
749
                    {
750
                        foreach (Item item in topology.Items)
751
                        {
752
                            if (item.LineNumber == null)
753
                                continue;
754
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
755
                            if (attribute != null && value == attribute.Value)
756
                            {
757
                                result.Add(topology);
758
                                break;
759
                            }
760
                        }
761
                    }
762

    
763
                    if (result.Count > 0)
764
                        break;
765
                }
766

    
767
                return result;
768
            }
769

    
770
            List<Topology> GetDiaTopology(List<Topology> topologies)
771
            {
772
                List<Topology> result = new List<Topology>();
773
                foreach (DataRow row in nominalDiameterDT.Rows)
774
                {
775
                    string inchValue = row["InchStr"].ToString();
776
                    string metricValue = row["MetricStr"].ToString();
777
                    foreach (Topology topology in topologies)
778
                    {
779
                        foreach (Item item in topology.Items)
780
                        {
781
                            if (item.LineNumber == null)
782
                                continue;
783
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
784
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
785
                            {
786
                                result.Add(topology);
787
                                break;
788
                            }
789
                        }
790
                    }
791

    
792
                    if (result.Count > 0)
793
                        break;
794
                }
795

    
796
                return result;
797
            }
798

    
799
            List<Topology> GetItemTopology(List<Topology> topologies)
800
            {
801
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
802
            }
803

    
804
            return main;
805
        }
806

    
807
        private DataTable GetOPCInfo()
808
        {
809
            DataTable opc = DB.SelectOPCRelations();
810
            DataTable drawing = DB.SelectDrawings();
811

    
812
            DataTable dt = new DataTable();
813
            dt.Columns.Add("FromDrawing", typeof(string));
814
            dt.Columns.Add("FromDrawingUID", typeof(string));
815
            dt.Columns.Add("FromOPCUID", typeof(string));
816
            dt.Columns.Add("ToDrawing", typeof(string));
817
            dt.Columns.Add("ToDrawingUID", typeof(string));
818
            dt.Columns.Add("ToOPCUID", typeof(string));
819
            foreach (DataRow row in opc.Rows)
820
            {
821
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
822
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString(); 
823
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString(); 
824
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
825
                if (!string.IsNullOrEmpty(toOPCUID))
826
                {
827
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
828
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
829
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
830
                    {
831
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
832
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
833

    
834
                        DataRow newRow = dt.NewRow();
835
                        newRow["FromDrawing"] = fromDrawingName;
836
                        newRow["FromDrawingUID"] = fromDrawingUID;
837
                        newRow["FromOPCUID"] = fromOPCUID;
838
                        newRow["ToDrawing"] = toDrawingName;
839
                        newRow["ToDrawingUID"] = toDrawingUID;
840
                        newRow["ToOPCUID"] = toOPCUID;
841

    
842
                        dt.Rows.Add(newRow);
843
                    }
844
                }
845
            }
846

    
847
            return dt;
848
        }
849

    
850
        private DataTable GetTopologyRule()
851
        {
852
            DataTable dt = DB.SelectTopologyRule();
853

    
854
            return dt;
855
        }
856

    
857
        private bool IsConnected(Item item1, Item item2)
858
        {
859
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
860
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
861
                return true;
862
            else
863
                return false;
864
        }
865

    
866
        private void SaveNozzleAndEquipment()
867
        {
868
            List<Item> nozzles = new List<Item>();
869
            List<Equipment> equipments = new List<Equipment>();
870
            foreach (Document document in Documents)
871
            {
872
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
873
                equipments.AddRange(document.Equipments);
874
            }
875
                
876

    
877
            DataTable nozzleDT = new DataTable();
878
            nozzleDT.Columns.Add("OID", typeof(string));
879
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
880
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
881
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
882
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
883
            nozzleDT.Columns.Add("FLUID", typeof(string));
884
            nozzleDT.Columns.Add("NPD", typeof(string));
885
            nozzleDT.Columns.Add("PMC", typeof(string));
886
            nozzleDT.Columns.Add("ROTATION", typeof(string));
887
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
888

    
889
            foreach (Item item in nozzles)
890
            {
891
                DataRow row = nozzleDT.NewRow();
892
                row["OID"] = item.UID;
893

    
894
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
895
                if (relation != null)
896
                {
897
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
898
                    equipment.Nozzles.Add(item);
899
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
900
                    row["Equipment_OID"] = equipment.UID; 
901
                    item.Equipment = equipment;
902
                }
903
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
904
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
905
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
906
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
907
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
908
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
909
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
910
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
911

    
912
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
913
                if (angle >= Math.PI * 2)
914
                    angle = angle - Math.PI * 2;
915
                row["ROTATION"] = angle.ToString();
916

    
917
                if (item.Topology.Items.First().Equals(item))
918
                    row["FlowDirection"] = "Outlet";
919
                else if (item.Topology.Items.Last().Equals(item))
920
                    row["FlowDirection"] = "Inlet";
921
                else
922
                    row["FlowDirection"] = string.Empty;
923

    
924
                nozzleDT.Rows.Add(row);
925
            }
926

    
927
            DataTable equipDT = new DataTable();
928
            equipDT.Columns.Add("OID", typeof(string));
929
            equipDT.Columns.Add("ITEMTAG", typeof(string));
930
            equipDT.Columns.Add("XCOORDS", typeof(string));
931
            equipDT.Columns.Add("YCOORDS", typeof(string));
932

    
933
            foreach (Equipment equipment in equipments)
934
            {
935
                DataRow row = equipDT.NewRow();
936
                row["OID"] = equipment.UID;
937
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
938
                {
939
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
940
                    if (attribute != null)
941
                        equipment.ItemTag = attribute.Value;
942
                }
943
                else
944
                    equipment.ItemTag = equipment.Name;
945

    
946
                row["ITEMTAG"] = equipment.ItemTag;
947
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
948
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
949

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

    
953
                equipDT.Rows.Add(row);
954
            }
955

    
956
            Equipment = equipDT;
957
            Nozzle = nozzleDT;
958
        }
959

    
960
        private void SavePSNData()
961
        {
962
            try
963
            {
964
                DataTable pathItemsDT = new DataTable();
965
                pathItemsDT.Columns.Add("OID", typeof(string));
966
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
967
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
968
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
969
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
970
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
971
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
972
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));                
973
                pathItemsDT.Columns.Add("Class", typeof(string));
974
                pathItemsDT.Columns.Add("SubClass", typeof(string));
975
                pathItemsDT.Columns.Add("TYPE", typeof(string));
976
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
977
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
978
                pathItemsDT.Columns.Add("NPD", typeof(string));
979
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
980
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
981
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
982

    
983
                DataTable sequenceDataDT = new DataTable();
984
                sequenceDataDT.Columns.Add("OID", typeof(string));
985
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
986
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
987
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
988

    
989
                DataTable pipeSystemNetworkDT = new DataTable();
990
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
991
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
992
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
993
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
994
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
995
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
996
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
997
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
998
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
999
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
1000
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
1001
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
1002
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
1003
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
1004

    
1005
                DataTable topologySetDT = new DataTable();
1006
                topologySetDT.Columns.Add("OID", typeof(string));
1007
                topologySetDT.Columns.Add("Type", typeof(string));
1008
                topologySetDT.Columns.Add("SubType", typeof(string));
1009
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
1010
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
1011
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
1012
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
1013

    
1014
                DataTable pipelineDT = new DataTable();
1015
                pipelineDT.Columns.Add("OID", typeof(string));
1016
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
1017
                pipelineDT.Columns.Add("FLUID", typeof(string));
1018
                pipelineDT.Columns.Add("PMC", typeof(string));
1019
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
1020
                pipelineDT.Columns.Add("INSULATION", typeof(string));
1021
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
1022
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
1023
                pipelineDT.Columns.Add("Unit", typeof(string));
1024

    
1025
                // Set Vent/Drain Info
1026
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1027
                DataTable dt = DB.SelectVentDrainSetting();
1028
                foreach (DataRow row in dt.Rows)
1029
                {
1030
                    string groupID = row["GROUP_ID"].ToString();
1031
                    string desc = row["DESCRIPTION"].ToString();
1032
                    int index = Convert.ToInt32(row["INDEX"]);
1033
                    string name = row["NAME"].ToString();
1034

    
1035
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1036
                    if (ventDrainInfo == null)
1037
                    {
1038
                        ventDrainInfo = new VentDrainInfo(groupID);
1039
                        ventDrainInfo.Description = desc;
1040
                        VentDrainInfos.Add(ventDrainInfo);
1041
                    }
1042

    
1043
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1044
                    {
1045
                        Index = index,
1046
                        Name = name
1047
                    });
1048
                }
1049
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1050
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
1051

    
1052
                #region Keyword Info
1053
                KeywordInfo KeywordInfos = new KeywordInfo();
1054
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1055
                foreach (DataRow row in dtKeyword.Rows)
1056
                {
1057
                    int index = Convert.ToInt32(row["INDEX"]);
1058
                    string name = row["NAME"].ToString();
1059
                    string keyword = row["KEYWORD"].ToString();
1060

    
1061
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1062
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1063
                    {
1064
                        Index = index,
1065
                        Name = name,
1066
                        Keyword = keyword
1067
                    });
1068
                }               
1069
                #endregion
1070

    
1071
                // key = 미입력 branch
1072
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1073
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1074

    
1075
                foreach (PSNItem PSNItem in PSNItems)
1076
                {
1077
                    try
1078
                    {
1079
                        int psnOrder = 0;
1080
                        int index = 0;
1081
                        bool bPSNStart = true;
1082
                        string sPSNData = string.Empty;
1083
                        bool bVentDrain = false;
1084
                        List<Group> Groups = PSNItem.Groups;
1085
                        //VentDrain 검사
1086
                        if (PSNItem.Groups.Count.Equals(1))
1087
                        {
1088
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();                           
1089
                            for (int g = 0; g < Groups.Count; g++)  
1090
                            {
1091
                                Group group = Groups[g];
1092
                                for (int i = 0; i < group.Items.Count; i++)
1093
                                {
1094
                                    Item item = group.Items[i];
1095
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1096
                                    {
1097
                                        if (endInfos.Contains(ventDrainInfo))
1098
                                            continue;
1099

    
1100
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1101
                                        {
1102
                                            endInfos.Add(ventDrainInfo);
1103
                                            continue;
1104
                                        }
1105

    
1106
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1107
                                        {
1108
                                            bVentDrain = true;
1109
                                            break;
1110
                                        }
1111
                                    }
1112

    
1113
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1114
                                        break;
1115
                                }
1116

    
1117
                                if (!bVentDrain)
1118
                                {
1119
                                    endInfos = new List<VentDrainInfo>();
1120
                                    for (int i = 0; i < group.Items.Count; i++)
1121
                                    {
1122
                                        Item item = group.Items[group.Items.Count - i - 1];
1123
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1124
                                        {
1125
                                            if (endInfos.Contains(ventDrainInfo))
1126
                                                continue;
1127

    
1128
                                            if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1129
                                            {
1130
                                                endInfos.Add(ventDrainInfo);
1131
                                                continue;
1132
                                            }
1133

    
1134
                                            if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1135
                                            {
1136
                                                bVentDrain = true;
1137
                                                break;
1138
                                            }
1139
                                        }
1140

    
1141
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1142
                                            break;
1143
                                    }
1144
                                }
1145
                            }
1146
                        }
1147
                                                                       
1148
                        try
1149
                        {                            
1150
                            //PSN, PathItems, SequenceData 관련
1151
                            foreach (Group group in PSNItem.Groups)
1152
                            {                                
1153
                                foreach (Item item in group.Items)
1154
                                {
1155
                                    string PathitemUID = string.Empty;
1156
                                    if (item.BranchItems.Count == 0)
1157
                                    {
1158
                                        PathitemUID = item.UID;
1159
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType);
1160
                                        CreateSequenceDataDataRow(PathitemUID);
1161
                                        index++;
1162
                                    }
1163
                                    else
1164
                                    {
1165
                                        PathitemUID = item.UID + "_L1";
1166
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType);
1167
                                        CreateSequenceDataDataRow(PathitemUID);
1168
                                        index++;
1169
                                        for (int i = 0; i < item.BranchItems.Count; i++)
1170
                                        {
1171
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1172
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1173
                                            index++;
1174
                                                
1175
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1176
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1177
                                            index++;
1178

    
1179
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1180
                                                startBranchDic.Add(item.BranchItems[i], item);
1181
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1182
                                                endBranchDic.Add(item.BranchItems[i], item);
1183
                                        }
1184
                                    }
1185
                                    
1186
                                    if (bPSNStart)
1187
                                    {
1188
                                        
1189
                                        CreatePipeSystemNetworkDataRow();
1190
                                        sPSNData = item.TopologyData;
1191
                                        psnOrder++;
1192
                                        bPSNStart = false;
1193
                                    }
1194
                                    else
1195
                                    {
1196
                                        if (item.TopologyData != sPSNData)
1197
                                        {
1198
                                            CreatePipeSystemNetworkDataRow();
1199
                                            sPSNData = item.TopologyData;
1200
                                            psnOrder++;
1201
                                        }
1202
                                    }
1203
                                    
1204
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string branchTopologyName = "", Item branchItem = null)
1205
                                    {
1206
                                        DataRow newRow = pathItemsDT.NewRow();
1207

    
1208
                                        if (itemType == "Nozzles")
1209
                                        {
1210
                                            newRow["Equipment_OID"] = item.Equipment.UID;
1211
                                        }
1212

    
1213
                                        newRow["OID"] = itemOID;
1214
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1215
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
1216
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
1217
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
1218
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
1219
                                        newRow["ITEMTAG"] = GetItemTag(item);
1220
                                        newRow["Class"] = GetClass(item, itemOID);
1221
                                        string subClass = GetSubClass(item, itemOID);                                           
1222
                                        newRow["SubClass"] = subClass;
1223

    
1224
                                        if (item.ItemType == ItemType.Symbol)
1225
                                            newRow["TYPE"] = item.ID2DBName;
1226
                                        else if (item.ItemType == ItemType.Line)
1227
                                            newRow["TYPE"] = item.ID2DBType;
1228
                                        newRow["PIDNAME"] = group.Document.DrawingName;
1229

    
1230
                                        // NPD
1231
                                        if (item.LineNumber != null)
1232
                                        {
1233
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1234
                                            if (attribute != null)
1235
                                                newRow["NPD"] = attribute.Value;
1236
                                        }
1237
                                        else
1238
                                            newRow["NPD"] = null;
1239

    
1240

    
1241
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1242
                                        if (branchItem == null)
1243
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1244
                                        else
1245
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
1246

    
1247
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
1248

    
1249
                                        pathItemsDT.Rows.Add(newRow);
1250
                                    }                                   
1251
                                    void CreateSequenceDataDataRow(string itemOID)
1252
                                    {
1253
                                        DataRow newRow = sequenceDataDT.NewRow();
1254
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1255
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
1256
                                        newRow["PathItem_OID"] = itemOID;
1257
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1258

    
1259
                                        sequenceDataDT.Rows.Add(newRow);
1260
                                    }
1261
                                    void CreatePipeSystemNetworkDataRow()
1262
                                    {                                       
1263
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1264
                                        if (lineNumber != null)
1265
                                        {
1266
                                            List<Attribute> att = lineNumber.Attributes;
1267
                                            if (att != null)
1268
                                            {
1269
                                                List<string> oid = new List<string>();
1270
                                                string FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
1271
                                                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;
1272
                                                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;
1273
                                                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;
1274
                                                //InsulationPurpose
1275
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
1276
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
1277

    
1278
                                                string PipeSystem_OID = string.Join("-", oid);
1279

    
1280
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
1281
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
1282

    
1283
                                                string OID = string.Join("-", oid);
1284

    
1285
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
1286
                                                {
1287
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
1288
                                                    newPipelineRow["OID"] = OID;
1289
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
1290
                                                    newPipelineRow["FLUID"] = FluidCode;
1291
                                                    newPipelineRow["PMC"] = PMC;
1292
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
1293
                                                    newPipelineRow["INSULATION"] = INSULATION;
1294
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
1295
                                                    newPipelineRow["TO_DATA"] = string.Empty;
1296
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
1297
                                                    pipelineDT.Rows.Add(newPipelineRow);
1298
                                                }
1299
                                            }
1300
                                        }
1301

    
1302
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
1303
                                        newRow["OID"] = PSNItem.PSN_OID();
1304
                                            
1305
                                        newRow["OrderNumber"] = psnOrder;
1306
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
1307
                                        PSNItem.KeywordInfos = KeywordInfos;
1308
                                        PSNItem.Nozzle = Nozzle;
1309
                                        
1310
                                        string FromType = string.Empty;
1311
                                        Item From_item = new Item();
1312
                                       
1313
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
1314
                                        string status = string.Empty;
1315
                                        if (psnOrder == 0)
1316
                                        {
1317
                                            status = PSNItem.Status;
1318
                                        }
1319

    
1320
                                        if (PSNItem.IsKeyword)
1321
                                        {
1322
                                            PSNItem.StartType = PSNType.Equipment;
1323
                                        }
1324
                                        string ToType = string.Empty;
1325
                                        Item To_item = new Item();
1326
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
1327
                                        if (PSNItem.IsKeyword)
1328
                                        {
1329
                                            PSNItem.EndType = PSNType.Equipment;
1330
                                        }
1331
                                     
1332
                                        if (group.Items.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
1333
                                        {
1334
                                            status += PSNItem.Status;
1335
                                        }
1336

    
1337
                                        newRow["FROM_DATA"] = FROM_DATA;
1338
                                        newRow["TO_DATA"] = TO_DATA;                                     
1339
                                        newRow["Type"] = PSNItem.GetPSNType();
1340

    
1341
                                        if (psnOrder > 0)
1342
                                        {
1343
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = 0", PSNItem.PSN_OID())).FirstOrDefault();
1344
                                            if(dr != null)
1345
                                            {
1346
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
1347
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
1348
                                                newRow["Type"] = dr.Field<string>("Type");
1349
                                            }
1350
                                        }                                                                           
1351

    
1352
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
1353
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
1354
                                        {
1355
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
1356
                                            int cnt = matches.Count;
1357
                                            if (cnt > 1)
1358
                                                status.Replace(", Missing LineNumber_1", string.Empty);
1359
                                        }
1360
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1361
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1362

    
1363
                                      
1364
                                        newRow["IsValid"] = PSNItem.IsValid;
1365
                                        newRow["Status"] = status;
1366
                                        newRow["PBS"] = PSNItem.GetPBSData();
1367

    
1368
                                        List<string> drawingNames = new List<string>();
1369
                                        foreach (Group _group in PSNItem.Groups)
1370
                                        {
1371
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
1372
                                            {
1373
                                                if (drawingNames.Count == 0)
1374
                                                    newRow["Drawings"] = _group.Document.DrawingName;
1375
                                                else
1376
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
1377
                                                drawingNames.Add(_group.Document.DrawingName);
1378
                                            }
1379
                                        }
1380

    
1381
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
1382
                                        if (bVentDrain)
1383
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
1384
                                        else
1385
                                            newRow["IncludingVirtualData"] = "No";
1386
                                        //    return;
1387
                                        //newRow["IncludingVirtualData"] = "No";
1388
                                        newRow["PSNAccuracy"] = "100";
1389
                                        pipeSystemNetworkDT.Rows.Add(newRow);
1390
                                    }
1391
                                }
1392
                                
1393
                            }
1394
                            DataRow createTeeRow(DataRow itemRow)
1395
                            {
1396
                                DataRow newRow = pathItemsDT.NewRow();
1397
                                newRow["OID"] = Guid.NewGuid().ToString();
1398
                                newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1399
                                newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1400
                                newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1401
                                newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
1402
                                newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
1403
                                newRow["ITEMTAG"] = itemRow["ITEMTAG"];
1404
                                newRow["DESCRIPTION"] = "";
1405
                                newRow["Class"] = "Branch";
1406
                                newRow["SubClass"] = "Tee";
1407
                                newRow["TYPE"] = itemRow["TYPE"];
1408
                                newRow["PIDNAME"] = itemRow["PIDNAME"];
1409
                                newRow["NPD"] = itemRow["NPD"];
1410
                                newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1411
                                newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1412
                                newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1413

    
1414
                                return newRow;
1415
                            }
1416
                            
1417
                        }
1418
                        catch (Exception ex)
1419
                        {
1420
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1421
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1422
                        }
1423

    
1424
                        //TopologySet 관련
1425
                        foreach (Topology topology in PSNItem.Topologies)
1426
                        {
1427
                            DataRow newRow = topologySetDT.NewRow();
1428
                            newRow["OID"] = topology.FullName;
1429
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1430
                            if (bVentDrain)
1431
                                newRow["SubType"] = "Vent_Drain";
1432
                            else
1433
                                newRow["SubType"] = null;
1434
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1435
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1436
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
1437
                            newRow["TailItemSPID"] = topology.Items.First().UID;
1438
                            topologySetDT.Rows.Add(newRow);
1439
                        }
1440
                        
1441
                    }
1442
                    catch(Exception ee)
1443
                    {
1444

    
1445
                    }
1446
                }
1447

    
1448

    
1449
                foreach (var item in startBranchDic)
1450
                {
1451
                    string uid = item.Key.UID;
1452
                    string topologyName = item.Value.Topology.FullName;
1453
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1454
                   
1455
                    if (rows.Length == 1)
1456
                    {
1457
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1458
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1459
                    }
1460
                    else if (rows.Length > 1)
1461
                    {
1462
                        DataRow targetRow = null;
1463
                        int index = int.MaxValue;
1464
                        foreach (DataRow row in rows)
1465
                        {
1466
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1467
                            if (split.StartsWith("L"))
1468
                            {
1469
                                int num = Convert.ToInt32(split.Remove(0, 1));
1470
                                if (index > num)
1471
                                {
1472
                                    index = num;
1473
                                    targetRow = row;
1474
                                }
1475
                            }
1476
                        }
1477

    
1478
                        if (targetRow != null)
1479
                        {
1480
                            targetRow["BranchTopologySet_OID"] = topologyName;
1481
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1482
                        }
1483
                    }
1484
                }
1485

    
1486
                foreach (var item in endBranchDic)
1487
                {
1488
                    string uid = item.Key.UID;
1489
                    string topologyName = item.Value.Topology.FullName;
1490
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1491
                    if (rows.Length == 1)
1492
                    {
1493
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1494
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1495
                    }
1496
                    else if (rows.Length > 1)
1497
                    {
1498
                        DataRow targetRow = null;
1499
                        int index = int.MinValue;
1500
                        foreach (DataRow row in rows)
1501
                        {
1502
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1503
                            if (split.StartsWith("L"))
1504
                            {
1505
                                int num = Convert.ToInt32(split.Remove(0, 1));
1506
                                if (index < num)
1507
                                {
1508
                                    index = num;
1509
                                    targetRow = row;
1510
                                }
1511
                            }
1512
                        }
1513

    
1514
                        if (targetRow != null)
1515
                        {
1516
                            targetRow["BranchTopologySet_OID"] = topologyName;
1517
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1518
                        }
1519
                    }
1520
                }
1521

    
1522
                PathItems = pathItemsDT;
1523
                SequenceData = sequenceDataDT;
1524
                PipeSystemNetwork = pipeSystemNetworkDT;
1525
                TopologySet = topologySetDT;
1526
                PipeLine = pipelineDT;
1527
            }
1528
            catch (Exception ex)
1529
            {
1530
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1531
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1532
            }
1533
        }
1534

    
1535
        private double AccuracyCalculation(List<double> lstAcc, double acc)
1536
        {
1537
            foreach(double lacc in lstAcc)
1538
            {
1539
                acc *= lacc;
1540
            }
1541
            return acc;
1542
        }
1543

    
1544
        private void UpdateSubType()
1545
        {
1546
            try
1547
            {
1548
                foreach (PSNItem PSNItem in PSNItems)
1549
                {
1550
                    if (PSNItem.IsBypass)
1551
                    {
1552
                        foreach (Topology topology in PSNItem.Topologies)
1553
                        {
1554
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1555
                            if (rows.Length.Equals(1))
1556
                                rows.First()["SubType"] = "Bypass";
1557
                        }
1558
                    }
1559

    
1560
                    if (PSNItem.StartType == PSNType.Header)
1561
                    {
1562
                        Topology topology = PSNItem.Topologies.First();
1563
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1564
                        if (rows.Length.Equals(1))
1565
                            rows.First()["SubType"] = "Header";
1566
                    }
1567
                    else if (PSNItem.EndType == PSNType.Header)
1568
                    {
1569
                        Topology topology = PSNItem.Topologies.Last();
1570
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1571
                        if (rows.Length.Equals(1))
1572
                            rows.First()["SubType"] = "Header";
1573
                    }
1574
                }
1575

    
1576

    
1577
                foreach (Topology topology in Topologies)
1578
                {
1579
                    try
1580
                    {
1581
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1582
                        
1583
                        if(rows.Count() > 0)
1584
                        {
1585
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
1586
                            {
1587
                                if (topology.Items == null)
1588
                                    continue;
1589

    
1590
                                Item firstItem = topology.Items.First();
1591
                                Item lastItem = topology.Items.Last();
1592

    
1593
                                List<Relation> relations = new List<Relation>();
1594

    
1595
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1596
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1597

    
1598
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1599
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1600

    
1601
                                if (relations.Count > 0)
1602
                                    rows.First()["SubType"] = "OtherSystem";
1603
                            }
1604
                        }
1605
                    }
1606
                    catch (Exception ex)
1607
                    {
1608
                       
1609
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1610
                    }
1611
                }
1612

    
1613
                    foreach (DataRow row in TopologySet.Rows)
1614
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
1615
                        row["SubType"] = "Normal";
1616
            }
1617
            catch (Exception ex)
1618
            {
1619
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1620
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1621
            }
1622
        }
1623

    
1624
        private bool IsBypass(PSNItem PSNItem)
1625
        {
1626
            bool bResult = false;
1627

    
1628
            if (PSNItem.GetPSNType() == "B2B")
1629
            {
1630
                Group firstGroup = PSNItem.Groups.First();
1631
                Group lastGroup = PSNItem.Groups.Last();
1632
                Item firstItem = firstGroup.Items.First();
1633
                Item lastItem = lastGroup.Items.Last();
1634

    
1635
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
1636
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
1637

    
1638
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
1639
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
1640
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
1641
                    bResult = true;
1642
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
1643
                    bResult = true;
1644
            }
1645

    
1646
            Item GetConnectedItemByPSN(Item item)
1647
            {
1648
                Item result = null;
1649

    
1650
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
1651
                if (relation != null)
1652
                    result = relation.Item;
1653

    
1654

    
1655
                return result;
1656
            }
1657

    
1658
            return bResult;
1659
        }
1660

    
1661
        private void DeleteVentDrain()
1662
        {
1663
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
1664
            
1665
            foreach (DataRow dataRow in ventdrainRows)
1666
            {
1667
                dataRow.Delete();             
1668
            }       
1669
        }
1670

    
1671
        private void UpdateAccuracy()
1672
        {
1673
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
1674
            List<double> lstAcc = null;
1675
            string Status = string.Empty;
1676

    
1677
            foreach (DataRow dataRow in statusRows)
1678
            {
1679
                lstAcc = new List<double>();
1680
                Status = dataRow.Field<string>("Status");
1681
                if (!string.IsNullOrEmpty(Status))
1682
                {
1683
                    string[] arrStatus = Status.Split(',');
1684
                    foreach(string arrstr in arrStatus)
1685
                    {
1686
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
1687
                            lstAcc.Add(0.75);
1688

    
1689
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
1690
                            lstAcc.Add(0.7);
1691

    
1692
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
1693
                            lstAcc.Add(0.5);
1694

    
1695
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
1696
                            lstAcc.Add(0.65);
1697

    
1698
                        if (arrstr.Contains(Rule5)) //Line Disconnected
1699
                            lstAcc.Add(0.6);
1700
                    }
1701
                }
1702

    
1703
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
1704
                if (PSNAccuracy == "100")
1705
                    PSNAccuracy = "1";
1706

    
1707
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
1708
                //if (PSNAccuracy != "100")
1709
                //{
1710
                //    //dataRow["IncludingVirtualData"] = "No";
1711
                    dataRow["PSNAccuracy"] = PSNAccuracy;
1712
                //}
1713
            }
1714
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
1715
            foreach (DataRow dr in dt.Rows)
1716
            {
1717
                string oid = dr.Field<string>("OID");
1718
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
1719
                double totalDdr = 0;
1720
                foreach (DataRow ddr in select)
1721
                {
1722
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
1723
                    if (acc == 100) acc = 1;
1724
                    if (totalDdr == 0) totalDdr = acc;
1725
                    else totalDdr *= acc;
1726
                }
1727

    
1728
                totalDdr *= 100;
1729

    
1730
                if(totalDdr != 100)
1731
                {
1732
                    foreach (DataRow ddr in select)
1733
                    {
1734
                        ddr["IncludingVirtualData"] = "Yes";
1735
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
1736
                    }
1737
                }
1738
                else
1739
                {
1740
                    foreach (DataRow ddr in select)
1741
                    {
1742
                        ddr["IncludingVirtualData"] = "No";
1743
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
1744
                    }
1745
                }
1746
            }
1747

    
1748
        }
1749

    
1750
        private void UpdateKeywordForPSN()
1751
        {
1752
            #region Keyword Info
1753
            KeywordInfo KeywordInfos = new KeywordInfo();
1754
            DataTable dtKeyword = DB.SelectKeywordsSetting();
1755
            foreach (DataRow row in dtKeyword.Rows)
1756
            {
1757
                int index = Convert.ToInt32(row["INDEX"]);
1758
                string name = row["NAME"].ToString();
1759
                string keyword = row["KEYWORD"].ToString();
1760

    
1761
                //KeywordInfo keywordInfo = new KeywordInfo();   
1762
                KeywordInfos.KeywordItems.Add(new KeywordItem()
1763
                {
1764
                    Index = index,
1765
                    Name = name,
1766
                    Keyword = keyword
1767
                });
1768
            }
1769
            #endregion
1770

    
1771
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
1772
            foreach (DataRow dataRow in endofHeaderRows)
1773
            {
1774
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
1775

    
1776
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
1777
                {
1778
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1779
                    DataRow dr = pathItemRows.First();
1780
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
1781
                    dr["TYPE"] = "End";
1782
                    dr["ITEMTAG"] = "ENDOFHEADER";
1783
                    dr["DESCRIPTION"] = "ENDOFHEADER";
1784
                }
1785

    
1786
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
1787
                {
1788
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1789
                    DataRow dr = pathItemRows.Last();
1790
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
1791
                    dr["TYPE"] = "End";
1792
                    dr["ITEMTAG"] = "ENDOFHEADER";
1793
                    dr["DESCRIPTION"] = "ENDOFHEADER";
1794
                }
1795
            }
1796

    
1797
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
1798
            {
1799
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
1800
                foreach (DataRow dataRow in keywordRows)
1801
                {                    
1802
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());                     
1803

    
1804
                    if(dataRow.Field<string>("From_Data") == keyitem.Keyword)
1805
                    {                   
1806
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1807
                             
1808
                        //
1809
                        //if(.)
1810
                        if(PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
1811
                        {
1812
                            DataRow dr = pathItemRows.First();
1813
                            //dr["CLASS"] = ""; //Type
1814
                            dr["TYPE"] = "End";
1815
                            dr["ITEMTAG"] = keyitem.Keyword;
1816
                            dr["DESCRIPTION"] = keyitem.Keyword;
1817
                        }
1818
                           
1819
                    }
1820

    
1821
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
1822
                    {
1823
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1824

    
1825
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
1826
                        {
1827
                            DataRow dr = pathItemRows.Last();
1828
                            //dr["CLASS"] = ""; //Type
1829
                            dr["TYPE"] = "End";
1830
                            dr["ITEMTAG"] = keyitem.Keyword;
1831
                            dr["DESCRIPTION"] = keyitem.Keyword;
1832
                            //dr.Field<string>("Type")
1833
                        }
1834

    
1835
                    }                   
1836
                }
1837
            }          
1838
        }
1839

    
1840
        private void UpdateErrorForPSN()
1841
        {
1842
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
1843
            foreach (DataRow dataRow in errorRows)
1844
            {
1845
                try
1846
                {
1847
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
1848
                    bool change = false;
1849
                    bool bCheck = false;
1850
                    int bCount = 0;
1851
                    if (!PSNItem.EnableType(PSNItem.StartType))
1852
                    {
1853
                        change = true;
1854
                        bCheck = change;
1855
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));                       
1856
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
1857
                        
1858
                        Item item = PSNItem.Groups.First().Items.First();
1859
                        try
1860
                        {
1861
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1862
                           
1863
                            tieInPointIndex++;
1864

    
1865

    
1866
                            if (item.ItemType == ItemType.Line)
1867
                            {
1868
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
1869
                                bCount = 2;
1870

    
1871
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1872
                                {
1873
                                    loopRow["FROM_DATA"] = FROM_DATA;
1874
                                    if (loopRow.Field<string>("OrderNumber") == "0")
1875
                                    {
1876
                                        string status = loopRow.Field<string>("Status");
1877
                                        if (string.IsNullOrEmpty(status))
1878
                                            status = "Line Disconnected";
1879
                                        else if (!status.Contains("Line Disconnected"))
1880
                                            status += ", Line Disconnected";
1881
                                        loopRow["Status"] = status;
1882
                                    }
1883
                                }
1884
                            }
1885
                            else
1886
                            {
1887
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
1888
                                
1889
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
1890
                                bCount = 3;
1891
                            }
1892

    
1893
                            PSNItem.StartType = PSNType.Equipment;
1894
                        }
1895
                        catch (Exception ex)
1896
                        {
1897
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1898
                            return;
1899
                        }
1900
                    }
1901

    
1902
                    if (!PSNItem.EnableType(PSNItem.EndType))
1903
                    {
1904
                        change = true;
1905
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1906
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
1907

    
1908
                        Item item = PSNItem.Groups.Last().Items.Last();
1909
                        try
1910
                        {
1911
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1912

    
1913
                            if (item.ItemType == ItemType.Line)
1914
                            {
1915
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1916
                                {
1917
                                    loopRow["TO_DATA"] = TO_DATA;
1918
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
1919
                                    {
1920
                                        string status = loopRow.Field<string>("Status");
1921
                                        if (string.IsNullOrEmpty(status))
1922
                                            status = "Line Disconnected";
1923
                                        else if (!status.Contains("Line Disconnected"))
1924
                                            status += ", Line Disconnected";
1925
                                        loopRow["Status"] = status;
1926
                                    }
1927
                                }
1928
                            }
1929

    
1930
                            tieInPointIndex++;
1931
                            
1932
                            if(!bCheck)
1933
                            {
1934
                                if (item.ItemType == ItemType.Line)
1935
                                {
1936
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
1937
                                }
1938
                                else
1939
                                {
1940
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
1941
                                    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);
1942
                                }
1943
                            }
1944
                            else
1945
                            {
1946
                                if (item.ItemType == ItemType.Line)
1947
                                {
1948
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
1949
                                }
1950
                                else
1951
                                {
1952
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
1953
                                    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);
1954
                                }
1955
                            }
1956
                            
1957

    
1958
                            PSNItem.EndType = PSNType.Equipment;
1959
                        }
1960
                        catch(Exception ex)
1961
                        {
1962
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1963
                            return;
1964
                        }
1965
                    }
1966

    
1967
                    dataRow["Type"] = PSNItem.GetPSNType();
1968
                    if (change)
1969
                    {
1970
                        int rowIndex = 0;
1971
                        for (int i = 0; i < PathItems.Rows.Count; i++)
1972
                        {
1973
                            DataRow row = PathItems.Rows[i];
1974
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
1975
                                continue;
1976
                            string sequenceData = row["SequenceData_OID"].ToString();
1977
                            string[] split = sequenceData.Split(new char[] { '_' });
1978

    
1979
                            StringBuilder sb = new StringBuilder();
1980
                            for (int j = 0; j < split.Length - 1; j++)
1981
                                sb.Append(split[j] + "_");
1982
                            sb.Append(rowIndex++);
1983
                            row["SequenceData_OID"] = sb.ToString();
1984

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

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

    
1990
                            if (seqItemRows == null)
1991
                            {
1992
                                DataRow newRow = SequenceData.NewRow();    
1993
                                newRow["OID"] = sb.ToString();
1994
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
1995
                                newRow["PathItem_OID"] = row["OID"];
1996
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
1997
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
1998
                            }
1999
                            else
2000
                            {
2001
                                seqItemRows["OID"] = sb.ToString();
2002
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2003
                                seqItemRows["PathItem_OID"] = row["OID"];
2004
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2005
                            }                         
2006
                        }                        
2007
                    }
2008

    
2009
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
2010
                    {
2011
                        DataRow newRow = PathItems.NewRow();
2012
                        newRow["OID"] = Guid.NewGuid().ToString();
2013
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2014
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2015
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2016
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];                        
2017
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
2018
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
2019
                        newRow["DESCRIPTION"] = DATA; 
2020
                        newRow["Class"] = "End of line terminator";
2021
                        newRow["SubClass"] = "End of line terminator";
2022
                        newRow["TYPE"] = "End";
2023
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2024
                        newRow["NPD"] = itemRow["NPD"];
2025
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2026
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2027
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];                       
2028

    
2029
                        return newRow;
2030
                    }
2031

    
2032
                    DataRow createLineRow(DataRow itemRow)
2033
                    {
2034
                        DataRow newRow = PathItems.NewRow();
2035
                        newRow["OID"] = Guid.NewGuid().ToString();
2036
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2037
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2038
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2039
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2040
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
2041
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2042
                        newRow["Class"] = itemRow["Class"];
2043
                        newRow["SubClass"] = itemRow["SubClass"];
2044
                        newRow["TYPE"] = itemRow["TYPE"];
2045
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2046
                        newRow["NPD"] = itemRow["NPD"];
2047
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2048
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2049
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2050

    
2051
                        return newRow;
2052
                    }
2053
                }
2054
                catch(Exception ex)
2055
                {
2056

    
2057
                }
2058
            }
2059
        }
2060

    
2061
        private void InsertTeePSN()
2062
        {
2063
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
2064
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
2065
            bool change = false;
2066
            foreach (DataRow dataRow in branchRows)
2067
            {
2068
                try
2069
                {            
2070
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2071
                    change = false;
2072

    
2073
                    if (PSNItem.StartType == PSNType.Branch)
2074
                    {
2075
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2076
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2077
                        Item Teeitem = PSNItem.Groups.First().Items.First();
2078
                        try
2079
                        {
2080
                            if (Teeitem.ItemType == ItemType.Line)
2081
                            {
2082
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
2083
                                {   
2084
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
2085
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
2086
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2087
                                    change = true;
2088
                                }
2089

    
2090
                            }
2091
                        }
2092
                        catch (Exception ex)
2093
                        {
2094
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2095
                            return;
2096
                        }
2097
                    }
2098

    
2099
                    if (PSNItem.EndType == PSNType.Branch)
2100
                    {
2101
                        //change = true;
2102
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2103
                                                
2104
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
2105

    
2106
                        DataRow dr = pathItemRows.Last();
2107
                        if (change)
2108
                            dr = pathItemRows[pathItemRows.Count() - 2];
2109

    
2110
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2111

    
2112
                        try
2113
                        {
2114
                            if (Teeitem.ItemType == ItemType.Line)
2115
                            {
2116
                                if (dr.Field<string>("SubClass") != "Tee")
2117
                                {
2118
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
2119
                                    change = true;
2120
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
2121
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2122
                                }
2123

    
2124
                            }
2125
                        }
2126
                        catch (Exception ex)
2127
                        {
2128
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2129
                            return;
2130
                        }
2131
                    }
2132

    
2133
                    if (change)
2134
                    {
2135
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2136
                        int rowIndex = 0;
2137
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2138
                        {
2139
                            DataRow row = PathItems.Rows[i];
2140
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
2141
                                continue;
2142
                            string sequenceData = row["SequenceData_OID"].ToString();
2143
                            string[] split = sequenceData.Split(new char[] { '_' });
2144

    
2145
                            StringBuilder sb = new StringBuilder();
2146
                            for (int j = 0; j < split.Length - 1; j++)
2147
                                sb.Append(split[j] + "_");
2148
                            sb.Append(rowIndex++);
2149
                            row["SequenceData_OID"] = sb.ToString();
2150

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

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

    
2156
                            if (seqItemRows == null)
2157
                            {
2158
                                DataRow newRow = SequenceData.NewRow();
2159
                                newRow["OID"] = sb.ToString();
2160
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2161
                                newRow["PathItem_OID"] = row["OID"];
2162
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2163
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2164
                            }
2165
                            else
2166
                            {
2167
                                seqItemRows["OID"] = sb.ToString();
2168
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2169
                                seqItemRows["PathItem_OID"] = row["OID"];
2170
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2171
                            }
2172
                        }
2173
                    }
2174
                    
2175
                    DataRow createTeeRow(DataRow itemRow)
2176
                    {
2177
                        DataRow newRow = PathItems.NewRow();
2178
                        newRow["OID"] = Guid.NewGuid().ToString();
2179
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2180
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2181
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2182
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2183
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
2184
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2185
                        newRow["DESCRIPTION"] = "";
2186
                        newRow["Class"] = "Branch";
2187
                        newRow["SubClass"] = "Tee";
2188
                        newRow["TYPE"] = itemRow["TYPE"];
2189
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2190
                        newRow["NPD"] = itemRow["NPD"];
2191
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2192
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2193
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2194

    
2195
                        return newRow;
2196
                    }
2197
                }
2198
                catch (Exception ex)
2199
                {
2200

    
2201
                }
2202
            }
2203
        }
2204
    }
2205

    
2206
    public class PSNItem
2207
    {
2208
        public PSNItem(int count, int Revision)
2209
        {
2210
            Groups = new List<Group>();
2211
            Topologies = new List<Topology>();
2212

    
2213
            Index = count + 1;
2214
            this.Revision = Revision;
2215
        }
2216

    
2217
        private int Revision;
2218
        public string UID { get; set; }
2219
        public List<Group> Groups { get; set; }
2220
        public List<Topology> Topologies { get; set; }
2221
        public PSNType StartType { get; set; }
2222
        public PSNType EndType { get; set; }
2223
        public int Index { get; set; }
2224
        public string IsValid { get; set; }
2225
        public bool IsKeyword { get; set; }
2226
        public string Status { get; set; }
2227
        public string IncludingVirtualData { get; set; }
2228
        public string PSNAccuracy { get; set; }
2229
        public KeywordInfo KeywordInfos = new KeywordInfo();
2230
        public DataTable Nozzle = new DataTable();
2231

    
2232
        public string PSN_OID()
2233
        {
2234
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
2235
        }
2236
        public string GetPSNType()
2237
        {
2238
            string result = string.Empty;
2239

    
2240
            if (EnableType(StartType) && EnableType(EndType))
2241
            {
2242
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
2243
                    result = "E2E";
2244
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
2245
                    result = "B2B";
2246
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
2247
                    result = "HD2";
2248

    
2249
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
2250
                    result = "E2B";
2251
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
2252
                    result = "B2E";
2253

    
2254
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
2255
                    result = "HDB";
2256
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
2257
                    result = "HDB";
2258

    
2259
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
2260
                    result = "HDE";
2261
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
2262
                    result = "HDE";
2263
                else
2264
                    result = "Error";
2265
            }
2266
            else
2267
                result = "Error";
2268

    
2269
            return result;
2270

    
2271
            
2272
        }
2273
        public bool EnableType(PSNType type)
2274
        {
2275
            bool result = false;
2276

    
2277
            if (type == PSNType.Branch ||
2278
                type == PSNType.Equipment ||
2279
                type == PSNType.Header)
2280
            {
2281
                result = true;
2282
            }
2283

    
2284
            return result;
2285
        }
2286
        public bool IsBypass { get; set; }
2287

    
2288
        public string GetFromData(ref string Type, ref Item item)
2289
        {
2290
            Status = string.Empty;
2291
            string result = string.Empty;
2292
            if (IsKeyword)
2293
                IsKeyword = false;
2294
            try
2295
            {
2296
                if (StartType == PSNType.Header)
2297
                    result = "ENDOFHEADER";
2298
                else if (StartType == PSNType.Branch)
2299
                {
2300
                    item = Groups.First().Items.First();
2301
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2302
                    if(!item.MissingLineNumber2)
2303
                        result = item.Relations.First().Item.LineNumber.Name;
2304
                    else
2305
                    {
2306
                        Status += ", Missing LineNumber_2";
2307
                        result = "Empty LineNumber";
2308
                    }
2309

    
2310
                    //if (item.MissingLineNumber1)
2311
                    //{
2312
                    //    Status += ", Missing LineNumber_1";
2313
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2314

    
2315
                    //}
2316
                }
2317
                else if (StartType == PSNType.Equipment)
2318
                {
2319
                    if (Groups.First().Items.First().Equipment != null)
2320
                        result = Groups.First().Items.First().Equipment.ItemTag;
2321
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
2322

    
2323
                    if (drNozzle != null)
2324
                        result += " ["+ drNozzle.Field<string>("ITEMTAG") + "]";
2325
                }                
2326
                else
2327
                {
2328
                    IsValid = "Error";
2329
                    item = Groups.First().Items.First();
2330
                    if (item.ItemType == ItemType.Symbol)
2331
                    {
2332
                        
2333
                        string keyword = string.Empty;
2334
                        keyword = GetFromKeywordData(ref Type, item);
2335

    
2336
                        if (string.IsNullOrEmpty(keyword))
2337
                        {
2338
                            if (item.ID2DBType.Contains("OPC's"))
2339
                                Status += ", OPC Disconnected";
2340
                            else
2341
                                Status += ", Missing ItemTag or Description";
2342

    
2343
                            result = item.ID2DBName;
2344
                        }
2345
                        else
2346
                        {
2347
                            result = keyword;
2348
                            IsKeyword = true;
2349
                            IsValid = string.Empty;
2350
                        }
2351
                        
2352
                    }
2353
                    else if (item.ItemType == ItemType.Line)
2354
                    {
2355
                        if (item.MissingLineNumber1)
2356
                        {
2357
                            Status += ", Missing LineNumber_1";
2358
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2359
                        }
2360
                    }
2361
                    else
2362
                        result = "Unknown";
2363

    
2364
                }
2365
            }
2366
            catch(Exception ex)
2367
            {
2368

    
2369
            }
2370

    
2371
            return result;
2372
        }
2373

    
2374
        public string GetFromKeywordData(ref string Type, Item item)
2375
        {
2376
            string result = string.Empty;
2377
           
2378
            foreach(KeywordItem keyitem in KeywordInfos.KeywordItems)
2379
            {
2380
                if(keyitem.Name.Equals(item.Name))
2381
                {
2382
                    result = keyitem.Keyword;
2383
                    Type = item.ID2DBType;
2384
                    break;
2385
                }
2386
            }
2387
          
2388
            return result;
2389
        }
2390

    
2391
        public string GetToKeywordData(ref string Type, Item item)
2392
        {
2393
            string result = string.Empty;
2394

    
2395
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2396
            {
2397
                if (keyitem.Name.Equals(item.Name))
2398
                {
2399
                    result = keyitem.Keyword;
2400
                    Type = item.ID2DBType;
2401
                    break;
2402
                }
2403
            }
2404
            return result;
2405
        }
2406

    
2407
        public string GetToData(ref string ToType, ref Item item)
2408
        {
2409
            string result = string.Empty;
2410
            Status = string.Empty;
2411

    
2412
            if (IsKeyword)
2413
                IsKeyword = false;
2414

    
2415
            if (EndType == PSNType.Header)
2416
                result = "ENDOFHEADER";
2417
            else if (EndType == PSNType.Branch)
2418
            {
2419
                item = Groups.Last().Items.Last();
2420
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2421
                if (!item.MissingLineNumber2)
2422
                    result = item.Relations.Last().Item.LineNumber.Name;
2423
                else
2424
                {
2425
                    Status += ", Missing LineNumber_2";
2426
                    result = "Empty LineNumber";
2427
                }
2428

    
2429
                //if (item.MissingLineNumber1)
2430
                //{
2431
                //    Status += ", Missing LineNumber_1";
2432
                //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2433

    
2434
                //}
2435
            }
2436
            else if (EndType == PSNType.Equipment)
2437
            {
2438
                if(Groups.Last().Items.Last().Equipment != null)
2439
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
2440

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

    
2443
                if (drNozzle != null)
2444
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2445
            }
2446
            else
2447
            {
2448
                IsValid = "Error";
2449
                item = Groups.Last().Items.Last();
2450
                if (item.ItemType == ItemType.Symbol)
2451
                {
2452
                    string keyword = string.Empty;
2453
                    keyword = GetToKeywordData(ref ToType, item);
2454

    
2455
                    if (string.IsNullOrEmpty(keyword))
2456
                    {
2457
                        if (item.ID2DBType.Contains("OPC's"))
2458
                            Status += ", OPC Disconnected";
2459
                        else
2460
                            Status += ", Missing ItemTag or Description";
2461

    
2462
                        result = item.ID2DBName;
2463
                    }
2464
                    else
2465
                    {
2466
                        result = keyword;
2467
                        IsValid = string.Empty;
2468
                        IsKeyword = true;
2469
                    }
2470

    
2471
                }
2472
                else if (item.ItemType == ItemType.Line)
2473
                {
2474
                    if (item.MissingLineNumber1)
2475
                    {
2476
                        Status += ", Missing LineNumber_1";
2477
                        result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2478
                    }
2479
                }
2480
                else
2481
                    result = "Unknown";
2482
                
2483
               
2484
            }
2485
           
2486
        
2487
         
2488
            return result;
2489
        }
2490

    
2491
        public string GetPBSData()
2492
        {
2493
            string result = string.Empty;
2494
            List<string> PBSList = new List<string>();
2495
            if (Settings.Default.PBSSetting.Equals("Line Number"))
2496
            {
2497
                string attrValue = Settings.Default.PBSSettingValue;
2498

    
2499
                foreach (Group group in Groups)
2500
                {
2501
                    List<LineNumber> lineNumbers = group.Items.Select(x =>x.LineNumber).Distinct().ToList();
2502
                    foreach (LineNumber lineNumber in lineNumbers)
2503
                    {
2504
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
2505
                        if (attribute != null)
2506
                        {
2507
                            string value = attribute.Value;
2508
                            if (!PBSList.Contains(value))
2509
                                PBSList.Add(value);
2510
                        }
2511
                    }
2512
                }
2513
            }
2514
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
2515
            {
2516
                string attrValue = Settings.Default.PBSSettingValue;
2517

    
2518
                foreach (Group group in Groups)
2519
                {
2520
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
2521
                    foreach (Item item in items)
2522
                    {
2523
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
2524
                        if (!PBSList.Contains(value))
2525
                            PBSList.Add(value);
2526
                    }
2527
                }
2528
            }
2529
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
2530
            {
2531
                string attrValue = Settings.Default.PBSSettingValue;
2532

    
2533
                foreach (Group group in Groups)
2534
                {
2535
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2536
                    foreach (Document document in documents)
2537
                    {
2538
                        string name = document.DrawingName;
2539

    
2540
                        int startIndex = Settings.Default.PBSSettingStartValue;
2541
                        int endIndex = Settings.Default.PBSSettingEndValue;
2542

    
2543
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
2544
                        if (!PBSList.Contains(subStr))
2545
                            PBSList.Add(subStr);
2546
                    }
2547
                }
2548
            }
2549
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
2550
            {
2551
                foreach (Group group in Groups)
2552
                {
2553
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2554
                    foreach (Document document in documents)
2555
                    {
2556
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
2557
                        foreach (TextInfo textInfo in textInfos)
2558
                        {
2559
                            if (!PBSList.Contains(textInfo.Value))
2560
                                PBSList.Add(textInfo.Value);
2561
                        }
2562
                    }
2563
                }
2564
            }
2565

    
2566
            foreach (var item in PBSList)
2567
            {
2568
                if (string.IsNullOrEmpty(result))
2569
                    result = item;
2570
                else
2571
                    result += ", " + item;
2572
            }
2573
            return result;
2574
        }
2575
    }
2576
}
클립보드 이미지 추가 (최대 크기: 500 MB)