프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ 4e2e0aa1

이력 | 보기 | 이력해설 | 다운로드 (113 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 = "Line Disconnected";
47
        public string Rule2 = "Missing LineNumber"; //토폴로지데이터가 = Empty LineNumber 인것 ??..
48
        public string Rule3 = "OPC Disconneted";
49
        public string Rule4 = "Missing ItemTag or Description";
50
        //public string Rule5 = "";
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
            // Item들의 속성으로 Topology Data를 생성한다.
209
            // Topology Data는 Topology Rule Setting을 기준으로 생성한다. 
210
            SetTopologyData();
211
            // ID2의 OPC연결 Data 기반으로 Group(도면단위 PSN)을 연결한다.
212
            ConnectByOPC();
213
            // 실제 PSN 생성 로직
214
            // 연결된 Group을 하나의 PSN으로 만든다.
215
            SetPSNItem();
216
            // 생성된 PSN의 Type을 설정한다.
217
            SetPSNType();
218
            // ID2에는 Branch 정보가 없어서 Branch 정보를 생성한다.
219
            SetBranchInfo();
220
            // 생성된 Topology Data들을 정리하며 Main, Branch를 판단한다.
221
            SetTopology();
222
            // PSN이 Bypass인지 검사 
223
            SetPSNBypass();
224
            // Topology들에게 Index를 부여한다
225
            SetTopologyIndex();            
226
            // Nozzle, Equipment의 정보를 저장
227
            SaveNozzleAndEquipment();
228
            // PSN의 정보를 저장
229
            SavePSNData();
230
            // Update Keyword
231
            UpdateKeywordForPSN();
232
            // Vent/Drain PSN 데이터 제거
233
            DeleteVentDrain();
234
            // Topology의 subtype을 update(bypass, Header, 등등) 
235
            UpdateSubType();
236
            // Update Error
237
            UpdateErrorForPSN();
238
            // Insert Tee
239
            InsertTeePSN();
240
            // 확도 계산
241
            UpdateAccuracy();          
242
        }
243

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

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

    
285
                            item.Owner = prevLineNumber.UID;
286
                        }
287
                    }
288
                    else
289
                        prevLineNumber = lineNumber;
290
                }
291

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

    
298
                    // Copy
299
                    LineNumber cLineNumber = lineNumbers[index].Copy();
300
                    group.Document.LineNumbers.Add(cLineNumber);
301
                    
302
                    foreach (Item item in group.Items)
303
                    {
304
                        item.Owner = cLineNumber.UID;
305
                        item.MissingLineNumber = true;
306
                    }
307

    
308
                    
309
                }
310
            }
311

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

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

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

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

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

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

    
372
        }
373

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

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

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

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

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

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

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

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

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

    
481
                PSNItem.Groups.Clear();
482
                PSNItem.Groups.AddRange(_groups);
483
            }
484

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

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

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

    
506
                Item firstItem = firstGroup.Items.First();
507
                Item lastItem = lastGroup.Items.Last();
508

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

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

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

    
547
                return type;
548
            }
549
        }
550

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

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

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

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

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

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

    
619
                                        if (!PSNItem.Topologies.Contains(topology))
620
                                            PSNItem.Topologies.Add(topology);
621
                                    }
622
                                }
623

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

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

    
639

    
640
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
641

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

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

    
666
        }
667

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

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

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

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

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

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

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

    
722

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

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

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

    
761
                    if (result.Count > 0)
762
                        break;
763
                }
764

    
765
                return result;
766
            }
767

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

    
790
                    if (result.Count > 0)
791
                        break;
792
                }
793

    
794
                return result;
795
            }
796

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

    
802
            return main;
803
        }
804

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

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

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

    
840
                        dt.Rows.Add(newRow);
841
                    }
842
                }
843
            }
844

    
845
            return dt;
846
        }
847

    
848
        private DataTable GetTopologyRule()
849
        {
850
            DataTable dt = DB.SelectTopologyRule();
851

    
852
            return dt;
853
        }
854

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

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

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

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

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

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

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

    
922
                nozzleDT.Rows.Add(row);
923
            }
924

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

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

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

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

    
951
                equipDT.Rows.Add(row);
952
            }
953

    
954
            Equipment = equipDT;
955
            Nozzle = nozzleDT;
956
        }
957

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

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

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

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

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

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

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

    
1041
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1042
                    {
1043
                        Index = index,
1044
                        Name = name
1045
                    });
1046
                }
1047

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

    
1057
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1058
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1059
                    {
1060
                        Index = index,
1061
                        Name = name,
1062
                        Keyword = keyword
1063
                    });
1064
                }               
1065
                #endregion
1066

    
1067
                // key = 미입력 branch
1068
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1069
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1070

    
1071
                foreach (PSNItem PSNItem in PSNItems)
