프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ d446786e

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

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

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

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

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

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

    
55
        int tieInPointIndex = 1;
56
        int tieInPointSymbolIndex = 1;
57
        List<Document> Documents;
58
        List<Group> groups = new List<Group>();
59
        List<PSNItem> PSNItems = new List<PSNItem>();
60
        List<Topology> Topologies = new List<Topology>();
61

    
62
        DataTable opcDT = null;
63
        DataTable topologyRuleDT = null;
64

    
65
        ID2Info id2Info = ID2Info.GetInstance();
66

    
67
        private Dictionary<string, int> dicMultiwaySymbolUID = new Dictionary<string, int>();
68
        private Dictionary<string, int> dicMultiwaySymbolNameTag = new Dictionary<string, int>();
69

    
70
        //const string FluidPriorityType = "FLUIDCODE";
71
        //const string PipingMaterialsPriorityType = "PIPINGMATERIALSCLASS";
72

    
73
        public PSN()
74
        {
75

    
76
        }
77

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

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

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

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

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

    
210
        public void SetPSNData(SplashScreenManager splashScreenManager1)
211
        {
212
            // Item들의 속성으로 Topology Data를 생성한다.
213
            // Topology Data는 Topology Rule Setting을 기준으로 생성한다.
214
            int i = 1;
215
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopologyData ( 3 % )");
216
            SetTopologyData();
217
            // ID2의 OPC연결 Data 기반으로 Group(도면단위 PSN)을 연결한다.
218
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  ConnectByOPC ( 5 % )");
219
            ConnectByOPC();
220
            // 실제 PSN 생성 로직
221
            // 연결된 Group을 하나의 PSN으로 만든다.
222
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNItem ( 10 % )");
223
            SetPSNItem();
224
            // 생성된 PSN의 Type을 설정한다.
225
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNType ( 15 % )");
226
            SetPSNType();
227
            // ID2에는 Branch 정보가 없어서 Branch 정보를 생성한다.
228
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetBranchInfo ( 20 % )");
229
            SetBranchInfo();
230
            // 생성된 Topology Data들을 정리하며 Main, Branch를 판단한다.
231
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopology ( 25 % )");
232
            SetTopology();
233
            // PSN이 Bypass인지 검사 
234
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNBypass ( 30 % )");
235
            SetPSNBypass();
236
            // Topology들에게 Index를 부여한다
237
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopologyIndex ( 35 % )");
238
            SetTopologyIndex();
239
            // Nozzle, Equipment의 정보를 저장
240
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SaveNozzleAndEquipment ( 40 % )");
241
            SaveNozzleAndEquipment();
242
            // PSN의 정보를 저장
243
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNData ( 45 % )");
244
            SavePSNData();
245
            // Update PSN From/To Keyword & EndofHeader
246
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateKeywordForPSN ( 55 % )");
247
            UpdateKeywordForPSN(); 
248
          
249
            // Topology의 subtype을 update(bypass, Header, 등등) 
250
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateSubType ( 60 % )");
251
            UpdateSubType();
252

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

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

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

    
271
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  PathItemSorting ( 85 % )");
272
            PathItemSorting();
273

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

    
278
            UpdateNoPocket();
279

    
280
            // 확도 계산
281
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAccuracy ( 95 % )");
282
            UpdateAccuracy();
283

    
284
            //UpdatePSNType();
285

    
286
        }
287

    
288
        private void UpdateNoPocket()
289
        {
290
            try
291
            {
292
                DataRow[] nopocketRows = PipeSystemNetwork.Select("Pocket = 'Yes'");
293
                foreach (DataRow row in nopocketRows)
294
                {
295
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", row["OID"].ToString()));
296
                    foreach (DataRow dr in pathItemRows)
297
                    {
298
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
299
                        {
300
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
301

    
302
                            if (rows.First()["SubType"].ToString() == "Bypass")
303
                            {
304
                                DataRow[] bypassRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID")));
305

    
306
                                foreach (DataRow drby in bypassRows)
307
                                {
308
                                    drby["Pocket"] = "Yes";
309
                                }
310
                            }
311
                        }
312
                    }                    
313
                }            
314
            }
315
            catch (Exception ex)
316
            {
317
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
318
            }
319
        }
320

    
321
        private void UpdatePSNType()
322
        {
323
            try
324
            {
325
                foreach (PSNItem PSNItem in PSNItems)
326
                {    
327
                    foreach (Group group in PSNItem.Groups)
328
                    {
329
                        foreach (Item item in group.Items)
330
                        {
331
                            DataRow[] pipeSystems = PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID()));
332
                           // PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
333

    
334
                            foreach(DataRow dr in pipeSystems)
335
                            {
336
                                dr["Type"] = PSNItem.GetPSNType();
337
                            }                            
338
                        }
339
                    }                
340
                }
341
            }
342
            catch (Exception ex)
343
            {
344
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
345
            }
346
        }
347

    
348
        private void PathItemSorting()
349
        {
350
            try
351
            {
352
                DataTable dtPathItems = PathItems.Clone();
353
                DataTable dtPipeSystemNetwork = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
354

    
355
                foreach (DataRow drpipe in dtPipeSystemNetwork.Rows)
356
                {
357
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drpipe["OID"].ToString()));
358
                    DataTable dtSequenceItems = SequenceData.Clone();
359
                    foreach (DataRow drpath in pathItemRows)
360
                    {
361
                        DataRow sequenceRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", drpath.Field<string>("OID"))).First();
362

    
363
                        DataRow newRow = dtSequenceItems.NewRow();
364
                        foreach (DataColumn column in SequenceData.Columns)
365
                            if (dtSequenceItems.Columns[column.ColumnName] != null)
366
                                newRow[column.ColumnName] = sequenceRows[column.ColumnName];
367

    
368
                        dtSequenceItems.Rows.Add(newRow);
369
                    }
370

    
371
                    foreach (DataRow sqrow in dtSequenceItems.Select().OrderBy(x => Convert.ToInt32(x.Field<string>("SERIALNUMBER"))))
372
                    {
373
                        DataRow newRow = dtPathItems.NewRow();
374
                        DataRow row = PathItems.Select(string.Format("OID = '{0}'", sqrow["PathItem_OID"])).First();
375

    
376
                        foreach (DataColumn column in PathItems.Columns)
377
                            if (dtPathItems.Columns[column.ColumnName] != null)
378
                                newRow[column.ColumnName] = row[column.ColumnName];
379

    
380
                        dtPathItems.Rows.Add(newRow);
381
                    }
382
                }
383

    
384
                PathItems.Clear();
385
                PathItems = dtPathItems.Copy();
386
            }
387
            catch (Exception ex)
388
            {
389
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
390
            }
391
        }
392
        
393
        private void UpdateAirFinCooler()
394
        {
395
            try
396
            {
397
                
398
                int pumpTagNum = 0;
399
                #region EquipmentAirFinCooler Info
400
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
401
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
402
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
403
                {
404
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
405
                    {
406
                        Type = row["Type"].ToString(),
407
                        TagIdentifier = row["TagIdentifier"].ToString(),
408
                        AttributeName = row["AttributeName"].ToString(),
409
                        Name = row["Name"].ToString()
410
                    });
411
                }
412
                #endregion
413

    
414
                
415
                DataRow[] pumpRows = PipeSystemNetwork.Select("PUMP = 'PUMP'");
416
                Dictionary<string, string> eqkeyValuePairs = new Dictionary<string, string>();
417
                // 1, 2번
418
                foreach (DataRow dataRow in pumpRows) 
419
                {                  
420
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
421

    
422
                    string EGTAG = "EGTAG";
423
                   // string ItemTag = "ItemTag";
424
                    string EGFlowDirection = string.Empty;
425
                    string Prefix = string.Empty;
426
                    string SymbolName = string.Empty;
427

    
428
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
429
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
430
                    {
431
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
432
                        {
433
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
434
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
435
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null
436
                                   ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
437

    
438
                            SymbolName = PSNItem.Groups.First().Items.First().Equipment.Name;
439
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
440
                            EGFlowDirection = "O";
441
                        }                        
442
                    } 
443
                    
444
                    if(string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
445
                    {
446
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
447
                        {
448
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
449
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
450
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null
451
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
452

    
453
                            SymbolName = PSNItem.Groups.Last().Items.Last().Equipment.Name;
454
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
455
                            EGFlowDirection = "I";
456
                        }
457
                    }
458

    
459
                    //Attribute가 세팅되어있지 않다면
460
                    if (EGTAG.Equals("EGTAG"))
461
                    {
462
                        if (!eqkeyValuePairs.ContainsKey(SymbolName))
463
                        {
464
                            if (!string.IsNullOrEmpty(Prefix))
465
                            {
466
                                pumpTagNum++;
467
                                EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", pumpTagNum));
468
                                eqkeyValuePairs.Add(SymbolName, EGTAG);
469
                            }
470
                            else
471
                            {
472
                                eqkeyValuePairs.Add(SymbolName, SymbolName);
473
                            }
474
                        }
475
                        else
476
                        {
477
                            EGTAG = eqkeyValuePairs[SymbolName];
478
                        }
479
                    }
480
                    else
481
                    {
482
                        if (!string.IsNullOrEmpty(Prefix))
483
                            EGTAG = Prefix + "-" + EGTAG;
484
                    }
485

    
486

    
487
                    foreach (DataRow dr in pathItemRows)
488
                    {
489
                        dr["EqpGroupTag"] = EGTAG;
490
                        dr["EGFlowDirection"] = EGFlowDirection;
491
                    }
492
                }
493

    
494
                // 3, 4번
495
                foreach (DataRow dataRow in pumpRows) 
496
                {
497

    
498
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
499
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
500
                    string EGFlowDirection = string.Empty;
501

    
502
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
503
                    {
504
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
505
                        {
506
                            EGFlowDirection = "O";
507
                        }
508
                    }
509
                    
510
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
511
                    {
512
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
513
                        {
514
                            EGFlowDirection = "I";
515
                        }
516
                    }
517

    
518

    
519
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
520

    
521
                    foreach (DataRow dr in pathItemRows)
522
                    {
523
                        if(dr.Field<string>("ViewPipeSystemNetwork_OID") != dataRow["OID"].ToString())
524
                        {
525
                            string viewEGFlowDirection = string.Empty;
526
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
527
                            {
528
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));                               
529

    
530
                                if (viewPSNItem.Groups.First().Items.First().Equipment != null)
531
                                {
532
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
533
                                    {
534
                                        viewEGFlowDirection = "O";
535
                                    }
536
                                }
537
                                
538
                                
539
                                if (string.IsNullOrEmpty(viewEGFlowDirection) && viewPSNItem.Groups.Last().Items.Last().Equipment != null)
540
                                {
541
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
542
                                    {
543
                                        viewEGFlowDirection = "I";
544
                                    }
545
                                }
546

    
547
                                if (EGFlowDirection.Equals(viewEGFlowDirection) && !lstViewPipeSystemNetwork_OID.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
548
                                    lstViewPipeSystemNetwork_OID.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
549
                            }
550
                            else
551
                            {
552
                            }
553
                        }
554
                    }
555

    
556
                    string selectViewOID = string.Empty;
557

    
558
                    if (EGFlowDirection == "O") //From 이면 시작점에서 제일 먼 값
559
                    {
560
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
561
                        {
562
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
563
                            {                                
564
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
565
                            }
566
                        }
567
                    }
568
                    else if (EGFlowDirection == "I") //To 이면 시작점에서 제일 가까운 값
569
                    {
570
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
571
                        {
572
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
573
                            {
574
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
575
                                break;
576
                            }
577
                        }
578
                    }
579

    
580
                    if (!string.IsNullOrEmpty(selectViewOID)) //selectViewOID 가 있으면
581
                    {              
582
                        string EqpGroupTag = string.Empty;                       
583

    
584
                        if((EGFlowDirection == "O" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.Last().Field<string>("ViewPipeSystemNetwork_OID"))) ||
585
                            (EGFlowDirection == "I" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID"))))
586
                        { 
587
                            DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID")));
588

    
589
                            foreach (DataRow row in viewpathItemRows)
590
                            {
591
                                if (!string.IsNullOrEmpty(row.Field<string>("EqpGroupTag")))
592
                                {
593
                                    EqpGroupTag = row.Field<string>("EqpGroupTag");
594
                                    break;
595
                                }
596
                            }
597

    
598
                            foreach (DataRow dr in pathItemRows)
599
                            {
600
                                dr["EqpGroupTag"] = EqpGroupTag;
601
                            }
602

    
603
                        }
604
                        else
605
                        {
606
                            bool bCheck = false;
607
                            if (EGFlowDirection == "I") //To 일때
608
                            {
609
                                foreach (DataRow dr in pathItemRows)
610
                                {
611
                                    if (selectViewOID == dr["OID"].ToString())
612
                                    {
613
                                        dr["EGTConnectedPoint"] = "1";
614
                                        bCheck = true;
615
                                    }
616

    
617
                                    if (!bCheck)
618
                                    {
619
                                        dr["EqpGroupTag"] = string.Empty;
620
                                        dr["MainLineTag"] = string.Empty;
621
                                        dr["EGTConnectedPoint"] = "0";
622
                                        dr["EGFlowDirection"] = string.Empty;
623
                                    }
624
                                    else
625
                                    {
626
                                        dr["MainLineTag"] = "M";
627
                                    }
628
                                    
629
                                }
630

    
631
                            }
632
                            else if (EGFlowDirection == "O") //From 일 때
633
                            {
634
                                foreach (DataRow dr in pathItemRows)
635
                                {
636
                                    if (bCheck)
637
                                    {
638
                                        
639
                                        dr["EqpGroupTag"] = string.Empty;
640
                                        dr["MainLineTag"] = string.Empty;
641
                                        dr["EGTConnectedPoint"] = "0";
642
                                        dr["EGFlowDirection"] = string.Empty;
643
                                    }
644
                                    else
645
                                    {
646
                                        dr["MainLineTag"] = "M";
647
                                    }
648

    
649
                                    if (selectViewOID == dr["OID"].ToString())
650
                                    {
651
                                        dr["EGTConnectedPoint"] = "1";
652
                                        bCheck = true;
653
                                    }
654
                                }
655
                            }
656
                        }
657
                    }
658
                    else
659
                    {
660
                        //foreach (DataRow dr in pathItemRows)
661
                        //{
662
                        //    dr["EqpGroupTag"] = string.Empty;
663
                        //    dr["EGFlowDirection"] = string.Empty;
664
                        //    dr["EGTConnectedPoint"] = "0";
665
                        //    dr["MainLineTag"] = string.Empty;
666
                        //}
667
                    }
668
                }
669
                                
670
                // 5번
671
                foreach (DataRow dataRow in pumpRows)
672
                {
673
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
674

    
675
                    bool bCheck = false;
676
                    string EqpGroupTag = string.Empty;
677

    
678
                    string EGFlowDirection = string.Empty;                   
679

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

    
682
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
683
                    {
684
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
685
                        {
686
                            EGFlowDirection = "O";
687
                        }
688
                    }
689
                    
690
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
691
                    {
692
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
693
                        {
694
                            EGFlowDirection = "I";
695
                        }
696
                    }
697

    
698
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
699
                    List<string> lstEqTagRows = new List<string>();
700
                    if (EGFlowDirection.Equals("I"))
701
                    {
702
                        foreach (DataRow dr in pathItemRows)
703
                        {                            
704
                            if (!string.IsNullOrEmpty(dr.Field<string>("MainLineTag")) && dr.Field<string>("MainLineTag").Equals("M") && !string.IsNullOrEmpty(dr.Field<string>("EqpGroupTag")))
705
                            {
706
                                bCheck = true;
707
                                EqpGroupTag = dr.Field<string>("EqpGroupTag");
708
                                if(!lstEqTagRows.Contains(EqpGroupTag))
709
                                    lstEqTagRows.Add(EqpGroupTag);
710

    
711
                                if(dataRow["OID"].ToString() != dr.Field<string>("ViewPipeSystemNetwork_OID"))
712
                                {
713
                                    PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));
714
                                    if (viewPSNItem.Groups.Last().Items.Last().Equipment == null)
715
                                        continue;
716

    
717
                                    if (!lstEqTagRows.Contains(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag))
718
                                        lstEqTagRows.Add(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag);
719
                                }
720
                                
721
                            }
722

    
723
                        }
724
                        if(bCheck)
725
                        {
726
                            foreach (DataRow row in pumpRows)
727
                            {
728
                                if (row.Field<string>("OID").Equals(dataRow["OID"].ToString()))
729
                                    continue;
730

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

    
733
                                if (viewPSNItem.Groups.First().Items.First().Equipment == null)
734
                                    continue;
735
                                
736
                                if (lstEqTagRows.Contains(viewPSNItem.Groups.First().Items.First().Equipment.ItemTag) && !lstViewPipeSystemNetwork_OID.Contains(row.Field<string>("OID")))
737
                                    lstViewPipeSystemNetwork_OID.Add(row.Field<string>("OID"));
738
                            }
739

    
740
                                
741

    
742
                            if (lstViewPipeSystemNetwork_OID.Count() > 0)
743
                            {
744
                                foreach (string viewPipesystem in lstViewPipeSystemNetwork_OID)
745
                                {
746
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewPipesystem));
747
                                    foreach (DataRow viewdr in viewpathItemRows)
748
                                    {
749
                                        if (!string.IsNullOrEmpty(viewdr["EqpGroupTag"].ToString()))
750
                                            viewdr["EqpGroupTag"] = EqpGroupTag;
751
                                    }
752
                                }
753
                            }
754
                        }                        