1072
                {
1073
                    try
1074
                    {
1075
                        int psnOrder = 0;
1076
                        int index = 0;
1077
                        bool bPSNStart = true;
1078
                        string sPSNData = string.Empty;
1079
                        bool bVentDrain = false;
1080

    
1081
                        //VentDrain 검사
1082
                        if (PSNItem.Groups.Count.Equals(1))
1083
                        {
1084
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1085
                            Group group = PSNItem.Groups[0];
1086
                            List<Item> items = group.Items.FindAll(x => x.Name != "PSN_Nozzle");
1087
                            for (int i = 0; i < items.Count; i++)
1088
                            {
1089
                                Item item = items[i];                               
1090

    
1091
                                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1092
                                {
1093
                                    if (endInfos.Contains(ventDrainInfo) || ventDrainInfo.VentDrainItems.Count != items.Count)
1094
                                        continue;
1095
                                    if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1096
                                    {
1097
                                        endInfos.Add(ventDrainInfo);
1098
                                        continue;
1099
                                    }
1100

    
1101
                                    if (i + 1 == items.Count && items.Count.Equals(ventDrainInfo.VentDrainItems.Count))
1102
                                    {
1103
                                        bVentDrain = true;
1104
                                    }
1105
                                }
1106
                            }
1107

    
1108
                            if (!bVentDrain)
1109
                            {
1110
                                endInfos = new List<VentDrainInfo>();
1111
                                for (int i = 0; i < items.Count; i++)
1112
                                {
1113
                                    Item item = items[items.Count - i - 1];
1114
                                   
1115
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1116
                                    {
1117
                                        if (endInfos.Contains(ventDrainInfo) || ventDrainInfo.VentDrainItems.Count != items.Count)
1118
                                            continue;
1119
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1120
                                        {
1121
                                            endInfos.Add(ventDrainInfo);
1122
                                            continue;
1123
                                        }
1124

    
1125
                                        if (i + 1 == items.Count && items.Count.Equals(ventDrainInfo.VentDrainItems.Count))
1126
                                        {
1127
                                            bVentDrain = true;
1128
                                        }
1129
                                    }
1130
                                }
1131
                            }
1132
                        }
1133
                                                                       
1134
                        try
1135
                        {                            
1136
                            //PSN, PathItems, SequenceData 관련
1137
                            foreach (Group group in PSNItem.Groups)
1138
                            {                                
1139
                                foreach (Item item in group.Items)
1140
                                {
1141
                                    string PathitemUID = string.Empty;
1142
                                    if (item.BranchItems.Count == 0)
1143
                                    {
1144
                                        PathitemUID = item.UID;
1145
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType);
1146
                                        CreateSequenceDataDataRow(PathitemUID);
1147
                                        index++;
1148
                                    }
1149
                                    else
1150
                                    {
1151
                                        PathitemUID = item.UID + "_L1";
1152
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType);
1153
                                        CreateSequenceDataDataRow(PathitemUID);
1154
                                        index++;
1155
                                        for (int i = 0; i < item.BranchItems.Count; i++)
1156
                                        {
1157
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1158
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1159
                                            index++;
1160
                                                
1161
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1162
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1163
                                            index++;
1164

    
1165
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1166
                                                startBranchDic.Add(item.BranchItems[i], item);
1167
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1168
                                                endBranchDic.Add(item.BranchItems[i], item);
1169
                                        }
1170
                                    }
1171
                                    if (bPSNStart)
1172
                                    {
1173
                                        CreatePipeSystemNetworkDataRow();
1174
                                        sPSNData = item.TopologyData;
1175
                                        psnOrder++;
1176
                                        bPSNStart = false;
1177
                                    }
1178
                                    else
1179
                                    {
1180
                                        if (item.TopologyData != sPSNData)
1181
                                        {
1182
                                            CreatePipeSystemNetworkDataRow();
1183
                                            sPSNData = item.TopologyData;
1184
                                            psnOrder++;
1185
                                        }
1186
                                    }
1187
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string branchTopologyName = "", Item branchItem = null)
1188
                                    {
1189
                                        DataRow newRow = pathItemsDT.NewRow();
1190

    
1191
                                        if (itemType == "Nozzles")
1192
                                        {
1193
                                            newRow["Equipment_OID"] = item.Equipment.UID;
1194
                                        }
1195

    
1196
                                        newRow["OID"] = itemOID;
1197
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1198
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
1199
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
1200
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
1201
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
1202
                                        newRow["ITEMTAG"] = GetItemTag(item);
1203
                                        newRow["Class"] = GetClass(item, itemOID);
1204
                                        string subClass = GetSubClass(item, itemOID);                                           
1205
                                        newRow["SubClass"] = subClass;
1206

    
1207
                                        if (item.ItemType == ItemType.Symbol)
1208
                                            newRow["TYPE"] = item.ID2DBName;
1209
                                        else if (item.ItemType == ItemType.Line)
1210
                                            newRow["TYPE"] = item.ID2DBType;
1211
                                        newRow["PIDNAME"] = group.Document.DrawingName;
1212

    
1213
                                        // NPD
1214
                                        if (item.LineNumber != null)
1215
                                        {
1216
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1217
                                            if (attribute != null)
1218
                                                newRow["NPD"] = attribute.Value;
1219
                                        }
1220
                                        else
1221
                                            newRow["NPD"] = null;
1222

    
1223

    
1224
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1225
                                        if (branchItem == null)
1226
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1227
                                        else
1228
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
1229

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

    
1232
                                        pathItemsDT.Rows.Add(newRow);
1233
                                    }
1234
                                    //void UpdatePathItemsDataRow(string itemOID, string Type, string Text)
1235
                                    //{
1236
                                    //    if (pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault() != null)
1237
                                    //    {
1238
                                    //        //pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["TYPE"] = Type;
1239
                                    //        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["ITEMTAG"] = Text;
1240
                                    //        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["DESCRIPTION"] = Text;
1241
                                    //        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["ITEMNAME"] = "PipingComp";
1242
                                    //    }
1243
                                    //}
1244
                                    //void UpdatePathItemsKeywordDataRow(string itemOID, string Text, string Type)
1245
                                    //{
1246
                                    //    if (pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault() != null)
1247
                                    //    {
1248
                                    //        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["CLASS"] = Type;
1249
                                    //        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["TYPE"] = "End";
1250
                                    //        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["ITEMTAG"] = Text;
1251
                                    //        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["DESCRIPTION"] = Text;
1252
                                    //    }
1253
                                    //}
1254
                                    void CreateSequenceDataDataRow(string itemOID)
1255
                                    {
1256
                                        DataRow newRow = sequenceDataDT.NewRow();
1257
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1258
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
1259
                                        newRow["PathItem_OID"] = itemOID;
1260
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1261

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

    
1281
                                                string PipeSystem_OID = string.Join("-", oid);
1282

    
1283
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
1284
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
1285

    
1286
                                                string OID = string.Join("-", oid);
1287

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

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

    
1318
                                        if (PSNItem.IsKeyword)
1319
                                        {                                           
1320
                                            PSNItem.StartType = PSNType.Equipment;
1321
                                          //  UpdatePathItemsKeywordDataRow(From_item.UID, FROM_DATA, FromType);
1322
                                        }
1323
                                        else if (FROM_DATA == "ENDOFHEADER")
1324
                                        {
1325
                                          //  UpdatePathItemsDataRow(From_item.UID, From_item.ID2DBName, FROM_DATA);
1326
                                        }
1327

    
1328
                                        string ToType = string.Empty;
1329
                                        Item To_item = new Item();
1330

    
1331
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
1332
                                        newRow["TO_DATA"] = TO_DATA;
1333

    
1334
                                        if (PSNItem.IsKeyword)
1335
                                        {
1336
                                            PSNItem.EndType = PSNType.Equipment;                                            
1337
                                           // UpdatePathItemsKeywordDataRow(To_item.UID, TO_DATA, ToType);
1338
                                        }
1339
                                        else if (TO_DATA == "ENDOFHEADER")
1340
                                        {
1341
                                          //  UpdatePathItemsDataRow(To_item.UID, To_item.ID2DBName, TO_DATA);
1342
                                        }
1343

    
1344
                                        newRow["Type"] = PSNItem.GetPSNType();
1345
                                       
1346

    
1347
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1348
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1349

    
1350
                                        newRow["IsValid"] = PSNItem.IsValid;
1351
                                        newRow["Status"] = !string.IsNullOrEmpty(PSNItem.Status) ? PSNItem.Status.Remove(0, 2) : string.Empty;
1352
                                        newRow["PBS"] = PSNItem.GetPBSData();
1353

    
1354
                                        List<string> drawingNames = new List<string>();
1355
                                        foreach (Group _group in PSNItem.Groups)
1356
                                        {
1357
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
1358
                                            {
1359
                                                if (drawingNames.Count == 0)
1360
                                                    newRow["Drawings"] = _group.Document.DrawingName;
1361
                                                else
1362
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
1363
                                                drawingNames.Add(_group.Document.DrawingName);
1364
                                            }
1365
                                        }
1366

    
1367
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
1368
                                        if (bVentDrain)
1369
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
1370
                                        else
1371
                                            newRow["IncludingVirtualData"] = "No";
1372
                                        //    return;
1373
                                        //newRow["IncludingVirtualData"] = "No";
1374
                                        newRow["PSNAccuracy"] = "100";
1375
                                        pipeSystemNetworkDT.Rows.Add(newRow);
1376
                                    }
1377
                                }
1378
                            }
1379
                        }
1380
                        catch (Exception ex)
1381
                        {
1382
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1383
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1384
                        }
1385

    
1386
                        //TopologySet 관련
1387
                        foreach (Topology topology in PSNItem.Topologies)
1388
                        {
1389
                            DataRow newRow = topologySetDT.NewRow();
1390
                            newRow["OID"] = topology.FullName;
1391
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1392
                            if (bVentDrain)
1393
                                newRow["SubType"] = "Vent_Drain";
1394
                            else
1395
                                newRow["SubType"] = null;
1396
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1397
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1398
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
1399
                            newRow["TailItemSPID"] = topology.Items.First().UID;
1400
                            topologySetDT.Rows.Add(newRow);
1401
                        }
1402
                        
1403
                    }
1404
                    catch(Exception ee)
1405
                    {
1406

    
1407
                    }
1408
                }
1409

    
1410

    
1411
                foreach (var item in startBranchDic)
1412
                {
1413
                    string uid = item.Key.UID;
1414
                    string topologyName = item.Value.Topology.FullName;
1415
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1416
                   
1417
                    if (rows.Length == 1)
1418
                    {
1419
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1420
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1421
                    }
1422
                    else if (rows.Length > 1)
1423
                    {
1424
                        DataRow targetRow = null;
1425
                        int index = int.MaxValue;
1426
                        foreach (DataRow row in rows)
1427
                        {
1428
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1429
                            if (split.StartsWith("L"))
1430
                            {
1431
                                int num = Convert.ToInt32(split.Remove(0, 1));
1432
                                if (index > num)
1433
                                {
1434
                                    index = num;
1435
                                    targetRow = row;
1436
                                }
1437
                            }
1438
                        }
1439

    
1440
                        if (targetRow != null)
1441
                        {
1442
                            targetRow["BranchTopologySet_OID"] = topologyName;
1443
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1444
                        }
1445
                    }
1446
                }
1447

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

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

    
1484
                PathItems = pathItemsDT;
1485
                SequenceData = sequenceDataDT;
1486
                PipeSystemNetwork = pipeSystemNetworkDT;
1487
                TopologySet = topologySetDT;
1488
                PipeLine = pipelineDT;
1489
            }
1490
            catch (Exception ex)
1491
            {
1492
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1493
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1494
            }
1495
        }
1496

    
1497
        private double AccuracyCalculation(List<double> lstAcc, double acc)
1498
        {
1499
            foreach(double lacc in lstAcc)
1500
            {
1501
                acc *= lacc;
1502
            }
1503
            return acc;
1504
        }
1505

    
1506
        private void UpdateSubType()