755
                    }                   
756
                }
757
                
758
                int afcTagNum = 0;
759
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
760
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
761
                foreach (DataRow dataRow in airFinCoolerRows)
762
                {
763
                    string EGFlowDirection = string.Empty;
764
                    string EGTAG = "EGTAG";
765
                    string Prefix = string.Empty;
766
                    string SymbolName = string.Empty;
767

    
768
                    //item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
769
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
770
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
771
                    {
772
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
773
                        {
774
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
775
                            if(!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
776
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
777
                                    ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
778

    
779
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
780
                            EGFlowDirection = "O";
781
                        }
782
                    }
783

    
784
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
785
                    {
786
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
787
                        {
788
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
789
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
790
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
791
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
792

    
793
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
794
                            EGFlowDirection = "I";
795
                        }
796
                    }
797

    
798
                    if(!string.IsNullOrEmpty(EGFlowDirection))
799
                    {
800
                        string[] afcTag = dataRow.Field<string>("AFC").Split(new string[] { "\\" }, StringSplitOptions.None);
801

    
802
                        //Attribute가 세팅되어있지 않다면
803
                        if (EGTAG.Equals("EGTAG"))
804
                        {                          
805
                            if (!keyValuePairs.ContainsKey(afcTag[1]))
806
                            {
807
                                if (!string.IsNullOrEmpty(Prefix))
808
                                {
809
                                    afcTagNum++;
810
                                    EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", afcTagNum));
811
                                    keyValuePairs.Add(afcTag[1], EGTAG);
812
                                }
813
                                else
814
                                {
815
                                    keyValuePairs.Add(afcTag[1], afcTag[1]);
816

    
817
                                }
818
                            }
819
                            else
820
                            {
821
                                EGTAG = keyValuePairs[afcTag[1]];
822
                            }
823
                            
824
                        }
825
                        else
826
                        {
827
                            if (!string.IsNullOrEmpty(Prefix))
828
                                EGTAG = Prefix + "-" + EGTAG;                          
829
                        }
830

    
831
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
832
                        foreach (DataRow dr in pathItemRows)
833
                        {
834
                            dr["EqpGroupTag"] = EGTAG;
835
                            dr["EGFlowDirection"] = EGFlowDirection;
836
                        }
837
                    }
838
                    
839
                }
840

    
841
                List<string> changePSN = new List<string>();
842
                foreach (DataRow dataRow in airFinCoolerRows)
843
                {
844
                    if (changePSN.Contains(dataRow["OID"].ToString()))
845
                        continue;
846

    
847
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
848
                    string AFCTag = string.Empty;
849
                    if (pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).Count() > 0)
850
                        AFCTag = pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");
851

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

    
854
                    if (dataRow["Type"].ToString() == "E2E")
855
                    {
856
                        foreach (DataRow dr in pathItemRows)
857
                        {
858
                            dr["MainLineTag"] = "M";
859
                        }
860
                        dataRow["AFC"] = "P3";
861
                    }
862
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
863
                    {
864
                        foreach (string lstoid in lstViewPipeSystemNetwork_OID)
865
                        {
866
                            DataRow[] p2psn = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", lstoid));
867

    
868
                            if (p2psn.Count() > 0)
869
                            {
870
                                DataRow[] viewPathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
871
                                List<string> lstview = viewPathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
872
                                lstview.Remove(dataRow["OID"].ToString()); // P1인 자신 제거
873
                                lstview.Remove(lstoid); // P2 자신 제거
874

    
875
                                List<string> lstnewpipe = new List<string>();
876
                                foreach (string lstvw in lstview) //자신 외 P1이 있는지 확인
877
                                {
878
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID").Equals(lstvw)).Count() > 0) //P1이면 리스트에 추가
879
                                        lstnewpipe.Add(lstvw);
880
                                }
881

    
882
                                if (lstnewpipe.Count() == 0)
883
                                {
884
                                    foreach (DataRow dr in pathItemRows)
885
                                    {
886
                                        dr["MainLineTag"] = "M";
887
                                    }
888
                                    dataRow["AFC"] = "P3";
889
                                }
890
                                else
891
                                {
892
                                    // P2에 ML값 AGT값 지정
893
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
894
                                    DataRow[] pipesystemRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", lstoid));
895
                                    foreach (DataRow viewdr in pipesystemRows)
896
                                    {
897
                                        viewdr["AFC"] = "P4";
898
                                    }
899

    
900
                                    foreach (DataRow viewdr in viewpathItemRows)
901
                                    {
902
                                        viewdr["EqpGroupTag"] = AFCTag;
903
                                        viewdr["MainLineTag"] = "M";
904
                                    }
905
                                    // 연결된 모든 P1들의 AGT값 치환
906
                                    foreach (string pipe in lstnewpipe)
907
                                    {
908
                                        viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipe));
909
                                        foreach (DataRow viewdr in viewpathItemRows)
910
                                        {
911
                                            viewdr["EqpGroupTag"] = AFCTag;
912
                                        }
913
                                    }
914
                                }
915
                            }                               
916
                        }   
917
                    }
918
                }
919
                
920
                //P3을 제외한 P1
921
                airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
922
                foreach (DataRow dataRow in airFinCoolerRows)
923
                {
924
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
925
                    
926
                    if (pathItemRows.Count() > 0)
927
                    {
928
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
929
                        List<string> lstpsn = new List<string>();
930
                        List<string> lstAll = new List<string>();
931
                        string EqpGroupTag = string.Empty;
932
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
933
                        {
934
                            if (dataRow["OID"].ToString() == viewOID)
935
                            {
936
                                lstAll.Add(viewOID);
937
                                continue;
938
                            }
939

    
940
                            //P3이면
941
                            DataRow viewPSN = null;
942
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
943
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
944
                            
945
                            if (viewPSN != null)
946
                            {
947
                                //P3의 AGT를 가져와 P1에 입력
948
                                if(string.IsNullOrEmpty(EqpGroupTag))
949
                                    EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
950

    
951
                                foreach (DataRow dr in pathItemRows)
952
                                {
953
                                    dr["EqpGroupTag"] = EqpGroupTag;
954

    
955
                                    //P1의 AGT와 같은 모든 AGT를 P3의 AGT로 변경하기위해 
956
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
957
                                    {
958
                                        //AND MainLineTag = ''
959
                                        if (PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' ", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
960
                                        {
961
                                            lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
962
                                            lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
963
                                        }
964
                                    }
965
                                }
966
                            }                            
967
                        }
968

    
969
                        while (lstpsn.Count() != 0)
970
                        {                            
971
                            DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstpsn[0]));
972
                            foreach (DataRow dr in rule4pathItems)
973
                            {
974
                                if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstAll.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
975
                                {
976
                                    DataRow viewPSN = null;
977

    
978
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).Count() > 0)
979
                                        viewPSN = airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).First();
980
                                                                        
981
                                    if (viewPSN != null)
982
                                    {
983
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
984
                                        lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
985
                                    }
986
                                }                                
987

    
988
                                dr["EqpGroupTag"] = EqpGroupTag;
989

    
990
                            }
991
                            lstpsn.Remove(lstpsn[0]);
992
                        }
993
                    }
994
                    
995
                }
996

    
997
                foreach(DataRow dr in PipeSystemNetwork.Rows)
998
                {
999
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
1000
                    if(pathItemRows.Count() > 0)
1001
                    {
1002
                        if(dr["Type"].ToString() == "HD2")
1003
                        {
1004
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
1005
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
1006
                            {                              
1007
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
1008
                                {
1009
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
1010
                                    {
1011
                                        dataRow["EGTConnectedPoint"] = "1";
1012
                                    }
1013
                                }
1014
                            }
1015
                        }
1016
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
1017
                        {
1018
                            PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dr["OID"].ToString());
1019
                            string EGFlowDirection = string.Empty;
1020
                            if (PSNItem.Groups.First().Items.First().Equipment != null)
1021
                            {
1022
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
1023
                                {
1024
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
1025
                                    if (equipmentAirFinCoolerItem != null)
1026
                                        EGFlowDirection = "O";
1027
                                }
1028
                            }
1029
                            
1030
                            if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
1031
                            {
1032
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
1033
                                {
1034
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
1035
                                    if(equipmentAirFinCoolerItem != null)
1036
                                        EGFlowDirection = "I";
1037
                                }
1038
                            }
1039

    
1040
                            if (!string.IsNullOrEmpty(EGFlowDirection))
1041
                            {
1042
                                List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
1043
                                string lastP1 = string.Empty;
1044

    
1045
                                foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
1046
                                {
1047
                                    if (viewpsn == dr["OID"].ToString())
1048
                                        continue;
1049

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

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

    
1055
                                    if (rows != null)
1056
                                    {
1057
                                        lastP1 = viewpsn;
1058
                                        if (EGFlowDirection.Equals("I")) // To         
1059
                                            break;
1060
                                    }
1061
                                }
1062

    
1063
                                if (!string.IsNullOrEmpty(lastP1))
1064
                                {
1065
                                    bool bCheck = false;
1066
                                    if (EGFlowDirection.Equals("O")) // From
1067
                                    {
1068
                                        foreach (DataRow dataRow in pathItemRows)
1069
                                        {
1070
                                            if (bCheck)
1071
                                            {
1072
                                                dataRow["EqpGroupTag"] = string.Empty;
1073
                                                dataRow["MainLineTag"] = string.Empty;
1074
                                                dataRow["EGTConnectedPoint"] = 0;
1075
                                                dataRow["EGFlowDirection"] = string.Empty;
1076
                                            }
1077

    
1078
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1079
                                            {
1080
                                                bCheck = true;
1081
                                                dataRow["EGTConnectedPoint"] = 1;
1082
                                            }
1083
                                        }
1084
                                    }
1085
                                    else
1086
                                    {
1087
                                        foreach (DataRow dataRow in pathItemRows)
1088
                                        {
1089
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1090
                                            {
1091
                                                dataRow["EGTConnectedPoint"] = 1;
1092
                                                break;
1093
                                            }
1094
                                            
1095
                                            dataRow["EqpGroupTag"] = string.Empty;
1096
                                            dataRow["MainLineTag"] = string.Empty;
1097
                                            dataRow["EGTConnectedPoint"] = 0;
1098
                                            dataRow["EGFlowDirection"] = string.Empty;
1099

    
1100
                                        }
1101
                                    }
1102
                                }
1103
                            }                          
1104
                        }
1105
                    }
1106
                }
1107

    
1108
                //psn data 정리
1109
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
1110
                {
1111
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
1112
                    string EGTag = string.Empty;
1113
                    string HasMLTags = "False";
1114

    
1115
                    foreach (DataRow dataRow in pathItemRows)
1116
                    {
1117
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
1118
                            EGTag = dataRow.Field<string>("EqpGroupTag");
1119

    
1120
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
1121
                            HasMLTags = "True";
1122

    
1123
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
1124
                            break;
1125
                    }
1126

    
1127
                    pipesystem["EGTag"] = EGTag;
1128
                    pipesystem["HasMLTags"] = HasMLTags;
1129
                }
1130
            }
1131
            catch (Exception ex)
1132
            {
1133
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1134
            }
1135
            //}
1136
        }
1137

    
1138
        private void UpdateValveGrouping()
1139
        {
1140
            try
1141
            {
1142
                #region ValveGrouping Info
1143
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1144
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1145
                foreach (DataRow row in dtValveGroupung.Rows)
1146
                {
1147
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1148
                    {
1149
                        OID = row["OID"].ToString(),
1150
                        GroupType = row["GroupType"].ToString(),
1151
                        TagIdentifier = row["TagIdentifier"].ToString(),
1152
                        AttributeName = row["AttributeName"].ToString(),
1153
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1154
                    });
1155
                }
1156
                #endregion
1157

    
1158

    
1159
                int vgTagNum = 1;
1160
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
1161
                List<string> pathOid = new List<string>();
1162
                foreach (DataRow drPathitem in tagpathItemRows)
1163
                {
1164
                    if (pathOid.Contains(drPathitem.Field<string>("OID")))
1165
                        continue;
1166

    
1167
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
1168
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1169
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
1170
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
1171
                        continue;
1172
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
1173
                    List<Item> valveGroupingItem = new List<Item>();
1174
                    int bCnt = 0;
1175

    
1176
                    
1177
                    List<DataRow> lstitem = new List<DataRow>();
1178
                    foreach (DataRow dr in pathItemRows)
1179
                    {
1180
                        if (dr["GROUPTAG"].ToString() == "Scope Break")
1181
                        {
1182
                            dr["GROUPTAG"] = string.Empty;
1183
                            keyValuePairs.Add(bCnt, lstitem.ToList());
1184
                            bCnt++;
1185
                            lstitem.Clear();
1186
                            continue;
1187
                        }
1188
                       
1189

    
1190
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1191
                        {
1192
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));                          
1193
                           
1194
                            if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
1195
                            {
1196
                                if (lstitem.ToList().Where(x => !string.IsNullOrEmpty(x.Field<string>("GROUPTAG"))).Count() > 0)
1197
                                {
1198
                                    lstitem.Add(dr);
1199
                                    keyValuePairs.Add(bCnt, lstitem.ToList());
1200
                                    lstitem.Clear();
1201
                                }
1202
                                else
1203
                                {
1204
                                    keyValuePairs.Add(bCnt, lstitem.ToList());
1205
                                    lstitem.Clear();
1206
                                    lstitem.Add(dr);
1207
                                }
1208
                                bCnt++;
1209

    
1210
                            }
1211
                            else
1212
                                lstitem.Add(dr);
1213
                            
1214
                        }
1215
                        else
1216
                            lstitem.Add(dr);
1217
                    }
1218

    
1219
                    if (lstitem.Count > 0)
1220
                    {
1221
                        keyValuePairs.Add(bCnt, lstitem);
1222
                    }
1223

    
1224
                    if (keyValuePairs.Count() == 0)
1225
                        continue;
1226

    
1227
                    string VGTag = string.Empty;
1228
                    if (valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
1229
                    {
1230
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1231
                        vgTagNum++;
1232
                    }
1233
                    else
1234
                    {                        
1235
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
1236
                    }
1237

    
1238
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
1239
                    {                       
1240
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
1241
                        {
1242
                            if (!pathOid.Contains(drPathitem.Field<string>("OID")))
1243
                                pathOid.Add(drPathitem.Field<string>("OID"));
1244

    
1245
                            foreach (DataRow dr in keyValuePair.Value)
1246
                            {
1247
                                dr["GROUPTAG"] = VGTag;
1248

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

    
1287
                                        valvetag = drs["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
1288
                                        ValveGroupItem valveitems = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
1289
                                        if (valveitems == null || valveitems.GroupType == "Scope Break")
1290
                                            continue;
1291

    
1292
                                        VGTag = string.Empty;
1293
                                        if (valveitems.AttributeName == "NoSelection" || valveitems.AttributeName == string.Empty)
1294
                                        {
1295
                                            VGTag = valveitems.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1296
                                            vgTagNum++;
1297
                                        }
1298
                                        else
1299
                                        {
1300
                                            VGTag = valveitems.TagIdentifier + "-" + valvetag[1];
1301
                                        }
1302

    
1303
                                        foreach (DataRow dr in keyValuePair.Value)
1304
                                        {
1305
                                            dr["GROUPTAG"] = VGTag;
1306

    
1307
                                            if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1308
                                            {
1309
                                                if (TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1310
                                                {
1311
                                                    DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1312
                                                    foreach (DataRow path in rows)
1313
                                                    {
1314
                                                        DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1315
                                                        if (topology.Field<string>("SubType").Equals("Bypass"))
1316
                                                        {
1317
                                                            DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1318
                                                            if (drPathItem.Where(x => x.Field<string>("GROUPTAG") == "Scope Break").Count() == 0)
1319
                                                            {
1320
                                                                foreach (DataRow pathitem in drPathItem)
1321
                                                                {
1322
                                                                    pathitem["GROUPTAG"] = VGTag;
1323
                                                                }
1324
                                                            }
1325
                                                        }
1326
                                                    }
1327
                                                }
1328
                                            }
1329
                                        }
1330

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

    
1343
                    if(valveitem.GroupType.Contains("PSV"))
1344
                    {
1345
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1346
                        foreach (DataRow row in psnRows)
1347
                            row["Pocket"] = "Yes";
1348
                    }                    
1349
                }
1350

    
1351
                tagpathItemRows = PathItems.Select(string.Format("GROUPTAG = 'Scope Break'"));
1352
                foreach (DataRow drPathitem in tagpathItemRows)
1353
                {
1354
                    drPathitem["GROUPTAG"] = string.Empty;
1355
                }
1356
            }
1357
            catch (Exception ex)
1358
            {
1359
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1360
            }
1361
        }
1362

    
1363
        private void SetTopologyData()
1364
        {
1365
            // 13번 excel
1366
            foreach (Group group in groups)
1367
            {
1368
                LineNumber prevLineNumber = null;
1369
                for (int i = 0; i < group.Items.Count; i++)
1370
                {
1371
                    Item item = group.Items[i];
1372
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1373
                    if (lineNumber == null)
1374
                    {
1375
                        if (prevLineNumber != null)
1376
                        {
1377
                            if (!prevLineNumber.IsCopy)
1378
                            {
1379
                                prevLineNumber = prevLineNumber.Copy();
1380
                                prevLineNumber.MissingLineNumber1 = true;
1381
                                item.Document.LineNumbers.Add(prevLineNumber);
1382
                                //item.LineNumber.MissingLineNumber1 = true;
1383
                            }
1384
                            item.Owner = prevLineNumber.UID;
1385
                        }
1386
                    }
1387
                    else
1388
                        prevLineNumber = lineNumber;
1389
                }
1390

    
1391
                prevLineNumber = null;
1392
                for (int i = group.Items.Count - 1; i > -1; i--)
1393
                {
1394
                    Item item = group.Items[i];
1395
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1396
                    if (lineNumber == null)
1397
                    {
1398
                        if (prevLineNumber != null)
1399
                        {
1400
                            if (!prevLineNumber.IsCopy)
1401
                            {
1402
                                prevLineNumber = prevLineNumber.Copy();
1403
                                prevLineNumber.MissingLineNumber1 = true;
1404
                                item.Document.LineNumbers.Add(prevLineNumber);
1405
                                //item.LineNumber.MissingLineNumber1 = true;                                
1406
                            }
1407

    
1408
                            item.Owner = prevLineNumber.UID;
1409
                        }
1410
                    }
1411
                    else
1412
                        prevLineNumber = lineNumber;
1413
                }
1414

    
1415
                if (prevLineNumber == null)
1416
                {
1417
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1418
                    Random random = new Random();
1419

    
1420
                    LineNumber cLineNumber = null;
1421

    
1422
                    if (lineNumbers.Count == 0)
1423
                    {
1424
                        var _groups = groups.Where(w => w != group).ToList();
1425
                        while (cLineNumber == null)
1426
                        {
1427
                            int _index = random.Next(_groups.Count - 1);
1428
                            List<LineNumber> _lineNumbers = groups[_index].Document.LineNumbers.FindAll(x => !x.IsCopy);
1429
                            if (_lineNumbers.Count != 0)
1430
                            {
1431
                                _index = random.Next(_lineNumbers.Count - 1);
1432

    
1433
                                // Copy
1434
                                cLineNumber = _lineNumbers[_index].Copy();
1435
                            }
1436
                        }
1437
                    }
1438
                    else
1439
                    {
1440
                        int index = random.Next(lineNumbers.Count - 1);
1441

    
1442
                        // Copy
1443
                        cLineNumber = lineNumbers[index].Copy();
1444
                    }
1445

    
1446
                    cLineNumber.MissingLineNumber2 = true;
1447
                    group.Document.LineNumbers.Add(cLineNumber);
1448

    
1449
                    foreach (Item item in group.Items)
1450
                    {
1451
                        item.Owner = cLineNumber.UID;                        
1452
                    }
1453
                }
1454

    
1455
                //if (prevLineNumber == null)
1456
                //{
1457
                //    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1458
                //    Random random = new Random();
1459
                //    int index = random.Next(lineNumbers.Count - 1);
1460

    
1461
                //    // Copy
1462
                //    LineNumber cLineNumber = lineNumbers[index].Copy();
1463
                //    group.Document.LineNumbers.Add(cLineNumber);
1464

    
1465
                //    foreach (Item item in group.Items)
1466
                //    {
1467
                //        item.Owner = cLineNumber.UID;
1468
                //        item.Document.MissingLineNumber2 = true;
1469
                //    }
1470
                //}
1471
            }
1472

    
1473
            foreach (Document document in Documents)
1474
            {
1475
                foreach (Item item in document.Items)
1476
                {
1477
                    item.TopologyData = string.Empty;
1478
                    item.PSNPipeLineID = string.Empty;
1479
                    List<string> pipeLineID = new List<string>();
1480
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1481
                    
1482
                    if (lineNumber != null)
1483
                    {
1484
                        item.LineNumber = lineNumber;
1485

    
1486
                        foreach (DataRow row in topologyRuleDT.Rows)
1487
                        {
1488
                            string uid = row["UID"].ToString();
1489
                            //if (uid == "-")
1490
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1491
                            if (uid != "-")
1492
                            {
1493
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1494

    
1495
                                Attribute attribute = lineNumber.Attributes.Find(x => x.DisplayName == uid);
1496
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1497
                                {
1498
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1499
                                                                    //if (uid.Equals("Tag Seq No") && attribute.Value.ToString().Substring(attribute.Value.ToString().Length - 1, 1).Equals("V"))
1500
                                                                    //{
1501
                                    if (item.LineNumber.MissingLineNumber1 && item.LineNumber.MissingLineNumber2)
1502
                                    {
1503

    
1504
                                    }
1505

    
1506
                                }
1507
                                else
1508
                                {
1509

    
1510
                                }
1511

    
1512
                            }
1513
                        }
1514
                        
1515
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1516
                        {
1517
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1518
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1519
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1520
                                                                 //else
1521
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1522
                        }
1523

    
1524
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1525
                        item.TopologyData = string.Join("-", pipeLineID);
1526
                        
1527
                    }
1528
                    else
1529
                    {
1530
                        item.TopologyData = "Empty LineNumber";
1531
                        item.LineNumber = new LineNumber();
1532
                    }
1533
                }
1534
            }
1535

    
1536
            int emptyIndex = 1;
1537
            foreach (Group group in groups)
1538
            {
1539
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1540
                if (groupItems.Count > 0)
1541
                {
1542
                    foreach (var item in groupItems)
1543
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1544
                    emptyIndex++;
1545
                }
1546
            }
1547

    
1548
        }
1549

    
1550
        private void ConnectByOPC()
1551
        {
1552
            try
1553
            {
1554
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1555
                {
1556
                    Item opcItem = group.Items.Last();
1557
                    if(opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID)) != null)
1558
                    {
1559
                        DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1560
                        if (fromRows.Length.Equals(1))
1561
                        {
1562
                            DataRow opcRow = fromRows.First();
1563
                            string toDrawing = opcRow["ToDrawing"].ToString();
1564
                            string toOPCUID = opcRow["ToOPCUID"].ToString();
1565

    
1566
                            Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1567
                            if (toDocument != null)
1568
                            {
1569
                                Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1570

    
1571
                                if (toGroup != null && opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID)) != null)
1572
                                {
1573
                                    DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1574
                                    //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1575
                                    if (toRows.Length > 1)
1576
                                    {
1577
                                        //throw new Exception("OPC error(multi connect)");
1578
                                        MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1579
                                        return;
1580
                                    }
1581
                                    group.EndGroup = toGroup;
1582
                                    toGroup.StartGroup = group;
1583
                                }
1584

    
1585
                            }
1586
                        }
1587
                    }                    
1588
                }
1589
            }
1590
            catch (Exception ex)
1591
            {
1592
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1593
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1594
            }
1595
        }
1596

    
1597
        private void SetPSNItem()
1598
        {
1599
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1600
            foreach (Group group in groups)
1601
                groupDic.Add(group, Guid.NewGuid().ToString());
1602

    
1603
            foreach (Group group in groups)
1604
            {
1605
                string groupKey = groupDic[group];
1606
                if (group.StartGroup != null)
1607
                {
1608
                    string otherKey = groupDic[group.StartGroup];
1609
                    ChangeGroupID(otherKey, groupKey);
1610
                }
1611
            }
1612

    
1613
            // PSN 정리
1614
            foreach (var item in groupDic)
1615
            {
1616
                Group group = item.Key;
1617
                string uid = item.Value;
1618
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1619
                if (PSNItem == null)
1620
                {
1621
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1622
                    PSNItems.Add(PSNItem);
1623
                }
1624
                PSNItem.Groups.Add(group);
1625
                foreach (Item groupItem in group.Items)
1626
                    groupItem.PSNItem = PSNItem;
1627
            }
1628

    
1629
            // Sort PSN
1630
            foreach (PSNItem PSNItem in PSNItems)
1631
            {
1632
                List<Group> _groups = new List<Group>();
1633

    
1634
                Stack<Group> stacks = new Stack<Group>();
1635
                stacks.Push(PSNItem.Groups.First());
1636
                while (stacks.Count > 0)
1637
                {
1638
                    Group stack = stacks.Pop();
1639
                    if (_groups.Contains(stack))
1640
                        continue;
1641

    
1642
                    if (_groups.Count == 0)
1643
                        _groups.Add(stack);
1644
                    else
1645
                    {
1646
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1647
                        {
1648
                            int index = _groups.IndexOf(stack.StartGroup);
1649
                            _groups.Insert(index + 1, stack);
1650
                        }
1651
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1652
                        {
1653
                            int index = _groups.IndexOf(stack.EndGroup);
1654
                            _groups.Insert(index, stack);
1655
                        }
1656
                    }
1657

    
1658
                    if (stack.StartGroup != null)
1659
                        stacks.Push(stack.StartGroup);
1660
                    if (stack.EndGroup != null)
1661
                        stacks.Push(stack.EndGroup);
1662
                }
1663

    
1664
                PSNItem.Groups.Clear();
1665
                PSNItem.Groups.AddRange(_groups);
1666
            }
1667

    
1668
            void ChangeGroupID(string from, string to)
1669
            {
1670
                if (from.Equals(to))
1671
                    return;
1672

    
1673
                List<Group> changeItems = new List<Group>();
1674
                foreach (var _item in groupDic)
1675
                    if (_item.Value.Equals(from))
1676
                        changeItems.Add(_item.Key);
1677
                foreach (var _item in changeItems)
1678
                    groupDic[_item] = to;
1679
            }
1680
        }
1681

    
1682
        private void SetPSNType()
1683
        {
1684
            foreach (PSNItem PSNItem in PSNItems)
1685
            {
1686
                Group firstGroup = PSNItem.Groups.First();
1687
                Group lastGroup = PSNItem.Groups.Last();
1688

    
1689
                Item firstItem = firstGroup.Items.First();
1690
                Item lastItem = lastGroup.Items.Last();
1691

    
1692
                PSNItem.StartType = GetPSNType(firstItem, true);
1693
                PSNItem.EndType = GetPSNType(lastItem, false);
1694

    
1695
            }
1696

    
1697
            PSNType GetPSNType(Item item, bool bFirst = true)
1698
            {
1699
                PSNType type = PSNType.None;
1700

    
1701
                if (item.ItemType == ItemType.Line)
1702
                {
1703
                    Group group = groups.Find(x => x.Items.Contains(item));
1704
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1705
                    {
1706
                        Item connItem = item.Relations[0].Item;
1707
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1708
                            type = PSNType.Branch;
1709
                        else if (connItem.ItemType == ItemType.Symbol)
1710
                            type = PSNType.Symbol;
1711
                    }
1712
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1713
                    {
1714
                        Item connItem = item.Relations[1].Item;
1715
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1716
                            type = PSNType.Branch;
1717
                        else if (connItem.ItemType == ItemType.Symbol)
1718
                            type = PSNType.Symbol;
1719
                    }
1720
                }
1721
                else if (item.ItemType == ItemType.Symbol)
1722
                {
1723
                    if (item.SubItemType == SubItemType.Nozzle)
1724
                        type = PSNType.Equipment;
1725
                    else if (item.SubItemType == SubItemType.Header)
1726
                        type = PSNType.Header;
1727
                    else if (item.SubItemType == SubItemType.OPC)
1728
                        type = PSNType.OPC;
1729
                    else
1730
                    {
1731
                        Group group = groups.Find(x => x.Items.Contains(item));
1732
                        List<Item> fromItems = item.Relations.Select(w => w.Item).ToList();
1733
                        foreach (var fromItem in fromItems)
1734
                        {
1735
                            if (fromItem != null)
1736
                            {
1737
                                Group _group = groups.Find(x => x.Items.Contains(fromItem));
1738
                                if (_group.UID != group.UID && fromItem.ItemType == ItemType.Symbol)
1739
                                {
1740
                                    type = PSNType.Branch;
1741
                                    break;
1742
                                }
1743
                            }
1744
                        }
1745
                    }
1746
                }
1747

    
1748
                return type;
1749
            }
1750
        }
1751

    
1752
        private void SetBranchInfo()
1753
        {
1754
            foreach (Document document in Documents)
1755
            {
1756
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1757
                foreach (Item line in lines)
1758
                {
1759
                    double[] point = line.Relations[0].Point;
1760
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1761
                    connLines.Sort(SortBranchLine);
1762
                    line.BranchItems.AddRange(connLines);
1763

    
1764
                    int SortBranchLine(Item a, Item b)
1765
                    {
1766
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1767
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1768

    
1769
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1770
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1771

    
1772
                        // 내림차순
1773
                        return distanceA.CompareTo(distanceB);
1774
                    }
1775
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1776
                    {
1777
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1778
                    }
1779
                }
1780

    
1781
                List<Item> symbols = document.Items.FindAll(x => x.ItemType == ItemType.Symbol && x.Relations.Count > 2).ToList();
1782
                foreach (var symbol in symbols)
1783
                {
1784
                    List<Item> connLines = symbol.Relations.FindAll(x => x.Item != null && x.Item.Group != symbol.Group).Select(x => x.Item).ToList();
1785
                    symbol.BranchItems.AddRange(connLines);
1786
                }
1787
            }
1788
        }
1789

    
1790
        private void SetTopology()
1791
        {
1792
            try
1793
            {
1794
                #region 기본 topology 정리
1795
                foreach (PSNItem PSNItem in PSNItems)
1796
                {
1797
                    Topology topology = null;
1798
                    foreach (Group group in PSNItem.Groups)
1799
                    {
1800
                        foreach (Item item in group.Items)
1801
                        {
1802
                            if (string.IsNullOrEmpty(item.TopologyData))
1803
                                topology = null;
1804
                            else
1805
                            {
1806
                                if (topology == null)
1807
                                {
1808
                                    topology = new Topology()
1809
                                    {
1810
                                        ID = item.TopologyData
1811
                                    };
1812
                                    Topologies.Add(topology);
1813

    
1814
                                    if (!PSNItem.Topologies.Contains(topology))
1815
                                        PSNItem.Topologies.Add(topology);
1816
                                }
1817
                                else
1818
                                {
1819
                                    if (topology.ID != item.TopologyData)
1820
                                    {
1821
                                        topology = new Topology()
1822
                                        {
1823
                                            ID = item.TopologyData
1824
                                        };
1825
                                        Topologies.Add(topology);
1826

    
1827
                                        if (!PSNItem.Topologies.Contains(topology))
1828
                                            PSNItem.Topologies.Add(topology);
1829
                                    }
1830
                                }
1831
                                if (topology == null)
1832
                                {
1833

    
1834
                                }
1835
                                item.Topology = topology;
1836
                                topology.Items.Add(item);
1837
                            }
1838
                        }
1839
                    }
1840
                    
1841
                }
1842
                #endregion
1843

    
1844
                #region Type
1845
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1846
                foreach (string id in ids)
1847
                {
1848
                    try
1849
                    {
1850

    
1851

    
1852
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1853

    
1854
                        // Main
1855
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1856
                        foreach (Topology topology in mainTopologies)
1857
                            topology.Type = "M";
1858

    
1859
                        // Branch
1860
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1861
                        foreach (Topology topology in branchToplogies)
1862
                            topology.Type = "B";
1863
                    }
1864
                    catch (Exception ex)
1865
                    {
1866
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1867
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1868
                    }
1869
                }
1870
                #endregion
1871
            }
1872
            catch (Exception ex)
1873
            {
1874
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1875
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1876
            }
1877

    
1878
        }