1507
        {
1508
            try
1509
            {
1510
                foreach (PSNItem PSNItem in PSNItems)
1511
                {
1512
                    if (PSNItem.IsBypass)
1513
                    {
1514
                        foreach (Topology topology in PSNItem.Topologies)
1515
                        {
1516
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1517
                            if (rows.Length.Equals(1))
1518
                                rows.First()["SubType"] = "Bypass";
1519
                        }
1520
                    }
1521

    
1522
                    if (PSNItem.StartType == PSNType.Header)
1523
                    {
1524
                        Topology topology = PSNItem.Topologies.First();
1525
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1526
                        if (rows.Length.Equals(1))
1527
                            rows.First()["SubType"] = "Header";
1528
                    }
1529
                    else if (PSNItem.EndType == PSNType.Header)
1530
                    {
1531
                        Topology topology = PSNItem.Topologies.Last();
1532
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1533
                        if (rows.Length.Equals(1))
1534
                            rows.First()["SubType"] = "Header";
1535
                    }
1536
                }
1537

    
1538

    
1539
                foreach (Topology topology in Topologies)
1540
                {
1541
                    try
1542
                    {
1543
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1544
                        
1545
                        if(rows.Count() > 0)
1546
                        {
1547
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
1548
                            {
1549
                                if (topology.Items == null)
1550
                                    continue;
1551

    
1552
                                Item firstItem = topology.Items.First();
1553
                                Item lastItem = topology.Items.Last();
1554

    
1555
                                List<Relation> relations = new List<Relation>();
1556

    
1557
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1558
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1559

    
1560
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1561
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1562

    
1563
                                if (relations.Count > 0)
1564
                                    rows.First()["SubType"] = "OtherSystem";
1565
                            }
1566
                        }
1567
                    }
1568
                    catch (Exception ex)
1569
                    {
1570
                       
1571
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1572
                    }
1573
                }
1574

    
1575
                    foreach (DataRow row in TopologySet.Rows)
1576
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
1577
                        row["SubType"] = "Normal";
1578
            }
1579
            catch (Exception ex)
1580
            {
1581
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1582
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1583
            }
1584
        }
1585

    
1586
        private bool IsBypass(PSNItem PSNItem)
1587
        {
1588
            bool bResult = false;
1589

    
1590
            if (PSNItem.GetPSNType() == "B2B")
1591
            {
1592
                Group firstGroup = PSNItem.Groups.First();
1593
                Group lastGroup = PSNItem.Groups.Last();
1594
                Item firstItem = firstGroup.Items.First();
1595
                Item lastItem = lastGroup.Items.Last();
1596

    
1597
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
1598
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
1599

    
1600
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
1601
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
1602
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
1603
                    bResult = true;
1604
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
1605
                    bResult = true;
1606
            }
1607

    
1608
            Item GetConnectedItemByPSN(Item item)
1609
            {
1610
                Item result = null;
1611

    
1612
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
1613
                if (relation != null)
1614
                    result = relation.Item;
1615

    
1616

    
1617
                return result;
1618
            }
1619

    
1620
            return bResult;
1621
        }
1622

    
1623
        private void DeleteVentDrain()
1624
        {
1625
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
1626
            
1627
            foreach (DataRow dataRow in ventdrainRows)
1628
            {
1629
                dataRow.Delete();             
1630
            }       
1631
        }
1632

    
1633
        private void UpdateAccuracy()
1634
        {
1635
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
1636
            List<double> lstAcc = null;
1637
            string Status = string.Empty;
1638

    
1639
            foreach (DataRow dataRow in statusRows)
1640
            {
1641
                lstAcc = new List<double>();
1642
                Status = dataRow.Field<string>("Status");
1643

    
1644
                if (!string.IsNullOrEmpty(Status))
1645
                {
1646
                    if (Status.Contains(Rule1)) //Line Disconnected
1647
                        lstAcc.Add(0.75);
1648

    
1649
                    if (Status.Contains(Rule2)) //Missing LineNumber
1650
                        lstAcc.Add(0.7);
1651

    
1652
                    if (Status.Contains(Rule3))
1653
                        lstAcc.Add(0.5);
1654

    
1655
                    if (Status.Contains(Rule4)) //Missing ItemTag or Description
1656
                        lstAcc.Add(0.65);                      
1657
                
1658
                }
1659

    
1660
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
1661
                if (PSNAccuracy == "100")
1662
                    PSNAccuracy = "1";
1663

    
1664
                PSNAccuracy = Convert.ToString(Math.Round(Convert.ToDouble(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))), 2));
1665
                if (PSNAccuracy != "100")
1666
                {
1667
                    //dataRow["IncludingVirtualData"] = "No";
1668
                    dataRow["PSNAccuracy"] = PSNAccuracy;
1669
                }
1670
            }
1671
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
1672
            foreach (DataRow dr in dt.Rows)
1673
            {
1674
                string oid = dr.Field<string>("OID");
1675
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
1676
                double totalDdr = 0;
1677
                foreach (DataRow ddr in select)
1678
                {
1679
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
1680
                    if (acc == 100) acc = 1;
1681
                    if (totalDdr == 0) totalDdr = acc;
1682
                    else totalDdr *= acc;
1683
                }
1684

    
1685
                totalDdr *= 100;
1686

    
1687
                if(totalDdr != 100)
1688
                {
1689
                    foreach (DataRow ddr in select)
1690
                    {
1691
                        ddr["IncludingVirtualData"] = "Yes";
1692
                        ddr["PSNAccuracy"] = Math.Round(totalDdr, 2);
1693
                    }
1694
                }
1695
            }
1696

    
1697
        }
1698

    
1699
        private void UpdateKeywordForPSN()