1879

    
1880
        private void SetTopologyIndex()
1881
        {
1882
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1883
            foreach (string id in ids)
1884
            {
1885
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1886

    
1887
                // Main
1888
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1889
                foreach (Topology topology in mainTopologies)
1890
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1891

    
1892
                // Branch
1893
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1894
                foreach (Topology topology in branchToplogies)
1895
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1896
            }
1897
        }
1898

    
1899
        private void SetPSNBypass()
1900
        {
1901
            foreach (PSNItem PSNItem in PSNItems)
1902
                PSNItem.IsBypass = IsBypass(PSNItem);
1903
        }
1904

    
1905
        private List<Topology> FindMainTopology(List<Topology> data)
1906
        {
1907
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1908
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1909
            //2021.11.17 안쓰네 JY
1910
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1911

    
1912
            List<Topology> main = new List<Topology>();
1913
            main.AddRange(data);
1914
            //
1915
            main = GetNozzleTopology(data);
1916
            if (main.Count == 1)
1917
                return main;
1918
            else
1919
            {
1920
                if (main.Count > 0)
1921
                    main = GetPMCTopology(main);
1922
                else
1923
                    main = GetPMCTopology(data);
1924

    
1925
                if (main.Count == 1)
1926
                    return main;
1927
                else
1928
                {
1929
                    if (main.Count > 0)
1930
                        main = GetDiaTopology(main);
1931
                    else
1932
                        main = GetDiaTopology(data);
1933

    
1934

    
1935
                    if (main.Count == 1)
1936
                        return main;
1937
                    else
1938
                    {
1939
                        if (main.Count > 0)
1940
                            main = GetItemTopology(main);
1941
                        else
1942
                            main = GetItemTopology(data);
1943
                    }
1944
                }
1945
            }
1946

    
1947
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1948
            {
1949
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1950
            }
1951

    
1952
            List<Topology> GetPMCTopology(List<Topology> topologies)
1953
            {
1954
                List<Topology> result = new List<Topology>();
1955
                foreach (DataRow row in PMCDT.Rows)
1956
                {
1957
                    string value = row["CODE"].ToString();
1958
                    foreach (Topology topology in topologies)
1959
                    {
1960
                        foreach (Item item in topology.Items)
1961
                        {
1962
                            if (item.LineNumber == null)
1963
                                continue;
1964
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1965
                            if (attribute != null && value == attribute.Value)
1966
                            {
1967
                                result.Add(topology);
1968
                                break;
1969
                            }
1970
                        }
1971
                    }
1972

    
1973
                    if (result.Count > 0)
1974
                        break;
1975
                }
1976

    
1977
                return result;
1978
            }
1979

    
1980
            List<Topology> GetDiaTopology(List<Topology> topologies)
1981
            {
1982
                List<Topology> result = new List<Topology>();
1983
                foreach (DataRow row in nominalDiameterDT.Rows)
1984
                {
1985
                    string inchValue = row["InchStr"].ToString();
1986
                    string metricValue = row["MetricStr"].ToString();
1987
                    foreach (Topology topology in topologies)
1988
                    {
1989
                        foreach (Item item in topology.Items)
1990
                        {
1991
                            if (item.LineNumber == null)
1992
                                continue;
1993
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1994
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1995
                            {
1996
                                result.Add(topology);
1997
                                break;
1998
                            }
1999
                        }
2000
                    }
2001

    
2002
                    if (result.Count > 0)
2003
                        break;
2004
                }
2005

    
2006
                return result;
2007
            }
2008

    
2009
            List<Topology> GetItemTopology(List<Topology> topologies)
2010
            {
2011
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
2012
            }
2013

    
2014
            return main;
2015
        }
2016

    
2017
        private DataTable GetOPCInfo()
2018
        {
2019
            DataTable opc = DB.SelectOPCRelations();
2020
            DataTable drawing = DB.AllDrawings();
2021

    
2022
            DataTable dt = new DataTable();
2023
            dt.Columns.Add("FromDrawing", typeof(string));
2024
            dt.Columns.Add("FromDrawingUID", typeof(string));
2025
            dt.Columns.Add("FromOPCUID", typeof(string));
2026
            dt.Columns.Add("ToDrawing", typeof(string));
2027
            dt.Columns.Add("ToDrawingUID", typeof(string));
2028
            dt.Columns.Add("ToOPCUID", typeof(string));
2029
            foreach (DataRow row in opc.Rows)
2030
            {
2031
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
2032
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
2033
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
2034
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
2035
                if (!string.IsNullOrEmpty(toOPCUID))
2036
                {
2037
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
2038
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
2039
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
2040
                    {
2041
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
2042
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
2043

    
2044
                        DataRow newRow = dt.NewRow();
2045
                        newRow["FromDrawing"] = fromDrawingName;
2046
                        newRow["FromDrawingUID"] = fromDrawingUID;
2047
                        newRow["FromOPCUID"] = fromOPCUID;
2048
                        newRow["ToDrawing"] = toDrawingName;
2049
                        newRow["ToDrawingUID"] = toDrawingUID;
2050
                        newRow["ToOPCUID"] = toOPCUID;
2051

    
2052
                        dt.Rows.Add(newRow);
2053
                    }
2054
                }
2055
            }
2056

    
2057
            return dt;
2058
        }
2059

    
2060
        private DataTable GetTopologyRule()
2061
        {
2062
            DataTable dt = DB.SelectTopologyRule();
2063

    
2064
            return dt;
2065
        }
2066

    
2067
        private bool IsConnected(Item item1, Item item2)
2068
        {
2069
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
2070
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
2071
                return true;
2072
            else
2073
                return false;
2074
        }
2075

    
2076
        private void SaveNozzleAndEquipment()
2077
        {
2078
            Dictionary<string, int> globalNozzleCount = new Dictionary<string, int>();
2079

    
2080
            List<Item> nozzles = new List<Item>();
2081
            List<Equipment> equipments = new List<Equipment>();
2082
            foreach (Document document in Documents)
2083
            {
2084
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
2085
                equipments.AddRange(document.Equipments);
2086
            }
2087

    
2088
            DataTable equipDT = new DataTable();
2089
            equipDT.Columns.Add("OID", typeof(string));
2090
            equipDT.Columns.Add("ITEMTAG", typeof(string));
2091
            equipDT.Columns.Add("XCOORDS", typeof(string));
2092
            equipDT.Columns.Add("YCOORDS", typeof(string));
2093

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

    
2111
                if (!string.IsNullOrEmpty(equipment.ItemTag))
2112
                {
2113
                    if (!globalNozzleCount.ContainsKey(equipment.ItemTag))
2114
                    {
2115
                        globalNozzleCount[equipment.ItemTag] = 0;
2116
                    }
2117
                }
2118

    
2119
                row["ITEMTAG"] = equipment.ItemTag;
2120
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
2121
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
2122

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

    
2126
                equipDT.Rows.Add(row);
2127
            }
2128

    
2129
            DataTable nozzleDT = new DataTable();
2130
            nozzleDT.Columns.Add("OID", typeof(string));
2131
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
2132
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
2133
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
2134
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
2135
            nozzleDT.Columns.Add("FLUID", typeof(string));
2136
            nozzleDT.Columns.Add("NPD", typeof(string));
2137
            nozzleDT.Columns.Add("PMC", typeof(string));
2138
            nozzleDT.Columns.Add("ROTATION", typeof(string));
2139
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
2140

    
2141
            foreach (Item item in nozzles)
2142
            {
2143
                DataRow row = nozzleDT.NewRow();
2144
                row["OID"] = item.UID;
2145

    
2146
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
2147
                if (relation != null)
2148
                {
2149
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
2150
                    equipment.Nozzles.Add(item);
2151
                    //row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
2152

    
2153
                    int nozzleCount = equipment.Nozzles.Count;
2154
                    if (globalNozzleCount.ContainsKey(equipment.ItemTag))
2155
                    {
2156
                        nozzleCount = globalNozzleCount[equipment.ItemTag];
2157
                    }
2158
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", nozzleCount + 100));
2159
                    if (globalNozzleCount.ContainsKey(equipment.ItemTag))
2160
                    {
2161
                        globalNozzleCount[equipment.ItemTag] += 1;
2162
                    }
2163

    
2164
                    row["Equipment_OID"] = equipment.UID;
2165
                    item.Equipment = equipment;
2166
                }
2167
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
2168
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
2169
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
2170
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
2171
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2172
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
2173
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
2174
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
2175

    
2176
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
2177
                if (angle >= Math.PI * 2)
2178
                    angle = angle - Math.PI * 2;
2179
                row["ROTATION"] = angle.ToString();
2180

    
2181
                if (item.Topology.Items.First().Equals(item))
2182
                    row["FlowDirection"] = "Outlet";
2183
                else if (item.Topology.Items.Last().Equals(item))
2184
                    row["FlowDirection"] = "Inlet";
2185
                else
2186
                    row["FlowDirection"] = string.Empty;
2187

    
2188
                nozzleDT.Rows.Add(row);
2189
            }
2190

    
2191
            //DataTable equipDT = new DataTable();
2192
            //equipDT.Columns.Add("OID", typeof(string));
2193
            //equipDT.Columns.Add("ITEMTAG", typeof(string));
2194
            //equipDT.Columns.Add("XCOORDS", typeof(string));
2195
            //equipDT.Columns.Add("YCOORDS", typeof(string));
2196

    
2197
            //foreach (Equipment equipment in equipments)
2198
            //{
2199
            //    DataRow row = equipDT.NewRow();
2200
            //    row["OID"] = equipment.UID;
2201
            //    if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
2202
            //    {
2203
            //        Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
2204
            //        if (attribute != null)
2205
            //            equipment.ItemTag = attribute.Value;
2206
            //    }
2207
            //    else
2208
            //        equipment.ItemTag = equipment.Name;
2209

    
2210
            //    row["ITEMTAG"] = equipment.ItemTag;
2211
            //    List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
2212
            //    row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
2213

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

    
2217
            //    equipDT.Rows.Add(row);
2218
            //}
2219

    
2220
            Equipment = equipDT;
2221
            Nozzle = nozzleDT;
2222
        }
2223

    
2224
        private void SavePSNData()
2225
        {
2226
            try
2227
            {
2228
                DataTable pathItemsDT = new DataTable();
2229
                pathItemsDT.Columns.Add("OID", typeof(string));
2230
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
2231
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
2232
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
2233
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
2234
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
2235
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
2236
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
2237
                pathItemsDT.Columns.Add("Class", typeof(string));
2238
                pathItemsDT.Columns.Add("SubClass", typeof(string));
2239
                pathItemsDT.Columns.Add("TYPE", typeof(string));
2240
                pathItemsDT.Columns.Add("MULTIWAY", typeof(string));
2241
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
2242
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
2243
                pathItemsDT.Columns.Add("NPD", typeof(string));
2244
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
2245
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
2246
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
2247
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
2248
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
2249
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
2250
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
2251
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
2252

    
2253
                DataTable sequenceDataDT = new DataTable();
2254
                sequenceDataDT.Columns.Add("OID", typeof(string));
2255
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
2256
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
2257
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2258

    
2259
                DataTable pipeSystemNetworkDT = new DataTable();
2260
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
2261
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
2262
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
2263
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
2264
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
2265
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
2266
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2267
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
2268
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
2269
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
2270
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
2271
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
2272
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
2273
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
2274
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
2275
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
2276
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
2277
                pipeSystemNetworkDT.Columns.Add("GroundLevel", typeof(string));
2278
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
2279
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
2280

    
2281
                DataTable topologySetDT = new DataTable();
2282
                topologySetDT.Columns.Add("OID", typeof(string));
2283
                topologySetDT.Columns.Add("Type", typeof(string));
2284
                topologySetDT.Columns.Add("SubType", typeof(string));
2285
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
2286
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
2287
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
2288
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
2289

    
2290
                DataTable pipelineDT = new DataTable();
2291
                pipelineDT.Columns.Add("OID", typeof(string));
2292
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
2293
                pipelineDT.Columns.Add("FLUID", typeof(string));
2294
                pipelineDT.Columns.Add("PMC", typeof(string));
2295
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
2296
                pipelineDT.Columns.Add("INSULATION", typeof(string));
2297
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
2298
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
2299
                pipelineDT.Columns.Add("Unit", typeof(string));
2300

    
2301
                DataTable pipesystemDT = new DataTable();
2302
                pipesystemDT.Columns.Add("OID", typeof(string));
2303
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
2304
                pipesystemDT.Columns.Add("FLUID", typeof(string));
2305
                pipesystemDT.Columns.Add("PMC", typeof(string));
2306
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
2307
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
2308

    
2309
                // Set Vent/Drain Info
2310
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
2311
                DataTable dt = DB.SelectVentDrainSetting();
2312
                foreach (DataRow row in dt.Rows)
2313
                {
2314
                    string groupID = row["GROUP_ID"].ToString();
2315
                    string desc = row["DESCRIPTION"].ToString();
2316
                    int index = Convert.ToInt32(row["INDEX"]);
2317
                    string name = row["NAME"].ToString();
2318

    
2319
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
2320
                    if (ventDrainInfo == null)
2321
                    {
2322
                        ventDrainInfo = new VentDrainInfo(groupID);
2323
                        ventDrainInfo.Description = desc;
2324
                        VentDrainInfos.Add(ventDrainInfo);
2325
                    }
2326

    
2327
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
2328
                    {
2329
                        Index = index,
2330
                        Name = name
2331
                    });
2332
                }
2333
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2334
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
2335

    
2336
                #region Keyword Info
2337
                KeywordInfo KeywordInfos = new KeywordInfo();
2338
                DataTable dtKeyword = DB.SelectKeywordsSetting();
2339
                foreach (DataRow row in dtKeyword.Rows)
2340
                {
2341
                    int index = Convert.ToInt32(row["INDEX"]);
2342
                    string name = row["NAME"].ToString();
2343
                    string keyword = row["KEYWORD"].ToString();
2344

    
2345
                    //KeywordInfo keywordInfo = new KeywordInfo();   
2346
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
2347
                    {
2348
                        Index = index,
2349
                        Name = name,
2350
                        Keyword = keyword
2351
                    });
2352
                }
2353
                #endregion
2354

    
2355
                #region ValveGrouping Info
2356
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
2357
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
2358
                foreach (DataRow row in dtValveGroupung.Rows)
2359
                {
2360
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
2361
                    {
2362
                        OID = row["OID"].ToString(),
2363
                        GroupType = row["GroupType"].ToString(),
2364
                        TagIdentifier = row["TagIdentifier"].ToString(),
2365
                        AttributeName = row["AttributeName"].ToString(),
2366
                        SppidSymbolName = row["SppidSymbolName"].ToString()
2367
                    });
2368
                }
2369
                #endregion
2370

    
2371
                #region EquipmentNoPocket Info
2372
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
2373
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
2374
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
2375
                {
2376
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
2377
                    {
2378
                        Index = Convert.ToInt32(row["INDEX"]),
2379
                        Type = row["TYPE"].ToString(),
2380
                        Name = row["NAME"].ToString()
2381
                    });
2382
                }
2383
                #endregion
2384

    
2385
                #region EquipmentAirFinCooler Info
2386
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
2387
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
2388
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
2389
                {
2390
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
2391
                    {
2392
                        Type = row["Type"].ToString(),
2393
                        Name = row["Name"].ToString()
2394
                    });
2395
                }
2396
                #endregion
2397

    
2398
                // key = 미입력 branch
2399
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
2400
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
2401
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
2402
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
2403
                foreach (PSNItem PSNItem in PSNItems)
2404
                {
2405
                    try
2406
                    {
2407
                        int psnOrder = 0;
2408
                        int index = 0;
2409
                        bool bPSNStart = true;
2410
                        string sPSNData = string.Empty;
2411
                        bool bVentDrain = false;
2412

    
2413
                        List<Group> Groups = PSNItem.Groups;
2414
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
2415
                        List<Item> valveGroupingItem = new List<Item>();
2416

    
2417
                        //VentDrain 검사
2418
                        if (PSNItem.Groups.Count.Equals(1))
2419
                        {
2420
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
2421
                            for (int g = 0; g < Groups.Count; g++)
2422
                            {
2423
                                Group group = Groups[g];
2424

    
2425
                                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2426
                                {
2427
                                    if(!bVentDrain)
2428
                                    {
2429
                                        for (int i = 0; i < group.Items.Count; i++)
2430
                                        {
2431
                                            Item item = group.Items[i];
2432
                                            if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2433
                                                endInfos.Add(ventDrainInfo);
2434
                                            else
2435
                                            {
2436
                                                endInfos.Clear();
2437
                                                if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2438
                                                    endInfos.Add(ventDrainInfo);
2439
                                            }
2440

    
2441
                                            if (ventDrainInfo.VentDrainItems.Count().Equals(endInfos.Count()))
2442
                                            {
2443
                                                bVentDrain = true;
2444
                                                break;
2445
                                            }
2446
                                        }
2447
                                    }                                   
2448
                                }                               
2449

    
2450
                                if (!bVentDrain)
2451
                                {
2452
                                    endInfos = new List<VentDrainInfo>();
2453

    
2454
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2455
                                    {
2456
                                        if (!bVentDrain)
2457
                                        {
2458
                                            for (int i = 0; i < group.Items.Count; i++)
2459
                                            {
2460
                                                Item item = group.Items[group.Items.Count - i - 1];
2461

    
2462
                                                if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2463
                                                    endInfos.Add(ventDrainInfo);
2464
                                                else
2465
                                                {
2466
                                                    endInfos.Clear();
2467
                                                    if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2468
                                                        endInfos.Add(ventDrainInfo);
2469
                                                }
2470

    
2471
                                                if (ventDrainInfo.VentDrainItems.Count().Equals(endInfos.Count()))
2472
                                                {
2473
                                                    bVentDrain = true;
2474
                                                    break;
2475
                                                }
2476
                                            }
2477
                                        }
2478
                                    }
2479
                                }
2480
                            }
2481
                        }
2482

    
2483
                        try
2484
                        {
2485
                            foreach (Group group in PSNItem.Groups)
2486
                            {
2487
                                foreach (Item item in group.Items)
2488
                                {
2489
                                    string VgTag = string.Empty;
2490
                                    
2491
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
2492
                                    {
2493
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
2494
                                        string value = string.Empty;
2495

    
2496
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
2497
                                            value = "NoSelection";
2498
                                        else
2499
                                        {
2500
                                            if(item.Attributes.Find(x => x.Name == valveitem.AttributeName) == null)
2501
                                                value = "NoSelection";
2502
                                            else
2503
                                                value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
2504
                                        }
2505

    
2506
                                        if (valveitem.GroupType == "Scope Break")
2507
                                            VgTag = "Scope Break";
2508
                                        else
2509
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
2510

    
2511
                                    }
2512

    
2513
                                    string PathitemUID = string.Empty;
2514
                                    if (item.BranchItems.Count == 0)
2515
                                    {
2516
                                        PathitemUID = item.UID;
2517
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2518
                                        CreateSequenceDataDataRow(PathitemUID);
2519
                                        index++;
2520
                                    }
2521
                                    else
2522
                                    {
2523
                                        if (item.ItemType == ItemType.Line)
2524
                                        {
2525
                                            PathitemUID = item.UID + "_L1";
2526
                                            CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2527
                                            CreateSequenceDataDataRow(PathitemUID);
2528
                                            index++;
2529
                                            for (int i = 0; i < item.BranchItems.Count; i++)
2530
                                            {
2531
                                                CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
2532
                                                CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
2533
                                                index++;
2534

    
2535
                                                CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
2536
                                                CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
2537
                                                index++;
2538

    
2539
                                                if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
2540
                                                    startBranchDic.Add(item.BranchItems[i], item);
2541
                                                else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
2542
                                                    endBranchDic.Add(item.BranchItems[i], item);
2543
                                            }
2544
                                        }
2545
                                        else
2546
                                        {
2547
                                            PathitemUID = item.UID + "_M1";
2548
                                            
2549
                                            dicMultiwaySymbolUID.Add(item.UID, 1); // 에러나면 이상한거임
2550

    
2551
                                            CreatePathItemsDataRow(PathitemUID, item.ID2DBType, multiwaysymbol: true);
2552
                                            CreateSequenceDataDataRow(PathitemUID);
2553
                                            index++;
2554

    
2555
                                            for (int i = 0; i < item.BranchItems.Count; i++)
2556
                                            {
2557
                                                if (item.BranchItems[i].ItemType == ItemType.Line)
2558
                                                {
2559
                                                    if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
2560
                                                        startBranchDic.Add(item.BranchItems[i], item);
2561
                                                    else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
2562
                                                        endBranchDic.Add(item.BranchItems[i], item);
2563
                                                }
2564
                                                else if (item.BranchItems[i].ItemType == ItemType.Symbol)
2565
                                                {
2566
                                                    Group _group = groups.Find(x => x.Items.Select(w => w.UID).Contains(item.BranchItems[i].UID));
2567
                                                    if (_group != null)  //심볼로 끝났을 경우 그룹이없어서 생성
2568
                                                    {
2569
                                                        if (_group.Items.First() == item.BranchItems[i])
2570
                                                            startBranchDic.Add(item.BranchItems[i], item);
2571
                                                        else if (_group.Items.Last() == item.BranchItems[i])
2572
                                                            endBranchDic.Add(item.BranchItems[i], item);
2573
                                                    }
2574
                                                    else
2575
                                                    {
2576
                                                        Log.Write("Error Item : " + item.BranchItems[i].UID);
2577
                                                    }
2578
                                                }
2579
                                            }
2580
                                        }
2581
                                    }
2582

    
2583
                                    if (bPSNStart)
2584
                                    {
2585
                                        CreatePipeSystemNetworkDataRow();
2586
                                        sPSNData = item.TopologyData;
2587
                                        psnOrder++;
2588
                                        bPSNStart = false;
2589
                                    }
2590
                                    else
2591
                                    {
2592
                                        if (item.TopologyData != sPSNData)
2593
                                        {
2594
                                            CreatePipeSystemNetworkDataRow();
2595
                                            sPSNData = item.TopologyData;
2596
                                            psnOrder++;
2597
                                        }
2598
                                    }
2599

    
2600
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null, bool multiwaysymbol = false)
2601
                                    {
2602
                                        DataRow newRow = pathItemsDT.NewRow();
2603

    
2604
                                        if (itemType == "Nozzles")
2605
                                        {
2606
                                            newRow["Equipment_OID"] = item.Equipment != null ? item.Equipment.UID : "";
2607
                                        }
2608

    
2609
                                        //string topologyFullName = 
2610

    
2611
                                        newRow["OID"] = itemOID;
2612
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2613
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
2614
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2615
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2616

    
2617
                                        if(multiwaysymbol)
2618
                                        {
2619
                                            if (!dicMultiwaySymbolNameTag.ContainsKey(item.Name))
2620
                                            {
2621
                                                dicMultiwaySymbolNameTag.Add(item.Name, 1);
2622
                                                
2623
                                            }
2624

    
2625
                                            newRow["MULTIWAY"] = string.Format("M_" + item.Name + "_{0:D3}", dicMultiwaySymbolNameTag[item.Name]);
2626
                                            dicMultiwaySymbolNameTag[item.Name] = dicMultiwaySymbolNameTag[item.Name] + 1;
2627
                                        }
2628

    
2629

    
2630
                                        if (item.Name.ToUpper().Equals("TIEINPOINT"))
2631
                                        {                                            
2632
                                            newRow["ITEMNAME"] = "PipingComp";
2633

    
2634
                                            string value = string.Empty;
2635
                                            if (string.IsNullOrEmpty(TieInPointAttributeName))
2636
                                                value = string.Format("TIEINPOINT_{0:D3}", tieInPointSymbolIndex);
2637
                                            else
2638
                                                value = item.Attributes.Find(x => x.Name == TieInPointAttributeName).Value;
2639

    
2640

    
2641
                                            newRow["ITEMTAG"] = value;
2642
                                            newRow["DESCRIPTION"] = value;
2643
                                            newRow["Class"] = "In-Line Fitting";
2644
                                            newRow["SubClass"] = "";
2645
                                            newRow["TYPE"] = "End";
2646
                                            tieInPointSymbolIndex++;
2647
                                        }
2648
                                        else
2649
                                        {
2650
                                            newRow["ITEMNAME"] = GetItemName(item, itemOID);
2651
                                            newRow["ITEMTAG"] = GetItemTag(item);
2652
                                            newRow["Class"] = GetClass(item, itemOID);
2653
                                            string subClass = GetSubClass(item, itemOID);
2654
                                            newRow["SubClass"] = subClass;
2655

    
2656
                                            if (item.ItemType == ItemType.Symbol)
2657
                                                newRow["TYPE"] = item.ID2DBName;
2658
                                            else if (item.ItemType == ItemType.Line)
2659
                                                newRow["TYPE"] = item.ID2DBType;
2660
                                        }
2661
                                       
2662
                                        
2663
                                       
2664
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2665

    
2666
                                        // NPD
2667
                                        if (item.LineNumber != null)
2668
                                        {
2669
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2670
                                            if (attribute != null)
2671
                                                newRow["NPD"] = attribute.Value;
2672
                                        }
2673
                                        else
2674
                                            newRow["NPD"] = null;
2675

    
2676
                                        newRow["GROUPTAG"] = GROUPTAG;
2677
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2678
                                        if (branchItem == null)
2679
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2680
                                        else
2681
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2682

    
2683
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2684
                                        newRow["EGTConnectedPoint"] = 0;
2685
                                        pathItemsDT.Rows.Add(newRow);
2686
                                    }
2687

    
2688

    
2689
                                    void CreateSequenceDataDataRow(string itemOID)
2690
                                    {
2691
                                        DataRow newRow = sequenceDataDT.NewRow();
2692
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2693
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2694
                                        newRow["PathItem_OID"] = itemOID;
2695
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2696

    
2697
                                        sequenceDataDT.Rows.Add(newRow);
2698
                                    }
2699

    
2700
                                    void CreatePipeSystemNetworkDataRow()
2701
                                    {
2702
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2703
                                        string FluidCode = string.Empty;
2704
                                        string GroundLevel = string.Empty;
2705
                                        if (lineNumber != null)
2706
                                        {
2707
                                            List<Attribute> att = lineNumber.Attributes;
2708
                                            if (att != null)
2709
                                            {
2710
                                                List<string> oid = new List<string>();
2711
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2712
                                                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;
2713
                                                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;
2714
                                                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;
2715
                                                //InsulationPurpose
2716
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2717
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2718

    
2719
                                                string PipeSystem_OID = string.Join("-", oid);
2720

    
2721
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2722
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2723

    
2724
                                                string OID = string.Join("-", oid);
2725
                                                string FluidCodeGL = string.Empty;
2726
                                                string PMCGL = string.Empty;
2727

    
2728
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2729
                                                {
2730
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2731
                                                    newPipelineRow["OID"] = OID;
2732
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2733
                                                    newPipelineRow["FLUID"] = FluidCode;
2734
                                                    newPipelineRow["PMC"] = PMC;
2735
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2736
                                                    newPipelineRow["INSULATION"] = INSULATION;
2737
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2738
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2739
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2740
                                                    pipelineDT.Rows.Add(newPipelineRow);
2741
                                                }
2742

    
2743
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2744
                                                {
2745
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2746
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2747
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2748
                                                    newPipesystemRow["FLUID"] = FluidCode;
2749
                                                    newPipesystemRow["PMC"] = PMC;
2750
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2751
                                                    
2752
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2753
                                                    {
2754
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2755
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2756
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2757
                                                            GroundLevel = "AG";
2758
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2759
                                                            GroundLevel = "UG";
2760
                                                        else
2761
                                                            GroundLevel = "AG_UG";
2762
                                                    }
2763
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2764
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2765
                                                }
2766
                                                else
2767
                                                {
2768
                                                    GroundLevel = pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).First().Field<string>("GroundLevel");
2769
                                                }
2770
                                            }
2771
                                        }
2772

    
2773
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2774
                                        newRow["OID"] = PSNItem.PSN_OID();
2775

    
2776
                                        newRow["OrderNumber"] = psnOrder;
2777
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2778
                                        PSNItem.KeywordInfos = KeywordInfos;
2779
                                        PSNItem.Nozzle = Nozzle;
2780

    
2781
                                        string FromType = string.Empty;
2782
                                        Item From_item = new Item();
2783

    
2784
                                        string oStatus = string.Empty;
2785
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item, item, ref oStatus);
2786
                                        string status = string.Empty;
2787
                                        if (psnOrder == 0)
2788
                                            status = PSNItem.Status;
2789

    
2790
                                        if (PSNItem.IsKeyword)
2791
                                        {
2792
                                            PSNItem.StartType = PSNType.Equipment;
2793
                                        }
2794
                                        string ToType = string.Empty;
2795
                                        Item To_item = new Item();
2796
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item, item);
2797
                                        if (PSNItem.IsKeyword)
2798
                                        {
2799
                                            PSNItem.EndType = PSNType.Equipment;
2800
                                        }
2801
                                                   
2802
                                        newRow["FROM_DATA"] = FROM_DATA;
2803
                                        newRow["TO_DATA"] = TO_DATA;
2804
                                       
2805
                                        newRow["Type"] = PSNItem.GetPSNType();
2806

    
2807
                                        if (psnOrder == 0) //order 0일땐 그냥 붙여줌
2808
                                        {
2809
                                           status += oStatus + PSNItem.Status;                                                                                      
2810
                                        }
2811
                                        else if (psnOrder > 0) //0보다 크면 
2812
                                        {
2813
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2814
                                            
2815
                                            if (psnOrder >= 1) 
2816
                                            {
2817
                                                if (!string.IsNullOrEmpty(PSNItem.Status))
2818
                                                {
2819
                                                    if (dr["Status"].ToString().Contains(PSNItem.Status))
2820
                                                    {
2821
                                                        dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
2822
                                                    }
2823
                                                    else
2824
                                                    {
2825
                                                        dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
2826
                                                    }    
2827
                                                }
2828
                                            }                                                                                    
2829
                                            
2830
                                            status = oStatus + PSNItem.Status;
2831
                                            if (dr != null)
2832
                                            {
2833
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2834
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2835
                                                newRow["Type"] = dr.Field<string>("Type");
2836
                                            }
2837
                                        }                                        
2838
                                    
2839
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2840
                                        string[] st = status.Split(new string[] { ", " }, StringSplitOptions.None);
2841
                                        if (st.Count() > 1)
2842
                                        {
2843
                                            status = string.Join(", ", st.Distinct());                                                                                     
2844
                                        }
2845
                                        newRow["Status"] = status;
2846
                                        newRow["IsValid"] = PSNItem.IsValid;
2847

    
2848
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2849
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);                                                                           
2850
                                        newRow["PBS"] = PSNItem.GetPBSData();
2851

    
2852
                                        List<string> drawingNames = new List<string>();
2853
                                        foreach (Group _group in PSNItem.Groups)
2854
                                        {
2855
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2856
                                            {
2857
                                                if (drawingNames.Count == 0)
2858
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2859
                                                else
2860
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2861
                                                drawingNames.Add(_group.Document.DrawingName);
2862
                                            }
2863
                                        }
2864

    
2865
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2866
                                        if (bVentDrain)
2867
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2868
                                        else
2869
                                            newRow["IncludingVirtualData"] = "No";
2870
                                       
2871
                                        newRow["PSNAccuracy"] = "100";
2872

    
2873
                                        string Pocket = "No";
2874
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2875
                                        if (Condition.Equals("Flare"))
2876
                                            Pocket = "Yes";
2877

    
2878
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null) 
2879
                                        {
2880
                                            Equipment Equipment = From_item.Equipment;                                      
2881
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2882
                                          
2883
                                            if (nopocket != null)
2884
                                            {
2885
                                                DataRow bNozzle = null;
2886
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2887
                                                {
2888
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2889
                                                    if (drNozzle != null)
2890
                                                    {
2891
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2892
                                                        {
2893
                                                            bNozzle = drNozzle;
2894
                                                        }
2895

    
2896
                                                        if (bNozzle == null)
2897
                                                        {
2898
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2899

    
2900
                                                            if (drNozzle != null)
2901
                                                            {
2902
                                                                bNozzle = drNozzle;
2903
                                                                foreach (DataRow it in nozzleRows)
2904
                                                                {
2905
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2906
                                                                    {
2907
                                                                        bNozzle = null;
2908
                                                                        break;
2909
                                                                    }
2910
                                                                }
2911
                                                            }
2912
                                                        }
2913
                                                    }
2914

    
2915
                                                    if (bNozzle != null)
2916
                                                        Pocket = "Yes";
2917
                                                }
2918
                                                else
2919
                                                    Pocket = "Yes";
2920
                                            }
2921
                                        }