1700
        {
1701
            #region Keyword Info
1702
            KeywordInfo KeywordInfos = new KeywordInfo();
1703
            DataTable dtKeyword = DB.SelectKeywordsSetting();
1704
            foreach (DataRow row in dtKeyword.Rows)
1705
            {
1706
                int index = Convert.ToInt32(row["INDEX"]);
1707
                string name = row["NAME"].ToString();
1708
                string keyword = row["KEYWORD"].ToString();
1709

    
1710
                //KeywordInfo keywordInfo = new KeywordInfo();   
1711
                KeywordInfos.KeywordItems.Add(new KeywordItem()
1712
                {
1713
                    Index = index,
1714
                    Name = name,
1715
                    Keyword = keyword
1716
                });
1717
            }
1718
            #endregion
1719

    
1720
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
1721
            foreach (DataRow dataRow in endofHeaderRows)
1722
            {
1723
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
1724

    
1725
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
1726
                {
1727
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1728
                    DataRow dr = pathItemRows.First();
1729
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
1730
                    dr["TYPE"] = "End";
1731
                    dr["ITEMTAG"] = "ENDOFHEADER";
1732
                    dr["DESCRIPTION"] = "ENDOFHEADER";
1733
                }
1734

    
1735
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
1736
                {
1737
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1738
                    DataRow dr = pathItemRows.Last();
1739
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
1740
                    dr["TYPE"] = "End";
1741
                    dr["ITEMTAG"] = "ENDOFHEADER";
1742
                    dr["DESCRIPTION"] = "ENDOFHEADER";
1743
                }
1744
            }
1745

    
1746
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
1747
            {
1748
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
1749
                foreach (DataRow dataRow in keywordRows)
1750
                {                    
1751
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());                     
1752

    
1753
                    if(dataRow.Field<string>("From_Data") == keyitem.Keyword)
1754
                    {                   
1755
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1756
                             
1757
                        //
1758
                        //if(.)
1759
                        if(PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
1760
                        {
1761
                            DataRow dr = pathItemRows.First();
1762
                            //dr["CLASS"] = ""; //Type
1763
                            dr["TYPE"] = "End";
1764
                            dr["ITEMTAG"] = keyitem.Keyword;
1765
                            dr["DESCRIPTION"] = keyitem.Keyword;
1766
                        }
1767
                           
1768
                    }
1769

    
1770
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
1771
                    {
1772
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1773

    
1774
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
1775
                        {
1776
                            DataRow dr = pathItemRows.Last();
1777
                            //dr["CLASS"] = ""; //Type
1778
                            dr["TYPE"] = "End";
1779
                            dr["ITEMTAG"] = keyitem.Keyword;
1780
                            dr["DESCRIPTION"] = keyitem.Keyword;
1781
                            //dr.Field<string>("Type")
1782
                        }
1783

    
1784
                    }                   
1785
                }
1786
            }          
1787
        }
1788

    
1789
        private void UpdateErrorForPSN()
1790
        {
1791
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
1792
            double PSNAccuracy = 0;
1793
            foreach (DataRow dataRow in errorRows)
1794
            {
1795
                try
1796
                {
1797
                    PSNAccuracy = 0;
1798
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
1799
                    bool change = false;
1800
                    if (!PSNItem.EnableType(PSNItem.StartType))
1801
                    {
1802
                        change = true;
1803
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));                       
1804
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
1805
                        
1806
                        Item item = PSNItem.Groups.First().Items.First();
1807
                        try
1808
                        {
1809
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1810
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1811
                                loopRow["FROM_DATA"] = FROM_DATA;
1812
                            tieInPointIndex++;
1813

    
1814

    
1815
                            if (item.ItemType == ItemType.Line)
1816
                            {
1817
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
1818

    
1819
                                PSNAccuracy = 0.6;
1820
                            }
1821
                            else
1822
                            {
1823
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
1824
                                
1825
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
1826

    
1827
                               //PSNAccuracy = 0.5;
1828
                            }
1829

    
1830
                            PSNItem.StartType = PSNType.Equipment;
1831
                        }
1832
                        catch (Exception ex)
1833
                        {
1834
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1835
                            return;
1836
                        }
1837
                    }
1838

    
1839

    
1840
                    if (!PSNItem.EnableType(PSNItem.EndType))
1841
                    {
1842
                        change = true;
1843
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1844
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.Last());
1845
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
1846

    
1847
                        Item item = PSNItem.Groups.Last().Items.Last();
1848
                        try
1849
                        {
1850
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1851

    
1852
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1853
                                loopRow["TO_DATA"] = TO_DATA;
1854
                            tieInPointIndex++;
1855

    
1856

    
1857
                            if (item.ItemType == ItemType.Line)
1858
                            {
1859
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
1860
                                PSNAccuracy = 0.6;
1861
                            }
1862
                            else
1863
                            {
1864
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
1865
                                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);
1866
                                //PSNAccuracy = 0.5;
1867
                            }
1868

    
1869
                            PSNItem.EndType = PSNType.Equipment;
1870
                        }
1871
                        catch(Exception ex)
1872
                        {
1873
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1874
                            return;
1875
                        }
1876
                    }
1877

    
1878
                    dataRow["Type"] = PSNItem.GetPSNType();
1879
                    if (change)
1880
                    {
1881
                        int rowIndex = 0;
1882
                        for (int i = 0; i < PathItems.Rows.Count; i++)
1883
                        {
1884
                            DataRow row = PathItems.Rows[i];
1885
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
1886
                                continue;
1887
                            string sequenceData = row["SequenceData_OID"].ToString();
1888
                            string[] split = sequenceData.Split(new char[] { '_' });
1889

    
1890
                            StringBuilder sb = new StringBuilder();
1891
                            for (int j = 0; j < split.Length - 1; j++)
1892
                                sb.Append(split[j] + "_");
1893
                            sb.Append(rowIndex++);
1894
                            row["SequenceData_OID"] = sb.ToString();
1895

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

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

    
1901
                            if (seqItemRows == null)
1902
                            {
1903
                                DataRow newRow = SequenceData.NewRow();    
1904
                                newRow["OID"] = sb.ToString();
1905
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
1906
                                newRow["PathItem_OID"] = row["OID"];
1907
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
1908
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
1909
                            }
1910
                            else
1911
                            {
1912
                                seqItemRows["OID"] = sb.ToString();
1913
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
1914
                                seqItemRows["PathItem_OID"] = row["OID"];
1915
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
1916

    
1917
                            }
1918
                           
1919

    
1920
                        }
1921

    
1922
                        //rowIndex = 0;
1923
                        //for (int i = 0; i < SequenceData.Rows.Count; i++)
1924
                        //{
1925
                        //    DataRow row = SequenceData.Rows[i];
1926
                        //    if (row["PathItem_OID"].ToString() != dataRow["OID"].ToString())
1927
                        //        continue;
1928
                        //    string sequenceData = row["SequenceData_OID"].ToString();
1929
                        //    string[] split = sequenceData.Split(new char[] { '_' });
1930

    
1931
                        //    row["SERIALNUMBER"] = rowIndex++;
1932
                        //}
1933
                    }