2922
                                        
2923
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null) //To는 전체
2924
                                        {
2925
                                            Equipment Equipment = To_item.Equipment;
2926
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2927
                                            if (nopocket != null)
2928
                                            {
2929
                                                DataRow bNozzle = null;
2930
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2931
                                                {
2932
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2933
                                                    if(drNozzle != null)
2934
                                                    {
2935
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2936
                                                        {
2937
                                                            bNozzle = drNozzle;
2938
                                                        }
2939

    
2940
                                                        if (bNozzle == null)
2941
                                                        {
2942
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2943

    
2944
                                                            if (drNozzle != null)
2945
                                                            {
2946
                                                                bNozzle = drNozzle;
2947
                                                                foreach (DataRow it in nozzleRows)
2948
                                                                {
2949
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2950
                                                                    {
2951
                                                                        bNozzle = null;
2952
                                                                        break;
2953
                                                                    }
2954
                                                                }
2955
                                                            }
2956
                                                        }
2957
                                                    }                                                   
2958

    
2959
                                                    if (bNozzle != null)
2960
                                                        Pocket = "Yes";
2961
                                                }
2962
                                                else
2963
                                                    Pocket = "Yes";
2964
                                            }
2965
                                        }
2966
                                        
2967
                                        newRow["Pocket"] = Pocket;
2968
                                        string AFC = "P2";
2969
                                        if (PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2970
                                        {
2971
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2972
                                                AFC = "P1\\" + From_item.Equipment.Name;
2973
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2974
                                                newRow["PUMP"] = "PUMP";
2975
                                        }
2976

    
2977
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2978
                                        {
2979
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2980
                                                AFC = "P1\\" + To_item.Equipment.Name;
2981
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2982
                                                newRow["PUMP"] = "PUMP";
2983
                                        }
2984

    
2985
                                        newRow["AFC"] = AFC;
2986

    
2987
                                        newRow["EGTag"] = string.Empty;
2988
                                        newRow["HasMLTags"] = "False";
2989
                                        newRow["GroundLevel"] = GroundLevel;
2990
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2991
                                    }
2992
                                }
2993
                            }                      
2994
                        }
2995
                        catch (Exception ex)
2996
                        {
2997
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2998
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2999
                        }
3000

    
3001
                        //TopologySet 관련
3002
                        foreach (Topology topology in PSNItem.Topologies)
3003
                        {
3004
                            DataRow newRow = topologySetDT.NewRow();
3005
                            newRow["OID"] = topology.FullName;
3006
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
3007
                            if (bVentDrain)
3008
                                newRow["SubType"] = "Vent_Drain";
3009
                            else
3010
                                newRow["SubType"] = null;
3011
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
3012
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
3013
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
3014
                            newRow["TailItemSPID"] = topology.Items.First().UID;
3015
                            topologySetDT.Rows.Add(newRow);
3016
                        }
3017

    
3018
                    }
3019
                    catch (Exception ee)
3020
                    {
3021

    
3022
                    }
3023
                }
3024

    
3025

    
3026
                foreach (var item in startBranchDic)
3027
                {
3028
                    string uid = item.Key.UID;
3029
                    string topologyName = item.Value.Topology.FullName;
3030
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
3031

    
3032
                    if (rows.Length == 1)
3033
                    {
3034
                        rows.First()["BranchTopologySet_OID"] = topologyName;
3035
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
3036
                    }
3037
                    else if (rows.Length > 1)
3038
                    {
3039
                        DataRow targetRow = null;
3040
                        int index = int.MaxValue;
3041
                        foreach (DataRow row in rows)
3042
                        {
3043
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
3044
                            if (split.StartsWith("L"))
3045
                            {
3046
                                int num = Convert.ToInt32(split.Remove(0, 1));
3047
                                if (index > num)
3048
                                {
3049
                                    index = num;
3050
                                    targetRow = row;
3051
                                }
3052
                            }
3053
                        }
3054

    
3055
                        if (targetRow != null)
3056
                        {
3057
                            targetRow["BranchTopologySet_OID"] = topologyName;
3058
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
3059
                        }
3060
                    }
3061
                }
3062

    
3063
                foreach (var item in endBranchDic)
3064
                {
3065
                    string uid = item.Key.UID;
3066
                    string topologyName = item.Value.Topology.FullName;
3067
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
3068
                    if (rows.Length == 1)
3069
                    {
3070
                        rows.First()["BranchTopologySet_OID"] = topologyName;
3071
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
3072
                    }
3073
                    else if (rows.Length > 1)
3074
                    {
3075
                        DataRow targetRow = null;
3076
                        int index = int.MinValue;
3077
                        foreach (DataRow row in rows)
3078
                        {
3079
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
3080
                            if (split.StartsWith("L"))
3081
                            {
3082
                                int num = Convert.ToInt32(split.Remove(0, 1));
3083
                                if (index < num)
3084
                                {
3085
                                    index = num;
3086
                                    targetRow = row;
3087
                                }
3088
                            }
3089
                        }
3090

    
3091
                        if (targetRow != null)
3092
                        {
3093
                            targetRow["BranchTopologySet_OID"] = topologyName;
3094
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
3095
                        }
3096
                    }
3097
                }
3098

    
3099
                PathItems = pathItemsDT;
3100
                SequenceData = sequenceDataDT;
3101
                PipeSystemNetwork = pipeSystemNetworkDT;
3102
                TopologySet = topologySetDT;
3103
                PipeLine = pipelineDT;
3104
                PipeSystem = pipesystemDT;
3105
            }
3106
            catch (Exception ex)
3107
            {
3108
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3109
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
3110
            }
3111
        }
3112

    
3113
        private double AccuracyCalculation(List<double> lstAcc, double acc)
3114
        {
3115
            foreach (double lacc in lstAcc)
3116
            {
3117
                acc *= lacc;
3118
            }
3119
            return acc;
3120
        }
3121

    
3122
        private void UpdateSubType()
3123
        {
3124
            try
3125
            {
3126
                foreach (PSNItem PSNItem in PSNItems)
3127
                {
3128
                    if (PSNItem.IsBypass)
3129
                    {
3130
                        foreach (Topology topology in PSNItem.Topologies)
3131
                        {
3132
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
3133
                            if (rows.Length.Equals(1))
3134
                                rows.First()["SubType"] = "Bypass";
3135
                        }
3136
                    }
3137

    
3138
                    if (PSNItem.StartType == PSNType.Header)
3139
                    {
3140
                        Topology topology = PSNItem.Topologies.First();
3141
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
3142
                        if (rows.Length.Equals(1))
3143
                            rows.First()["SubType"] = "Header";
3144
                    }
3145
                    else if (PSNItem.EndType == PSNType.Header)
3146
                    {
3147
                        Topology topology = PSNItem.Topologies.Last();
3148
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
3149
                        if (rows.Length.Equals(1))
3150
                            rows.First()["SubType"] = "Header";
3151
                    }
3152
                }
3153

    
3154

    
3155
                foreach (Topology topology in Topologies)
3156
                {
3157
                    try
3158
                    {
3159
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
3160

    
3161
                        if (rows.Count() > 0)
3162
                        {
3163
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
3164
                            {
3165
                                if (topology.Items == null)
3166
                                    continue;
3167

    
3168
                                Item firstItem = topology.Items.First();
3169
                                Item lastItem = topology.Items.Last();
3170

    
3171
                                List<Relation> relations = new List<Relation>();
3172

    
3173
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0 && firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology != null && x.Item.Topology.ID != topology.ID) != null )
3174
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology != null && x.Item.Topology.ID != topology.ID));
3175

    
3176
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0 && lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology != null && x.Item.Topology.ID != topology.ID) != null)
3177
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology != null && x.Item.Topology.ID != topology.ID));
3178

    
3179
                                if (relations.Count > 0)
3180
                                    rows.First()["SubType"] = "OtherSystem";
3181
                            }
3182
                        }
3183
                    }
3184
                    catch (Exception ex)
3185
                    {
3186

    
3187
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
3188
                    }
3189
                }
3190

    
3191
                foreach (DataRow row in TopologySet.Rows)
3192
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
3193
                        row["SubType"] = "Normal";
3194
            }
3195
            catch (Exception ex)
3196
            {
3197
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3198
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
3199
            }
3200
        }
3201

    
3202
        private bool IsBypass(PSNItem PSNItem)
3203
        {
3204
            bool bResult = false;
3205

    
3206
            if (PSNItem.GetPSNType() == "B2B")
3207
            {
3208
                Group firstGroup = PSNItem.Groups.First();
3209
                Group lastGroup = PSNItem.Groups.Last();
3210
                Item firstItem = firstGroup.Items.First();
3211
                Item lastItem = lastGroup.Items.Last();
3212

    
3213
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
3214
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
3215

    
3216
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
3217
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
3218
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
3219
                    bResult = true;
3220
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
3221
                    bResult = true;
3222
            }
3223

    
3224
            Item GetConnectedItemByPSN(Item item)
3225
            {
3226
                Item result = null;
3227

    
3228
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
3229
                if (relation != null)
3230
                    result = relation.Item;
3231

    
3232

    
3233
                return result;
3234
            }
3235

    
3236
            return bResult;
3237
        }
3238

    
3239
        private void DeleteVentDrain()
3240
        {
3241
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
3242

    
3243
            foreach (DataRow dataRow in ventdrainRows)
3244
            {
3245
                dataRow.Delete();
3246
            }
3247
        }
3248

    
3249
        private void UpdateAccuracy()
3250
        {
3251
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
3252
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
3253
            List<double> lstAcc = null;
3254
            string Status = string.Empty;
3255

    
3256
            foreach (DataRow dataRow in statusRows)
3257
            {
3258
                lstAcc = new List<double>();
3259
                Status = dataRow.Field<string>("Status");
3260
                if (!string.IsNullOrEmpty(Status))
3261
                {
3262
                    string[] arrStatus = Status.Split(',');
3263
                    foreach (string arrstr in arrStatus)
3264
                    {
3265
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
3266
                            lstAcc.Add(0.75);
3267

    
3268
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
3269
                            lstAcc.Add(0.7);
3270

    
3271
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
3272
                            lstAcc.Add(0.5);
3273

    
3274
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
3275
                            lstAcc.Add(0.65);
3276

    
3277
                        if (arrstr.Contains(Rule5)) //Line Disconnected
3278
                            lstAcc.Add(0.6);
3279
                    }
3280
                }
3281

    
3282
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
3283
                if (PSNAccuracy == "100")
3284
                    PSNAccuracy = "1";
3285

    
3286
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
3287
                //if (PSNAccuracy != "100")
3288
                //{
3289
                //    //dataRow["IncludingVirtualData"] = "No";
3290
                dataRow["PSNAccuracy"] = PSNAccuracy;
3291
                //}
3292
            }
3293
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
3294
            foreach (DataRow dr in dt.Rows)
3295
            {
3296
                string oid = dr.Field<string>("OID");
3297
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
3298
                double totalDdr = 0;
3299
                foreach (DataRow ddr in select)
3300
                {
3301
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
3302
                    if (acc == 100) acc = 1;
3303
                    if (totalDdr == 0) totalDdr = acc;
3304
                    else totalDdr *= acc;
3305
                }
3306

    
3307
                totalDdr *= 100;
3308

    
3309
                if (totalDdr != 100)
3310
                {
3311
                    foreach (DataRow ddr in select)
3312
                    {
3313
                        ddr["IncludingVirtualData"] = "Yes";
3314
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
3315
                        ddr["IsValid"] = "Error";
3316
                    }
3317
                }
3318
                else
3319
                {
3320
                    foreach (DataRow ddr in select)
3321
                    {
3322
                        ddr["IncludingVirtualData"] = "No";
3323
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
3324
                    }
3325
                }
3326
            }
3327

    
3328
        }
3329

    
3330
        private void UpdateKeywordForPSN()
3331
        {
3332
            #region Keyword Info
3333
            KeywordInfo KeywordInfos = new KeywordInfo();
3334
            DataTable dtKeyword = DB.SelectKeywordsSetting();
3335
            foreach (DataRow row in dtKeyword.Rows)
3336
            {
3337
                int index = Convert.ToInt32(row["INDEX"]);
3338
                string name = row["NAME"].ToString();
3339
                string keyword = row["KEYWORD"].ToString();
3340

    
3341
                //KeywordInfo keywordInfo = new KeywordInfo();   
3342
                KeywordInfos.KeywordItems.Add(new KeywordItem()
3343
                {
3344
                    Index = index,
3345
                    Name = name,
3346
                    Keyword = keyword
3347
                });
3348
            }
3349
            #endregion
3350

    
3351
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
3352
            foreach (DataRow dataRow in endofHeaderRows)
3353
            {
3354
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3355

    
3356
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
3357
                {
3358
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3359
                    DataRow dr = pathItemRows.First();
3360
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
3361
                    dr["TYPE"] = "End";
3362
                    dr["ITEMTAG"] = "ENDOFHEADER";
3363
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3364
                }
3365

    
3366
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
3367
                {
3368
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3369
                    DataRow dr = pathItemRows.Last();
3370
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
3371
                    dr["TYPE"] = "End";
3372
                    dr["ITEMTAG"] = "ENDOFHEADER";
3373
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3374
                }
3375
            }
3376

    
3377
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3378
            {
3379
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
3380
                foreach (DataRow dataRow in keywordRows)
3381
                {
3382
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3383

    
3384
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
3385
                    {
3386
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3387

    
3388
                        //
3389
                        //if(.)
3390
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
3391
                        {
3392
                            DataRow dr = pathItemRows.First();
3393
                            //dr["CLASS"] = ""; //Type
3394
                            dr["TYPE"] = "End";
3395
                            dr["ITEMTAG"] = keyitem.Keyword;
3396
                            dr["DESCRIPTION"] = keyitem.Keyword;
3397
                        }
3398

    
3399
                    }
3400

    
3401
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
3402
                    {
3403
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3404

    
3405
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
3406
                        {
3407
                            DataRow dr = pathItemRows.Last();
3408
                            //dr["CLASS"] = ""; //Type
3409
                            dr["TYPE"] = "End";
3410
                            dr["ITEMTAG"] = keyitem.Keyword;
3411
                            dr["DESCRIPTION"] = keyitem.Keyword;
3412
                            //dr.Field<string>("Type")
3413
                        }
3414

    
3415
                    }
3416
                }
3417
            }
3418
        }
3419

    
3420
        private void UpdateErrorForPSN()
3421
        {
3422
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
3423
            foreach (DataRow dataRow in errorRows)
3424
            {
3425
                try
3426
                {
3427
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3428
                   
3429
                    bool change = false;
3430
                    bool bCheck = false;
3431
                    if (!PSNItem.EnableType(PSNItem.StartType))
3432
                    {
3433
                        
3434
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3435
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3436

    
3437
                        Item item = PSNItem.Groups.First().Items.First();
3438
                        try
3439
                        {
3440
                            if (PSNItem.StartType == PSNType.Symbol && item.Relations != null && item.Relations[0].Item.Relations != null && item.Relations[0].Item.Relations.Count() > 2)
3441
                            {
3442
                                PSNItem.StartType = PSNType.Branch;
3443
                            }
3444
                            else
3445
                            {
3446
                                if (!item.Name.ToUpper().Equals("TIEINPOINT"))
3447
                                {
3448
                                    change = true;
3449

    
3450
                                    string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3451

    
3452
                                    foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3453
                                    {
3454
                                        loopRow["FROM_DATA"] = FROM_DATA;
3455
                                        if (item.ItemType == ItemType.Line)
3456
                                        {
3457
                                            if (loopRow.Field<string>("OrderNumber") == "0")
3458
                                            {
3459
                                                string status = loopRow.Field<string>("Status");
3460
                                                //string isvali
3461
                                                if (string.IsNullOrEmpty(status))
3462
                                                    status = "Line Disconnected";
3463
                                                else if (!status.Contains("Line Disconnected"))
3464
                                                    status += ", Line Disconnected";
3465
                                                loopRow["Status"] = status;
3466
                                                if (!string.IsNullOrEmpty(status))
3467
                                                    loopRow["IsValid"] = "Error";
3468
                                            }
3469
                                        }
3470
                                    }
3471

    
3472
                                    tieInPointIndex++;
3473

    
3474
                                    if (item.ItemType == ItemType.Line)
3475
                                    {
3476
                                        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
3477
                                    }
3478
                                    else
3479
                                    {
3480
                                        PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
3481
                                        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
3482

    
3483
                                        bCheck = true;
3484
                                    }
3485
                                }
3486
                                else
3487
                                {
3488
                                    foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3489
                                    {
3490
                                        loopRow["FROM_DATA"] = pathItemRows.First().Field<string>("ITEMTAG");
3491

    
3492
                                        if (loopRow.Field<string>("OrderNumber") == "0")
3493
                                        {
3494
                                            if (loopRow["Status"].ToString().Contains(", Missing ItemTag or Description"))
3495
                                                loopRow["Status"] = loopRow["Status"].ToString().Replace(", Missing ItemTag or Description", "");
3496
                                            else if (loopRow["Status"].ToString().Contains("Missing ItemTag or Description"))
3497
                                                loopRow["Status"] = loopRow["Status"].ToString().Replace("Missing ItemTag or Description", "");
3498

    
3499
                                            if (!string.IsNullOrEmpty(loopRow["Status"].ToString()) && loopRow["Status"].ToString().Substring(0, 2).Equals(", "))
3500
                                                loopRow["Status"] = loopRow["Status"].ToString().Remove(0, 2);
3501
                                        }
3502
                                    }
3503

    
3504
                                    bool bStatus = false;
3505
                                    foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3506
                                    {
3507
                                        if (!string.IsNullOrEmpty(loopRow["Status"].ToString()))
3508
                                            bStatus = true;
3509
                                    }
3510

    
3511
                                    if (!bStatus)
3512
                                    {
3513
                                        foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3514
                                        {
3515
                                            loopRow["IsValid"] = string.Empty;
3516
                                        }
3517
                                    }
3518
                                }
3519
                                PSNItem.StartType = PSNType.Equipment;
3520
                            }                           
3521
                        }
3522
                        catch (Exception ex)
3523
                        {
3524
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3525
                            return;
3526
                        }                     
3527
                    }
3528

    
3529
                    if (!PSNItem.EnableType(PSNItem.EndType))
3530
                    {
3531
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3532
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
3533
                        DataRow dr = pathItemRows.Last();
3534
                        if (change)
3535
                        {
3536
                            if (bCheck)
3537
                                dr = pathItemRows[pathItemRows.Count() - 3];
3538
                            else
3539
                            {
3540
                                dr = pathItemRows[pathItemRows.Count() - 2];
3541
                            }
3542
                        }
3543

    
3544
                        change = true;
3545
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3546

    
3547
                        Item item = PSNItem.Groups.Last().Items.Last();
3548
                            
3549
                        try
3550
                        {
3551
                            if (PSNItem.EndType == PSNType.Symbol && item.Relations != null && item.Relations[item.Relations.Count - 1].Item.Relations != null && item.Relations[item.Relations.Count - 1].Item.Relations.Count() > 2)
3552
                            {
3553
                                PSNItem.EndType = PSNType.Branch;
3554
                            }
3555
                            else
3556
                            {
3557
                                if (!item.Name.ToUpper().Equals("TIEINPOINT"))
3558
                                {
3559

    
3560
                                    string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3561

    
3562
                                    foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3563
                                    {
3564
                                        loopRow["TO_DATA"] = TO_DATA;
3565
                                        if (item.ItemType == ItemType.Line)
3566
                                        {
3567
                                            if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
3568
                                            {
3569
                                                string status = loopRow.Field<string>("Status");
3570
                                                if (string.IsNullOrEmpty(status))
3571
                                                    status = "Line Disconnected";
3572
                                                else if (!status.Contains("Line Disconnected"))
3573
                                                    status += ", Line Disconnected";
3574
                                                loopRow["Status"] = status;
3575
                                                if (!string.IsNullOrEmpty(status))
3576
                                                    loopRow["IsValid"] = "Error";
3577
                                            }
3578
                                        }
3579
                                    }
3580

    
3581
                                    tieInPointIndex++;
3582

    
3583
                                    if (item.ItemType == ItemType.Line)
3584
                                    {
3585
                                        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3586
                                    }
3587
                                    else
3588
                                    {
3589
                                        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3590
                                        PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
3591
                                    }
3592
                                }
3593
                                else
3594
                                {
3595
                                    foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3596
                                    {
3597
                                        loopRow["TO_DATA"] = dr.Field<string>("ITEMTAG");
3598

    
3599
                                        if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
3600
                                        {
3601
                                            if (loopRow["Status"].ToString().Contains(", Missing ItemTag or Description"))
3602
                                                loopRow["Status"] = loopRow["Status"].ToString().Replace(", Missing ItemTag or Description", "");
3603
                                            else if (loopRow["Status"].ToString().Contains("Missing ItemTag or Description"))
3604
                                                loopRow["Status"] = loopRow["Status"].ToString().Replace("Missing ItemTag or Description", "");
3605

    
3606
                                            if (!string.IsNullOrEmpty(loopRow["Status"].ToString()) && loopRow["Status"].ToString().Substring(0, 2).Equals(", "))
3607
                                                loopRow["Status"] = loopRow["Status"].ToString().Remove(0, 2);
3608
                                        }
3609
                                    }
3610

    
3611
                                    bool bStatus = false;
3612
                                    foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3613
                                    {
3614
                                        if (!string.IsNullOrEmpty(loopRow["Status"].ToString()))
3615
                                            bStatus = true;
3616
                                    }
3617

    
3618
                                    if (!bStatus)
3619
                                    {
3620
                                        foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3621
                                        {
3622
                                            loopRow["IsValid"] = string.Empty;
3623
                                        }
3624
                                    }
3625
                                }
3626
                                PSNItem.EndType = PSNType.Equipment;
3627
                            }
3628
                           
3629
                        }
3630
                        catch (Exception ex)
3631
                        {
3632
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3633
                            return;
3634
                        }
3635
                           
3636
                    }
3637

    
3638
                    dataRow["Type"] = PSNItem.GetPSNType();
3639
                    if (change)
3640
                    {
3641
                        int rowIndex = 0;
3642
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3643
                        {
3644
                            DataRow row = PathItems.Rows[i];
3645
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
3646
                                continue;
3647
                            string sequenceData = row["SequenceData_OID"].ToString();
3648
                            string[] split = sequenceData.Split(new char[] { '_' });
3649

    
3650
                            StringBuilder sb = new StringBuilder();
3651
                            for (int j = 0; j < split.Length - 1; j++)
3652
                                sb.Append(split[j] + "_");
3653
                            sb.Append(rowIndex++);
3654
                            row["SequenceData_OID"] = sb.ToString();
3655

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

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

    
3661
                            if (seqItemRows == null)
3662
                            {
3663
                                DataRow newRow = SequenceData.NewRow();
3664
                                newRow["OID"] = sb.ToString();
3665
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3666
                                newRow["PathItem_OID"] = row["OID"];
3667
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3668
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3669
                            }
3670
                            else
3671
                            {
3672
                                seqItemRows["OID"] = sb.ToString();
3673
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3674
                                seqItemRows["PathItem_OID"] = row["OID"];
3675
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3676
                            }
3677
                        }
3678
                    }
3679

    
3680
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
3681
                    {
3682
                        DataRow newRow = PathItems.NewRow();
3683
                        newRow["OID"] = Guid.NewGuid().ToString();
3684
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3685
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3686
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3687
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3688
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
3689
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
3690
                        newRow["DESCRIPTION"] = DATA;
3691
                        newRow["Class"] = "End of line terminator";
3692
                        newRow["SubClass"] = "End of line terminator";
3693
                        newRow["TYPE"] = "End";
3694
                        newRow["MULTIWAY"] = "";
3695
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3696
                        newRow["NPD"] = itemRow["NPD"];
3697
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3698
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3699
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3700
                        newRow["EGTConnectedPoint"] = "0";
3701
                        return newRow;
3702
                    }
3703

    
3704
                    DataRow createLineRow(DataRow itemRow)
3705
                    {
3706
                        DataRow newRow = PathItems.NewRow();
3707
                        newRow["OID"] = Guid.NewGuid().ToString();
3708
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3709
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3710
                        newRow["BranchTopologySet_OID"] = "";
3711
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3712
                        newRow["ITEMNAME"] = "PipeRun";
3713
                        newRow["ITEMTAG"] = itemRow["PipeRun_OID"];
3714
                        newRow["Class"] = "Piping";
3715
                        newRow["SubClass"] = "";
3716
                        newRow["TYPE"] = "Secondary";
3717
                        newRow["MULTIWAY"] = "";
3718
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3719
                        newRow["NPD"] = itemRow["NPD"];
3720
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3721
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3722
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3723
                        newRow["EGTConnectedPoint"] = "0";
3724
                        return newRow;
3725
                    }
3726
                }
3727
                catch (Exception ex)
3728
                {
3729

    
3730
                }
3731
            }
3732
        }
3733

    
3734
        private void InsertTeePSN()
3735
        {
3736
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
3737
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
3738
            bool change = false;
3739
            foreach (DataRow dataRow in branchRows)
3740
            {
3741
                try
3742
                {
3743
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3744
                    change = false;
3745
                    DataRow[] pipeSystem = PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID()));
3746
                    if (PSNItem.StartType == PSNType.Branch)
3747
                    {
3748
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3749
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3750
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3751
                        try
3752
                        {
3753
                            if (Teeitem.ItemType == ItemType.Line)
3754
                            {
3755
                                //if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3756
                                //{
3757
                                if (Teeitem.Relations[0].Item.ItemType == ItemType.Line)
3758
                                {
3759
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3760
                                    change = true;
3761
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3762
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());                                    
3763
                                }
3764
                                else
3765
                                { //dicMultiwaySymbolUID.Add(item.UID, 1);
3766
                                    int index = dicMultiwaySymbolUID[Teeitem.Relations[0].Item.UID] + 1;
3767
                                    string multiItemOID = Teeitem.Relations[0].Item.UID + "_M" + index;
3768
                                    dicMultiwaySymbolUID[Teeitem.Relations[0].Item.UID] = index;
3769

    
3770
                                    PathItems.Rows.InsertAt(createMultiWayConnRow(PathItems.Select(string.Format("OID = '{0}'", Teeitem.Relations[0].Item.UID + "_M1")).First(), multiItemOID, pathItemRows.First()), insertIndex);
3771
                                    change = true;
3772
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3773
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3774

    
3775
                                    SequenceData.Rows.InsertAt(CreateSequenceDataDataRow(pathItemRows.First(), multiItemOID, 0), 0);
3776

    
3777
                                    foreach(DataRow pipedr in pipeSystem)
3778
                                    {
3779
                                        pipedr["FROM_DATA"] = PathItems.Select(string.Format("OID = '{0}'", Teeitem.Relations[0].Item.UID + "_M1")).First().Field<string>("MULTIWAY");
3780
                                    }
3781
                                }
3782
                            }
3783
                            else if (Teeitem.ItemType == ItemType.Symbol)
3784
                            {
3785
                                Group _group = groups.Find(x => x.Items.Select(w => w.UID).Contains(Teeitem.UID));
3786
                                var _items = Teeitem.Relations.Where(w => w.Item != null && !_group.Items.Contains(w.Item)).Select(w => w.Item).ToList();
3787
                                if (_items.Count > 0)
3788
                                {
3789
                                    int index = dicMultiwaySymbolUID[_items[0].UID] + 1;
3790
                                    string multiItemOID = _items[0].UID + "_M" + index;
3791
                                    dicMultiwaySymbolUID[_items[0].UID] = index;
3792
                                    PathItems.Rows.InsertAt(createMultiWayConnRow(PathItems.Select(string.Format("OID = '{0}'", _items[0].UID + "_M1")).First(), multiItemOID, pathItemRows.First()), insertIndex);
3793
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3794
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3795

    
3796
                                    change = true;
3797

    
3798
                                    SequenceData.Rows.InsertAt(CreateSequenceDataDataRow(pathItemRows.First(), multiItemOID, 0), 0);
3799

    
3800
                                    foreach (DataRow pipedr in pipeSystem)
3801
                                    {
3802
                                        pipedr["FROM_DATA"] = PathItems.Select(string.Format("OID = '{0}'", _items[0].UID + "_M1")).First().Field<string>("MULTIWAY");
3803
                                    }
3804

    
3805
                                }
3806
                            }
3807
                        }
3808
                        catch (Exception ex)
3809
                        {
3810
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3811
                            return;
3812
                        }
3813
                    }
3814

    
3815
                    if (PSNItem.EndType == PSNType.Branch)
3816
                    {
3817
                        //change = true;
3818
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3819

    
3820
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3821

    
3822
                        DataRow dr = pathItemRows.Last();
3823
                        if (change)
3824
                            dr = pathItemRows[pathItemRows.Count() - 2];
3825

    
3826
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3827

    
3828
                        try
3829
                        {
3830
                            if (Teeitem.ItemType == ItemType.Line)
3831
                            {
3832
                                if (dr.Field<string>("SubClass").ToUpper() != "TEE")
3833
                                {
3834
                                    if (Teeitem.Relations[1].Item.ItemType == ItemType.Line)
3835
                                    {
3836
                                        PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3837
                                        change = true;
3838
                                        dr.SetField("BranchTopologySet_OID", string.Empty);
3839
                                        dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3840
                                    }
3841
                                    else
3842
                                    {
3843
                                        int index = dicMultiwaySymbolUID[Teeitem.Relations[1].Item.UID] + 1;
3844
                                        string multiItemOID = Teeitem.Relations[1].Item.UID + "_M" + index;
3845
                                        dicMultiwaySymbolUID[Teeitem.Relations[1].Item.UID] = index;
3846
                                        PathItems.Rows.InsertAt(createMultiWayConnRow(PathItems.Select(string.Format("OID = '{0}'", Teeitem.Relations[1].Item.UID + "_M1")).First(), multiItemOID, dr), insertIndex);
3847
                                        change = true;
3848
                                        dr.SetField("BranchTopologySet_OID", string.Empty);
3849
                                        dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3850

    
3851
                                        SequenceData.Rows.InsertAt(CreateSequenceDataDataRow(dr, multiItemOID, PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID())).Count()), 0);
3852

    
3853
                                        foreach (DataRow pipedr in pipeSystem)
3854
                                        {
3855
                                            pipedr["TO_DATA"] = PathItems.Select(string.Format("OID = '{0}'", Teeitem.Relations[1].Item.UID + "_M1")).First().Field<string>("MULTIWAY");
3856
                                        }
3857
                                    }
3858
                                }
3859

    
3860
                            }
3861
                            else if (Teeitem.ItemType == ItemType.Symbol)
3862
                            {
3863
                                Group _group = groups.Find(x => x.Items.Select(w => w.UID).Contains(Teeitem.UID));
3864
                                var _items = Teeitem.Relations.Where(w => w.Item != null && !_group.Items.Contains(w.Item)).Select(w => w.Item).ToList();
3865
                                if (_items.Count > 0)
3866
                                {
3867
                                    int index = dicMultiwaySymbolUID[_items[0].UID] + 1;
3868
                                    string multiItemOID = _items[0].UID + "_M" + index;
3869
                                    dicMultiwaySymbolUID[_items[0].UID] = index;
3870
                                    //newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
3871
                                    PathItems.Rows.InsertAt(createMultiWayConnRow(PathItems.Select(string.Format("OID = '{0}'", _items[0].UID + "_M1")).First(), multiItemOID, dr), insertIndex);
3872
                                    change = true;
3873
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3874
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3875
                                    SequenceData.Rows.InsertAt(CreateSequenceDataDataRow(dr, multiItemOID, PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID())).Count()), 0);
3876

    
3877
                                    foreach (DataRow pipedr in pipeSystem)
3878
                                    {
3879
                                        pipedr["TO_DATA"] = PathItems.Select(string.Format("OID = '{0}'", _items[0].UID + "_M1")).First().Field<string>("MULTIWAY");
3880
                                    }
3881
                                }
3882
                            }
3883
                        }
3884
                        catch (Exception ex)
3885
                        {
3886
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3887
                            return;
3888
                        }
3889
                    }
3890

    
3891
                    if (change)