1934

    
1935
                    //if (PSNAccuracy != 0 )
1936
                    //{                       
1937
                    //    dataRow["IncludingVirtualData"] = "Yes";
1938
                    //    dataRow["PSNAccuracy"] = Convert.ToString(PSNAccuracy);
1939
                       
1940
                    //}
1941

    
1942
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
1943
                    {
1944
                        DataRow newRow = PathItems.NewRow();
1945
                        newRow["OID"] = Guid.NewGuid().ToString();
1946
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1947
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1948
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1949
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];                        
1950
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
1951
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
1952
                        newRow["DESCRIPTION"] = DATA; 
1953
                        newRow["Class"] = "End of line terminator";
1954
                        newRow["SubClass"] = "End of line terminator";
1955
                        newRow["TYPE"] = "End";
1956
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
1957
                        newRow["NPD"] = itemRow["NPD"];
1958
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1959
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1960
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1961

    
1962
                        
1963

    
1964
                        return newRow;
1965
                    }
1966

    
1967
                    //DataRow createSequenceTerminatorRow(DataRow itemRow, int insertIndex)
1968
                    //{
1969
                    //    DataRow newRow = SequenceData.NewRow();
1970
                    //    newRow["OID"] = itemRow["SequenceData_OID"]; 
1971
                    //    newRow["SERIALNUMBER"] = string.Format("{0}", insertIndex);
1972
                    //    newRow["PathItem_OID"] = itemRow["OID"];
1973
                    //    newRow["TopologySet_OID_Key"] = itemRow["TopologySet_OID"];
1974

    
1975
                    //    return newRow;
1976
                    //}
1977

    
1978
                    DataRow createLineRow(DataRow itemRow)
1979
                    {
1980
                        DataRow newRow = PathItems.NewRow();
1981
                        newRow["OID"] = Guid.NewGuid().ToString();
1982
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1983
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1984
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1985
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
1986
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
1987
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
1988
                        newRow["Class"] = itemRow["Class"];
1989
                        newRow["SubClass"] = itemRow["SubClass"];
1990
                        newRow["TYPE"] = itemRow["TYPE"];
1991
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
1992
                        newRow["NPD"] = itemRow["NPD"];
1993
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1994
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1995
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1996

    
1997
                        return newRow;
1998
                    }
1999
                }
2000
                catch(Exception ex)
2001
                {
2002

    
2003
                }
2004
            }
2005
        }
2006

    
2007
        private void InsertTeePSN()
2008
        {
2009
            DataRow[] branchRows = PipeSystemNetwork.Select("Type Like '%B%'");
2010
            bool checkF = false;
2011
            foreach (DataRow dataRow in branchRows)
2012
            {
2013
                checkF = false;
2014
                try
2015
                {
2016
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2017
                    bool change = false;
2018
                   
2019
                    if (PSNItem.StartType == PSNType.Branch)
2020
                    {
2021
                        change = true;
2022
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2023
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2024
                        Item item = PSNItem.Groups.First().Items.First();
2025
                        try
2026
                        {                
2027
                            if (item.ItemType == ItemType.Line)
2028
                            {
2029
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
2030
                                {
2031
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
2032
                                    checkF = true;
2033
                                }
2034

    
2035
                            }                            
2036
                        }
2037
                        catch (Exception ex)
2038
                        {
2039
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2040
                            return;
2041
                        }
2042
                    }
2043

    
2044
                    if (PSNItem.EndType == PSNType.Branch)
2045
                    {
2046
                        change = true;
2047
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2048
                        int insertIndex = 0;
2049

    
2050
                        if (!checkF)
2051
                            insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
2052
                        else
2053
                            insertIndex = pathItemRows.Count() - 1;
2054

    
2055
                        //if(checkF)
2056

    
2057

    
2058
                        Item item = PSNItem.Groups.Last().Items.Last();
2059
                        try
2060
                        {
2061
                            if (item.ItemType == ItemType.Line)
2062
                            {
2063
                                if (pathItemRows.Last().Field<string>("SubClass") != "Tee")
2064
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.Last()), insertIndex + 1);
2065
                            }
2066
                        }
2067
                        catch (Exception ex)
2068
                        {
2069
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2070
                            return;
2071
                        }
2072
                    }
2073

    
2074
                    if (change)
2075
                    {
2076
                        int rowIndex = 0;
2077
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2078
                        {
2079
                            DataRow row = PathItems.Rows[i];
2080
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
2081
                                continue;
2082
                            string sequenceData = row["SequenceData_OID"].ToString();
2083
                            string[] split = sequenceData.Split(new char[] { '_' });
2084

    
2085
                            StringBuilder sb = new StringBuilder();
2086
                            for (int j = 0; j < split.Length - 1; j++)
2087
                                sb.Append(split[j] + "_");
2088
                            sb.Append(rowIndex++);
2089
                            row["SequenceData_OID"] = sb.ToString();
2090

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

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

    
2096
                            if (seqItemRows == null)
2097
                            {
2098
                                DataRow newRow = SequenceData.NewRow();
2099
                                newRow["OID"] = sb.ToString();
2100
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2101
                                newRow["PathItem_OID"] = row["OID"];
2102
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2103
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2104
                            }
2105
                            else
2106
                            {
2107
                                seqItemRows["OID"] = sb.ToString();
2108
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2109
                                seqItemRows["PathItem_OID"] = row["OID"];
2110
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2111
                            }
2112
                        }
2113
                    }                  
2114

    
2115
                    DataRow createTeeRow(DataRow itemRow)
2116
                    {
2117
                        DataRow newRow = PathItems.NewRow();
2118
                        newRow["OID"] = Guid.NewGuid().ToString();
2119
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2120
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2121
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2122
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2123
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
2124
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2125
                        newRow["DESCRIPTION"] = "";
2126
                        newRow["Class"] = "Branch";
2127
                        newRow["SubClass"] = "Tee";
2128
                        newRow["TYPE"] = itemRow["TYPE"];
2129
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2130
                        newRow["NPD"] = itemRow["NPD"];
2131
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2132
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2133
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2134

    
2135
                        return newRow;
2136
                    }
2137
                }