3892
                    {
3893
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3894
                        int rowIndex = 0;
3895
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3896
                        {
3897
                            DataRow row = PathItems.Rows[i];
3898
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3899
                                continue;
3900
                            string sequenceData = row["SequenceData_OID"].ToString();
3901
                            string[] split = sequenceData.Split(new char[] { '_' });
3902

    
3903
                            StringBuilder sb = new StringBuilder();
3904
                            for (int j = 0; j < split.Length - 1; j++)
3905
                                sb.Append(split[j] + "_");
3906
                            sb.Append(rowIndex++);
3907
                            row["SequenceData_OID"] = sb.ToString();
3908

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

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

    
3914
                            if (seqItemRows == null)
3915
                            {
3916
                                DataRow newRow = SequenceData.NewRow();
3917
                                newRow["OID"] = sb.ToString();
3918
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3919
                                newRow["PathItem_OID"] = row["OID"];
3920
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3921
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3922
                            }
3923
                            else
3924
                            {
3925
                                seqItemRows["OID"] = sb.ToString();
3926
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3927
                                seqItemRows["PathItem_OID"] = row["OID"];
3928
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3929
                            }
3930
                        }
3931
                    }
3932

    
3933
                    DataRow createTeeRow(DataRow itemRow)
3934
                    {
3935
                        DataRow newRow = PathItems.NewRow();
3936
                        newRow["OID"] = Guid.NewGuid().ToString();
3937
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3938
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3939
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3940
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3941
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3942
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3943
                        newRow["DESCRIPTION"] = "";
3944
                        newRow["Class"] = "Branch";
3945
                        newRow["SubClass"] = "Tee";
3946
                        newRow["TYPE"] = itemRow["TYPE"];
3947
                        newRow["MULTIWAY"] = itemRow["MULTIWAY"];
3948
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3949
                        newRow["NPD"] = itemRow["NPD"];
3950
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3951
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3952
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3953
                      
3954
                        newRow["EGTConnectedPoint"] = 0;
3955
                        return newRow;
3956
                    }
3957

    
3958
                    DataRow CreateSequenceDataDataRow(DataRow itemRow, string multiItemOID, int index)
3959
                    {
3960
                        DataRow newRow = SequenceData.NewRow();
3961
                        newRow["OID"] = string.Format(itemRow["TopologySet_OID"].ToString() + "_{0}", index); // string.Format();
3962
                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
3963
                        newRow["PathItem_OID"] = multiItemOID;
3964
                        newRow["TopologySet_OID_Key"] = itemRow["TopologySet_OID"].ToString();//item.Topology.FullName;
3965

    
3966
                        return newRow;
3967
                    }
3968

    
3969
                    DataRow createMultiWayConnRow(DataRow itemRow, string multiItemOID, DataRow itemRow2)
3970
                    {
3971
                        DataRow newRow = PathItems.NewRow();                   
3972
                        newRow["OID"] = multiItemOID;
3973
                        newRow["SequenceData_OID"] = itemRow2["SequenceData_OID"];
3974
                        newRow["TopologySet_OID"] = itemRow2["TopologySet_OID"];
3975
                        newRow["BranchTopologySet_OID"] = itemRow2["BranchTopologySet_OID"];
3976
                        newRow["PipeLine_OID"] = itemRow2["PipeLine_OID"];
3977
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];// = "End of line terminator";
3978
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3979
                        newRow["DESCRIPTION"] = itemRow["DESCRIPTION"];
3980
                        newRow["Class"] = itemRow["Class"];
3981
                        newRow["SubClass"] = itemRow["SubClass"];
3982
                        newRow["TYPE"] = itemRow["TYPE"];
3983
                        newRow["MULTIWAY"] = itemRow["MULTIWAY"];
3984
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3985
                        newRow["NPD"] = itemRow["NPD"];
3986
                        newRow["PipeSystemNetwork_OID"] = itemRow2["PipeSystemNetwork_OID"];
3987
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow2["ViewPipeSystemNetwork_OID"];
3988
                        newRow["PipeRun_OID"] = itemRow2["PipeRun_OID"];
3989
                        newRow["EGTConnectedPoint"] = itemRow["EGTConnectedPoint"];
3990
                        return newRow;
3991
                    }
3992
                }
3993
                catch (Exception ex)
3994
                {
3995

    
3996
                }
3997
            }
3998
        }
3999
    }
4000

    
4001
    public class PSNItem
4002
    {
4003
        public PSNItem(int count, int Revision)
4004
        {
4005
            Groups = new List<Group>();
4006
            Topologies = new List<Topology>();
4007

    
4008
            Index = count + 1;
4009
            this.Revision = Revision;
4010
        }
4011

    
4012
        private int Revision;
4013
        public string UID { get; set; }
4014
        public List<Group> Groups { get; set; }
4015
        public List<Topology> Topologies { get; set; }
4016
        public PSNType StartType { get; set; }
4017
        public PSNType EndType { get; set; }
4018
        public int Index { get; set; }
4019
        public string IsValid { get; set; }
4020
        public bool IsKeyword { get; set; }
4021
        public string Status { get; set; }
4022
        public string IncludingVirtualData { get; set; }
4023
        public string PSNAccuracy { get; set; }
4024
        public KeywordInfo KeywordInfos = new KeywordInfo();
4025
        public DataTable Nozzle = new DataTable();
4026

    
4027
        public string PSN_OID()
4028
        {
4029
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
4030
        }
4031

    
4032
        public string GetPSNType()
4033
        {
4034
            string result = string.Empty;
4035

    
4036
            if (EnableType(StartType) && EnableType(EndType))
4037
            {
4038
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
4039
                    result = "E2E";
4040
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
4041
                    result = "B2B";
4042
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
4043
                    result = "HD2";
4044

    
4045
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
4046
                    result = "E2B";
4047
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
4048
                    result = "B2E";
4049

    
4050
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
4051
                    result = "HDB";
4052
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
4053
                    result = "HDB";
4054

    
4055
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
4056
                    result = "HDE";
4057
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
4058
                    result = "HDE";
4059
                else
4060
                    result = "Error";
4061
            }
4062
            else
4063
                result = "Error";
4064

    
4065
            return result;
4066

    
4067

    
4068
        }
4069

    
4070
        public bool EnableType(PSNType type)
4071
        {
4072
            bool result = false;
4073

    
4074
            if (type == PSNType.Branch ||
4075
                type == PSNType.Equipment ||
4076
                type == PSNType.Header)
4077
            {
4078
                result = true;
4079
            }
4080

    
4081
            return result;
4082
        }
4083

    
4084
        public bool IsBypass { get; set; }
4085

    
4086
        public string GetFromData(ref string Type, ref Item item, Item oItem, ref string OStatus)
4087
        {
4088
            Status = string.Empty;
4089
            string result = string.Empty;
4090
            if (IsKeyword)
4091
                IsKeyword = false;
4092
            try
4093
            {
4094
                item = Groups.First().Items.First();
4095

    
4096
                if (StartType == PSNType.Header)
4097
                    result = "ENDOFHEADER";
4098
                else if (StartType == PSNType.Branch)
4099
                {
4100
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
4101
                        result = item.Relations.First().Item.LineNumber.Name;
4102
                    else
4103
                    {
4104
                        IsValid = "Error";
4105
                        result = "Empty LineNumber";
4106
                    }
4107

    
4108
                        
4109

    
4110
                    //if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
4111
                    //{
4112
                    //    result = item.Relations.First().Item.LineNumber.Name;
4113
                    //    if (item.Relations.First().Item.LineNumber.MissingLineNumber2)
4114
                    //    {
4115
                    //        Status += ", Missing LineNumber_2";
4116
                    //        IsValid = "Error";
4117
                    //    }
4118
                    //    if (item.Relations.First().Item.LineNumber.MissingLineNumber1)
4119
                    //    {
4120
                    //        Status += ", Missing LineNumber_1";
4121
                    //        IsValid = "Error";
4122
                    //    }
4123
                    //}
4124
                    //else
4125
                    //{
4126
                    //    IsValid = "Error";
4127
                    //    result = "Empty LineNumber";
4128
                    //}
4129
                }
4130
                else if (StartType == PSNType.Equipment)
4131
                {
4132
                    if (Groups.First().Items.First().Equipment != null)
4133
                        result = Groups.First().Items.First().Equipment.ItemTag;
4134
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
4135

    
4136
                    if (drNozzle != null)
4137
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
4138
                }
4139
                else
4140
                {
4141
                    
4142
                    item = Groups.First().Items.First();
4143
                    if (item.ItemType == ItemType.Symbol)
4144
                    {
4145
                        string keyword = string.Empty;
4146
                        keyword = GetFromKeywordData(ref Type, item);
4147

    
4148
                        if (string.IsNullOrEmpty(keyword))
4149
                        {
4150
                            if (item.ID2DBType.Contains("OPC's"))
4151
                                Status += ", OPC Disconnected";
4152
                            else
4153
                                Status += ", Missing ItemTag or Description";
4154

    
4155
                            result = item.ID2DBName;
4156
                            IsValid = "Error";
4157
                        }
4158
                        else
4159
                        {
4160
                            result = keyword;
4161
                            IsKeyword = true;
4162
                        }
4163

    
4164
                    }
4165
                    else if (item.ItemType == ItemType.Line)
4166
                    {
4167
                        if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
4168
                        {
4169
                            result = item.LineNumber.Name;
4170
                        }
4171
                        else
4172
                        {
4173
                            IsValid = "Error";
4174
                            result = "Empty LineNumber";
4175
                        }
4176

    
4177
                   
4178
                       
4179
                    }
4180
                    else
4181
                        result = "Unknown";
4182
                }
4183

    
4184
                if (oItem.LineNumber != null && !string.IsNullOrEmpty(oItem.LineNumber.Name))
4185
                {
4186
                    if (oItem.LineNumber.MissingLineNumber2)
4187
                    {
4188
                        OStatus += ", Missing LineNumber_2";
4189
                        IsValid = "Error";
4190
                    }
4191
                    if (oItem.LineNumber.MissingLineNumber1)
4192
                    {
4193
                        OStatus += ", Missing LineNumber_1";
4194
                        IsValid = "Error";
4195
                    }
4196
                }
4197
            }
4198
            catch (Exception ex)
4199
            {
4200

    
4201
            }
4202

    
4203
            return result;
4204
        }
4205

    
4206
        public string GetFromKeywordData(ref string Type, Item item)
4207
        {
4208
            string result = string.Empty;
4209

    
4210
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
4211
            {
4212
                if (keyitem.Name.Equals(item.Name))
4213
                {
4214
                    result = keyitem.Keyword;
4215
                    Type = item.ID2DBType;
4216
                    break;
4217
                }
4218
            }
4219

    
4220
            return result;
4221
        }
4222

    
4223
        public string GetToKeywordData(ref string Type, Item item)
4224
        {
4225
            string result = string.Empty;
4226

    
4227
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
4228
            {
4229
                if (keyitem.Name.Equals(item.Name))
4230
                {
4231
                    result = keyitem.Keyword;
4232
                    Type = item.ID2DBType;
4233
                    break;
4234
                }
4235
            }
4236
            return result;
4237
        }
4238

    
4239
        public string GetToData(ref string ToType, ref Item item, Item oItem)
4240
        {
4241
            string result = string.Empty;
4242
            Status = string.Empty;
4243

    
4244
            if (IsKeyword)
4245
                IsKeyword = false;
4246

    
4247
            item = Groups.Last().Items.Last();
4248

    
4249
            if (EndType == PSNType.Header)
4250
                result = "ENDOFHEADER";
4251
            else if (EndType == PSNType.Branch)
4252
            {
4253
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
4254
                    result = item.Relations.Last().Item.LineNumber.Name;
4255
                else
4256
                {
4257
                    IsValid = "Error";
4258
                    result = "Empty LineNumber";
4259
                }
4260

    
4261
            
4262
              
4263
                //if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
4264
                //{
4265
                //    result = item.Relations.Last().Item.LineNumber.Name;
4266
                //    if (item.Relations.Last().Item.LineNumber.MissingLineNumber2)
4267
                //    {
4268
                //        Status += ", Missing LineNumber_2";
4269
                //        IsValid = "Error";
4270
                //    }
4271
                //    if (item.Relations.Last().Item.LineNumber.MissingLineNumber1)
4272
                //    {
4273
                //        Status += ", Missing LineNumber_1";
4274
                //        IsValid = "Error";
4275
                //    }
4276
                //}
4277
                //else
4278
                //{
4279
                //    IsValid = "Error";
4280
                //    result = "Empty LineNumber";
4281
                //}                
4282
            }
4283
            else if (EndType == PSNType.Equipment)
4284
            {
4285
                if (Groups.Last().Items.Last().Equipment != null)
4286
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
4287

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

    
4290
                if (drNozzle != null)
4291
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
4292
            }
4293
            else
4294
            {
4295
                
4296
                item = Groups.Last().Items.Last();
4297
                if (item.ItemType == ItemType.Symbol)
4298
                {
4299
                    string keyword = string.Empty;
4300
                    keyword = GetToKeywordData(ref ToType, item);
4301

    
4302
                    if (string.IsNullOrEmpty(keyword))
4303
                    {
4304
                        if (item.ID2DBType.Contains("OPC's"))
4305
                            Status += ", OPC Disconnected";
4306
                        else
4307
                            Status += ", Missing ItemTag or Description";
4308

    
4309
                        result = item.ID2DBName;
4310
                        IsValid = "Error";
4311
                    }
4312
                    else
4313
                    {
4314
                        result = keyword;
4315
                        IsKeyword = true;
4316
                    }
4317

    
4318
                }
4319
                else if (item.ItemType == ItemType.Line)
4320
                {
4321
                    if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
4322
                    {
4323
                        result = item.LineNumber.Name;
4324
                    }
4325
                    else
4326
                    {
4327
                        IsValid = "Error";
4328
                        result = "Empty LineNumber";
4329
                    }
4330

    
4331
                   
4332
                    
4333
                }
4334
                else
4335
                    result = "Unknown";
4336
            }
4337

    
4338
            return result;
4339
        }
4340

    
4341
        public string GetPBSData()
4342
        {
4343
            string result = string.Empty;
4344
            List<string> PBSList = new List<string>();
4345
            if (Settings.Default.PBSSetting.Equals("Line Number"))
4346
            {
4347
                string attrValue = Settings.Default.PBSSettingValue;
4348

    
4349
                foreach (Group group in Groups)
4350
                {
4351
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
4352
                    foreach (LineNumber lineNumber in lineNumbers)
4353
                    {
4354
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
4355
                        if (attribute != null)
4356
                        {
4357
                            string value = attribute.Value;
4358
                            if (!PBSList.Contains(value))
4359
                                PBSList.Add(value);
4360
                        }
4361
                    }
4362
                }
4363
            }
4364
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
4365
            {
4366
                string attrValue = Settings.Default.PBSSettingValue;
4367

    
4368
                foreach (Group group in Groups)
4369
                {
4370
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
4371
                    foreach (Item item in items)
4372
                    {
4373
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
4374
                        if (!PBSList.Contains(value))
4375
                            PBSList.Add(value);
4376
                    }
4377
                }
4378
            }
4379
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
4380
            {
4381
                string attrValue = Settings.Default.PBSSettingValue;
4382

    
4383
                foreach (Group group in Groups)
4384
                {
4385
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
4386
                    foreach (Document document in documents)
4387
                    {
4388
                        string name = document.DrawingName;
4389

    
4390
                        int startIndex = Settings.Default.PBSSettingStartValue;
4391
                        int endIndex = Settings.Default.PBSSettingEndValue;
4392

    
4393
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
4394
                        if (!PBSList.Contains(subStr))
4395
                            PBSList.Add(subStr);
4396
                    }
4397
                }
4398
            }
4399
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
4400
            {
4401
                foreach (Group group in Groups)
4402
                {
4403
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
4404
                    foreach (Document document in documents)
4405
                    {
4406
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
4407
                        foreach (TextInfo textInfo in textInfos)
4408
                        {
4409
                            if (!PBSList.Contains(textInfo.Value))
4410
                                PBSList.Add(textInfo.Value);
4411
                        }
4412
                    }
4413
                }
4414
            }
4415

    
4416
            foreach (var item in PBSList)
4417
            {
4418
                if (string.IsNullOrEmpty(result))
4419
                    result = item;
4420
                else
4421
                    result += ", " + item;
4422
            }
4423
            return result;
4424
        }
4425
    }
4426
}
클립보드 이미지 추가 (최대 크기: 500 MB)