2138
                catch (Exception ex)
2139
                {
2140

    
2141
                }
2142
            }
2143
        }
2144
    }
2145

    
2146
    public class PSNItem
2147
    {
2148
        public PSNItem(int count, int Revision)
2149
        {
2150
            Groups = new List<Group>();
2151
            Topologies = new List<Topology>();
2152

    
2153
            Index = count + 1;
2154
            this.Revision = Revision;
2155
        }
2156

    
2157
        private int Revision;
2158
        public string UID { get; set; }
2159
        public List<Group> Groups { get; set; }
2160
        public List<Topology> Topologies { get; set; }
2161
        public PSNType StartType { get; set; }
2162
        public PSNType EndType { get; set; }
2163
        public int Index { get; set; }
2164
        public string IsValid { get; set; }
2165
        public bool IsKeyword { get; set; }
2166
        public string Status { get; set; }
2167
        public string IncludingVirtualData { get; set; }
2168
        public string PSNAccuracy { get; set; }
2169
        public KeywordInfo KeywordInfos = new KeywordInfo();
2170
        public DataTable Nozzle = new DataTable();
2171

    
2172
        public string PSN_OID()
2173
        {
2174
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
2175
        }
2176
        public string GetPSNType()
2177
        {
2178
            string result = string.Empty;
2179

    
2180
            if (EnableType(StartType) && EnableType(EndType))
2181
            {
2182
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
2183
                    result = "E2E";
2184
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
2185
                    result = "B2B";
2186
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
2187
                    result = "HD2";
2188

    
2189
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
2190
                    result = "E2B";
2191
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
2192
                    result = "B2E";
2193

    
2194
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
2195
                    result = "HDB";
2196
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
2197
                    result = "HDB";
2198

    
2199
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
2200
                    result = "HDE";
2201
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
2202
                    result = "HDE";
2203
                else
2204
                    result = "Error";
2205
            }
2206
            else
2207
                result = "Error";
2208

    
2209
            return result;
2210

    
2211
            
2212
        }
2213
        public bool EnableType(PSNType type)
2214
        {
2215
            bool result = false;
2216

    
2217
            if (type == PSNType.Branch ||
2218
                type == PSNType.Equipment ||
2219
                type == PSNType.Header)
2220
            {
2221
                result = true;
2222
            }
2223

    
2224
            return result;
2225
        }
2226
        public bool IsBypass { get; set; }
2227

    
2228
        public string GetFromData(ref string Type, ref Item item)
2229
        {
2230
            string result = string.Empty;
2231
            if (IsKeyword)
2232
                IsKeyword = false;
2233
            try
2234
            {
2235
                if (StartType == PSNType.Header)
2236
                    result = "ENDOFHEADER";
2237
                else if (StartType == PSNType.Branch)
2238
                {
2239
                    item = Groups.First().Items.First();
2240
                    if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2241
                        result = item.Relations.First().Item.LineNumber.Name;
2242
                    else
2243
                    {
2244
                        Status += ", Missing LineNumber";
2245
                        result = "Empty LineNumber";
2246
                    }
2247
                }
2248
                else if (StartType == PSNType.Equipment)
2249
                {
2250
                    if (Groups.First().Items.First().Equipment != null)
2251
                        result = Groups.First().Items.First().Equipment.ItemTag;
2252
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
2253

    
2254
                    if (drNozzle != null)
2255
                        result += " ["+ drNozzle.Field<string>("ITEMTAG") + "]";
2256
                }
2257
                
2258
                else
2259
                {
2260
                    IsValid = "Error";
2261
                    item = Groups.First().Items.First();
2262
                    if (item.ItemType == ItemType.Symbol)
2263
                    {
2264
                        
2265
                        string keyword = string.Empty;
2266
                        keyword = GetFromKeywordData(ref Type, item);
2267

    
2268
                        if (string.IsNullOrEmpty(keyword))
2269
                        {
2270
                            if (item.ID2DBType.Contains("OPC's"))
2271
                                Status += ", OPC Disconneted";
2272
                            else
2273
                                Status += ", Missing ItemTag or Description";
2274

    
2275
                            result = item.ID2DBName;
2276
                        }
2277
                        else
2278
                        {
2279
                            result = keyword;
2280
                            IsKeyword = true;
2281
                            IsValid = string.Empty;
2282
                        }
2283
                        
2284
                    }
2285
                    else if (item.ItemType == ItemType.Line)
2286
                    {
2287
                        Status += ", Line Disconnected";
2288
                        result = !item.MissingLineNumber && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2289
                    }
2290
                    else
2291
                        result = "Unknown";
2292
                }
2293
            }
2294
            catch(Exception ex)
2295
            {
2296

    
2297
            }
2298

    
2299
            return result;
2300
        }
2301

    
2302
        public string GetFromKeywordData(ref string Type, Item item)
2303
        {
2304
            string result = string.Empty;
2305
           
2306
            foreach(KeywordItem keyitem in KeywordInfos.KeywordItems)
2307
            {
2308
                if(keyitem.Name.Equals(item.Name))
2309
                {
2310
                    result = keyitem.Keyword;
2311
                    Type = item.ID2DBType;
2312
                    break;
2313
                }
2314
            }
2315
          
2316
            return result;
2317
        }
2318

    
2319
        public string GetToKeywordData(ref string Type, Item item)
2320
        {
2321
            string result = string.Empty;
2322

    
2323
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2324
            {
2325
                if (keyitem.Name.Equals(item.Name))
2326
                {
2327
                    result = keyitem.Keyword;
2328
                    Type = item.ID2DBType;
2329
                    break;
2330
                }
2331
            }
2332
            return result;
2333
        }
2334

    
2335
        public string GetToData(ref string ToType, ref Item item)
2336
        {
2337
            string result = string.Empty;
2338
          
2339

    
2340
            if (IsKeyword)
2341
                IsKeyword = false;
2342

    
2343
            if (EndType == PSNType.Header)
2344
                result = "ENDOFHEADER";
2345
            else if (EndType == PSNType.Branch)
2346
            {
2347
                item = Groups.Last().Items.Last();
2348
                if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2349
                    result = item.Relations.Last().Item.LineNumber.Name;
2350
                else
2351
                {
2352
                    Status += ", Missing LineNumber";
2353
                    result = "Empty LineNumber";
2354
                }
2355
            }
2356
            else if (EndType == PSNType.Equipment)
2357
            {
2358
                if(Groups.Last().Items.Last().Equipment != null)
2359
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
2360

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

    
2363
                if (drNozzle != null)
2364
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2365
            }
2366
            else
2367
            {
2368
                IsValid = "Error";
2369
                item = Groups.Last().Items.Last();
2370
                if (item.ItemType == ItemType.Symbol)
2371
                {
2372
                    string keyword = string.Empty;
2373
                    keyword = GetToKeywordData(ref ToType, item);
2374

    
2375
                    if (string.IsNullOrEmpty(keyword))
2376
                    {
2377
                        if (item.ID2DBType.Contains("OPC's"))
2378
                            Status += ", OPC Disconneted";
2379
                        else
2380
                            Status += ", Missing ItemTag or Description";
2381

    
2382
                        result = item.ID2DBName;
2383
                    }
2384
                    else
2385
                    {
2386
                        result = keyword;
2387
                        IsValid = string.Empty;
2388
                        IsKeyword = true;
2389
                    }
2390

    
2391
                }
2392
                else if (item.ItemType == ItemType.Line)
2393
                {
2394
                    Status += ", Line Disconnected";
2395
                    result = !item.MissingLineNumber && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2396
                }
2397
                else
2398
                    result = "Unknown";
2399
            }
2400
        
2401
         
2402
            return result;
2403
        }
2404

    
2405
        public string GetPBSData()
2406
        {
2407
            string result = string.Empty;
2408
            List<string> PBSList = new List<string>();
2409
            if (Settings.Default.PBSSetting.Equals("Line Number"))
2410
            {
2411
                string attrValue = Settings.Default.PBSSettingValue;
2412

    
2413
                foreach (Group group in Groups)
2414
                {
2415
                    List<LineNumber> lineNumbers = group.Items.Select(x =>x.LineNumber).Distinct().ToList();
2416
                    foreach (LineNumber lineNumber in lineNumbers)
2417
                    {
2418
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
2419
                        if (attribute != null)
2420
                        {
2421
                            string value = attribute.Value;
2422
                            if (!PBSList.Contains(value))
2423
                                PBSList.Add(value);
2424
                        }
2425
                    }
2426
                }
2427
            }
2428
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
2429
            {
2430
                string attrValue = Settings.Default.PBSSettingValue;
2431

    
2432
                foreach (Group group in Groups)
2433
                {
2434
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
2435
                    foreach (Item item in items)
2436
                    {
2437
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
2438
                        if (!PBSList.Contains(value))
2439
                            PBSList.Add(value);
2440
                    }
2441
                }
2442
            }
2443
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
2444
            {
2445
                string attrValue = Settings.Default.PBSSettingValue;
2446

    
2447
                foreach (Group group in Groups)
2448
                {
2449
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2450
                    foreach (Document document in documents)
2451
                    {
2452
                        string name = document.DrawingName;
2453

    
2454
                        int startIndex = Settings.Default.PBSSettingStartValue;
2455
                        int endIndex = Settings.Default.PBSSettingEndValue;
2456

    
2457
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
2458
                        if (!PBSList.Contains(subStr))
2459
                            PBSList.Add(subStr);
2460
                    }
2461
                }
2462
            }
2463
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
2464
            {
2465
                foreach (Group group in Groups)
2466
                {
2467
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2468
                    foreach (Document document in documents)
2469
                    {
2470
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
2471
                        foreach (TextInfo textInfo in textInfos)
2472
                        {
2473
                            if (!PBSList.Contains(textInfo.Value))
2474
                                PBSList.Add(textInfo.Value);
2475
                        }
2476
                    }
2477
                }
2478
            }
2479

    
2480
            foreach (var item in PBSList)
2481
            {
2482
                if (string.IsNullOrEmpty(result))
2483
                    result = item;
2484
                else
2485
                    result += ", " + item;
2486
            }
2487
            return result;
2488
        }
2489
    }
2490
}
클립보드 이미지 추가 (최대 크기: 500 MB)