File size: 27,465 Bytes
b1b3bae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
using System;
using System.Collections.Generic;
using DWSIM.Interfaces;
using System.Runtime.InteropServices;
using DWSIM.UI.Desktop.Shared;
using System.Xml.Linq;
using System.IO;
using System.Reflection;
using DWSIM.SharedClassesCSharp.FilePicker.Windows;
using DWSIM.GlobalSettings;
using System.Linq;
using DWSIM.Interfaces.Enums;
using DWSIM.SharedClasses;
using DWSIM.Thermodynamics.PropertyPackages;
using DWSIM.Thermodynamics;
using System.Threading.Tasks;
using DWSIM.Thermodynamics.AdvancedEOS;
using CapeOpen;
using DWSIM.Thermodynamics.BaseClasses;
using System.Resources;
using static System.Net.Mime.MediaTypeNames;

namespace DWSIM.Automation
{

    [Guid("ed615e8f-da69-4c24-80e2-bfe342168060")]
    public interface AutomationInterface
    {
        Interfaces.IFlowsheet LoadFlowsheet(string filepath);
        void SaveFlowsheet(IFlowsheet flowsheet, string filepath, bool compressed);
        void SaveFlowsheet2(IFlowsheet flowsheet, string filepath);
        void CalculateFlowsheet(IFlowsheet flowsheet, ISimulationObject sender);
        List<Exception> CalculateFlowsheet2(IFlowsheet flowsheet);
        List<Exception> CalculateFlowsheet3(IFlowsheet flowsheet, int timeout_seconds);
        IFlowsheet CreateFlowsheet();
        void ReleaseResources();
        object GetMainWindow();

    }

    [Guid("37437090-e541-4f2c-9856-d1e27df32ecb"), ClassInterface(ClassInterfaceType.None)]
    [ComVisible(true)]
    public class Automation : AutomationInterface
    {

        FormMain fm = null;

        public Automation()
        {
            GlobalSettings.Settings.AutomationMode = true;
            fm = new FormMain();
        }

        public Interfaces.IFlowsheet LoadFlowsheet(string filepath)
        {
            if (System.IO.Path.GetExtension(filepath).ToLower().Contains("dwxmz"))
            {
                return fm.LoadAndExtractXMLZIP(new WindowsFile(filepath), null, true);
            }
            else
            {
                return fm.LoadXML(new WindowsFile(filepath), null, "", true);
            }
        }

        public void SaveFlowsheet(IFlowsheet flowsheet, string filepath, bool compressed)
        {
            if (compressed)
            {
                fm.SaveXMLZIP(new WindowsFile(filepath), (FormFlowsheet)flowsheet);
            }
            else
            {
                fm.SaveXML(new WindowsFile(filepath), (FormFlowsheet)flowsheet);
            }
        }

        public void CalculateFlowsheet(IFlowsheet flowsheet, ISimulationObject sender)
        {
            GlobalSettings.Settings.CalculatorActivated = true;
            GlobalSettings.Settings.SolverBreakOnException = true;
            if ((sender != null))
            {
                FlowsheetSolver.FlowsheetSolver.CalculateObject(flowsheet, sender.Name);
            }
            else
            {
                FlowsheetSolver.FlowsheetSolver.SolveFlowsheet(flowsheet, GlobalSettings.Settings.SolverMode);
            }
        }

        public List<Exception> CalculateFlowsheet2(IFlowsheet flowsheet)
        {
            GlobalSettings.Settings.CalculatorActivated = true;
            GlobalSettings.Settings.SolverBreakOnException = true;
            return FlowsheetSolver.FlowsheetSolver.SolveFlowsheet(flowsheet, GlobalSettings.Settings.SolverMode);
        }

        public List<Exception> CalculateFlowsheet3(IFlowsheet flowsheet, int timeout_seconds)
        {
            GlobalSettings.Settings.CalculatorActivated = true;
            GlobalSettings.Settings.SolverBreakOnException = true;
            GlobalSettings.Settings.SolverTimeoutSeconds = timeout_seconds;
            return FlowsheetSolver.FlowsheetSolver.SolveFlowsheet(flowsheet, GlobalSettings.Settings.SolverMode);
        }

        public void SaveFlowsheet2(IFlowsheet flowsheet, string filepath)
        {
            SaveFlowsheet(flowsheet, filepath, true);
        }

        public IFlowsheet CreateFlowsheet()
        {
            return new FormFlowsheet();
        }

        public void ReleaseResources()
        {
            if (fm != null && !fm.IsDisposed)
            {
                fm.Dispose();
                fm = null;
            }
        }

        public object GetMainWindow()
        {
            return fm;
        }
    }

    [Guid("22694b87-1ba6-4341-81dd-8d33f48643d7"), ClassInterface(ClassInterfaceType.None)]
    [ComVisible(true)]
    public class Automation2 : AutomationInterface
    {

        Eto.Forms.Application app;
        UI.Forms.Flowsheet fm;

        public Automation2()
        {
            GlobalSettings.Settings.AutomationMode = true;
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.AssemblyResolve += new ResolveEventHandler(LoadAssembly);
            app = UI.Desktop.Program.MainApp(null);
            app.Attach(this);
            FlowsheetBase.FlowsheetBase.AddPropPacks();
        }

        static Assembly LoadAssembly(object sender, ResolveEventArgs args)
        {
            string assemblyPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), new AssemblyName(args.Name).Name + ".dll");
            if (!File.Exists(assemblyPath))
            {
                return null;
            }
            else
            {
                Assembly assembly = Assembly.LoadFrom(assemblyPath);
                return assembly;
            }
        }

        public Interfaces.IFlowsheet LoadFlowsheet(string filepath)
        {
            GlobalSettings.Settings.AutomationMode = true;
            fm = new UI.Forms.Flowsheet();
            LoadSimulation(filepath);
            return fm.FlowsheetObject;
        }

        public void ReleaseResources()
        {
            fm?.Dispose();
            fm = null;
        }

        public void SaveFlowsheet(IFlowsheet flowsheet, string filepath, bool compressed)
        {
            fm.FlowsheetObject = (Flowsheet)flowsheet;
            fm.SaveSimulation(filepath);
        }

        public void CalculateFlowsheet(IFlowsheet flowsheet, ISimulationObject sender)
        {
            GlobalSettings.Settings.CalculatorActivated = true;
            GlobalSettings.Settings.SolverBreakOnException = true;
            fm.FlowsheetObject.SolveFlowsheet2();
        }

        public List<Exception> CalculateFlowsheet2(IFlowsheet flowsheet)
        {
            GlobalSettings.Settings.CalculatorActivated = true;
            GlobalSettings.Settings.SolverBreakOnException = true;
            return FlowsheetSolver.FlowsheetSolver.SolveFlowsheet(flowsheet, GlobalSettings.Settings.SolverMode);
        }

        public List<Exception> CalculateFlowsheet3(IFlowsheet flowsheet, int timeout_seconds)
        {
            GlobalSettings.Settings.CalculatorActivated = true;
            GlobalSettings.Settings.SolverTimeoutSeconds = timeout_seconds;
            return FlowsheetSolver.FlowsheetSolver.SolveFlowsheet(flowsheet, GlobalSettings.Settings.SolverMode);
        }

        private void LoadSimulation(string path)
        {
            if (System.IO.Path.GetExtension(path).ToLower() == ".dwxmz")
            {
                var xdoc = fm.FlowsheetObject.LoadZippedXML(path);
                xdoc = null;
            }
            else if (System.IO.Path.GetExtension(path).ToLower() == ".dwxml")
            {
                fm.FlowsheetObject.LoadFromXML(XDocument.Load(path));
            }
            else if (System.IO.Path.GetExtension(path).ToLower() == ".xml")
            {
                fm.FlowsheetObject.LoadFromMXML(XDocument.Load(path));
            }
            fm.FlowsheetObject.FilePath = path;
            fm.FlowsheetObject.FlowsheetOptions.FilePath = path;
        }

        public void SaveFlowsheet2(IFlowsheet flowsheet, string filepath)
        {
            SaveFlowsheet(flowsheet, filepath, true);
        }

        public IFlowsheet CreateFlowsheet()
        {
            GlobalSettings.Settings.AutomationMode = true;
            fm = new UI.Forms.Flowsheet();
            return fm.FlowsheetObject;
        }

        public object GetMainWindow()
        {
            throw new NotImplementedException();
        }
    }

    [Guid("62486815-2330-4CDE-8962-41F576B0C2B8"), ClassInterface(ClassInterfaceType.None)]
    [ComVisible(true)]
    public class Automation3 : AutomationInterface
    {

        public Dictionary<String, IPropertyPackage> AvailablePropertyPackages { get; } = new Dictionary<string, IPropertyPackage>();

        public Dictionary<String, ICompoundConstantProperties> AvailableCompounds { get; } = new Dictionary<string, ICompoundConstantProperties>();

        private System.Resources.ResourceManager rm, prm;

        public Automation3()
        {
            Settings.AutomationMode = true;
            Settings.InspectorEnabled = false;
            Settings.CultureInfo = "en";
            GlobalSettings.Settings.AutomationMode = true;
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.AssemblyResolve += new ResolveEventHandler(LoadAssembly);
            //FlowsheetBase.FlowsheetBase.AddPropPacks();
            LoadItems();
            LoadExtenders();
        }

        private void LoadItems()
        {

            // resources

            rm = new System.Resources.ResourceManager("DWSIM.FlowsheetBase.Strings", Assembly.GetAssembly(typeof(FlowsheetBase.FlowsheetBase)));
            prm = new System.Resources.ResourceManager("DWSIM.FlowsheetBase.Properties", Assembly.GetAssembly(typeof(FlowsheetBase.FlowsheetBase)));

            // proppacks

            if (AvailablePropertyPackages.Count > 0) return;

            var plist = new System.Collections.Concurrent.BlockingCollection<PropertyPackage>();

            var t1 = TaskHelper.Run(() =>
            {
                var CPPP = new CoolPropPropertyPackage();
                CPPP.ComponentName = "CoolProp";
                plist.Add(CPPP);

                var CPIPP = new CoolPropIncompressiblePurePropertyPackage();
                CPIPP.ComponentName = "CoolProp (Incompressible Fluids)";
                CPIPP.ComponentDescription = "CoolProp (Incompressible Fluids)";
                plist.Add(CPIPP);

                var CPIMPP = new CoolPropIncompressibleMixturePropertyPackage();
                CPIMPP.ComponentName = "CoolProp (Incompressible Mixtures)";
                CPIMPP.ComponentDescription = "CoolProp (Incompressible Mixtures)";
                plist.Add(CPIMPP);

                var STPP = new SteamTablesPropertyPackage();
                STPP.ComponentName = "Steam Tables (IAPWS-IF97)";
                plist.Add(STPP);

                var SEAPP = new SeawaterPropertyPackage();
                SEAPP.ComponentName = "Seawater IAPWS-08";
                plist.Add(SEAPP);
            });

            var t2 = TaskHelper.Run(() =>
            {

                var PRPP = new PengRobinsonPropertyPackage();
                PRPP.ComponentName = "Peng-Robinson (PR)";
                plist.Add(PRPP);

            });

            var t3 = TaskHelper.Run(() =>
            {

                var PRSV2PP = new PRSV2PropertyPackage();
                PRSV2PP.ComponentName = "Peng-Robinson-Stryjek-Vera 2 (PRSV2-M)";
                plist.Add(PRSV2PP);

                var PRSV2PPVL = new PRSV2VLPropertyPackage();
                PRSV2PPVL.ComponentName = "Peng-Robinson-Stryjek-Vera 2 (PRSV2-VL)";
                plist.Add(PRSV2PPVL);

            });

            var t4 = TaskHelper.Run(() =>
            {

                var SRKPP = new SRKPropertyPackage();
                SRKPP.ComponentName = "Soave-Redlich-Kwong (SRK)";
                plist.Add(SRKPP);

            });

            var t6 = TaskHelper.Run(() =>
            {

                var UPP = new UNIFACPropertyPackage();
                UPP.ComponentName = "UNIFAC";
                plist.Add(UPP);

                var ULLPP = new UNIFACLLPropertyPackage();
                ULLPP.ComponentName = "UNIFAC-LL";
                plist.Add(ULLPP);

                var MUPP = new MODFACPropertyPackage();
                MUPP.ComponentName = "Modified UNIFAC (Dortmund)";
                plist.Add(MUPP);

                var NUPP = new NISTMFACPropertyPackage();
                NUPP.ComponentName = "Modified UNIFAC (NIST)";
                plist.Add(NUPP);

            });

            var t10 = TaskHelper.Run(() =>
            {

                var WPP = new WilsonPropertyPackage();
                WPP.ComponentName = "Wilson";
                plist.Add(WPP);

                var NRTLPP = new NRTLPropertyPackage();
                NRTLPP.ComponentName = "NRTL";
                plist.Add(NRTLPP);

                var UQPP = new UNIQUACPropertyPackage();
                UQPP.ComponentName = "UNIQUAC";
                plist.Add(UQPP);

                var CSLKPP = new ChaoSeaderPropertyPackage();
                CSLKPP.ComponentName = "Chao-Seader";
                plist.Add(CSLKPP);

                var GSLKPP = new GraysonStreedPropertyPackage();
                GSLKPP.ComponentName = "Grayson-Streed";
                plist.Add(GSLKPP);

                var RPP = new RaoultPropertyPackage();
                RPP.ComponentName = "Raoult's Law";
                plist.Add(RPP);

                var LKPPP = new LKPPropertyPackage();
                LKPPP.ComponentName = "Lee-Kesler-Plöcker";
                plist.Add(LKPPP);

            });

            var t11 = TaskHelper.Run(() =>
            {

                var ISPP = new IdealElectrolytePropertyPackage();
                plist.Add(ISPP);

                var BOPP = new BlackOilPropertyPackage();
                BOPP.ComponentName = "Black Oil";
                plist.Add(BOPP);

                var GERGPP = new GERG2008PropertyPackage();
                plist.Add(GERGPP);

                var PCSAFTPP = new PCSAFT2PropertyPackage();
                plist.Add(PCSAFTPP);

                var PR78PP = new PengRobinson1978PropertyPackage();
                PR78PP.ComponentName = "Peng-Robinson 1978 (PR78)";
                plist.Add(PR78PP);

                var PR78Adv = new PengRobinson1978AdvancedPropertyPackage();
                plist.Add(PR78Adv);

                var SRKAdv = new SoaveRedlichKwongAdvancedPropertyPackage();
                plist.Add(SRKAdv);

            });

            Task.WaitAll(t1, t2, t3, t4, t6, t10, t11);

            foreach (var pp in plist)
            {
                AvailablePropertyPackages.Add(((ICapeIdentification)pp).ComponentName, pp);
            }

            var otherpps = SharedClasses.Utility.LoadAdditionalPropertyPackages();

            foreach (var pp in otherpps)
            {
                if (!AvailablePropertyPackages.ContainsKey(((ICapeIdentification)pp).ComponentName))
                    AvailablePropertyPackages.Add(((ICapeIdentification)pp).ComponentName, pp);
                else
                    Console.WriteLine(String.Format("Error adding External Property Package '{0}'. Check the 'ppacks' and 'extenders' folders for duplicate items.", ((ICapeIdentification)pp).ComponentName));
            }

            if (!Settings.IsRunningOnMono())
            {
                var COPP = new CAPEOPENPropertyPackage();
                COPP.ComponentName = "CAPE-OPEN";
                AvailablePropertyPackages.Add(COPP.ComponentName.ToString(), COPP);
            }

            // compounds

            if (AvailableCompounds.Count() > 0) return;

            var addedcomps = new List<String>();
            var casnumbers = new List<String>();

            var csdb = new Thermodynamics.Databases.ChemSep();
            csdb.Load();
            var cpa = csdb.Transfer();
            foreach (ConstantProperties cp in cpa)
            { if (!AvailableCompounds.ContainsKey(cp.Name)) AvailableCompounds.Add(cp.Name, cp); }

            var cpdb = new Thermodynamics.Databases.CoolProp();
            cpdb.Load();
            cpa = cpdb.Transfer();
            addedcomps = AvailableCompounds.Keys.Select((x) => x.ToLower()).ToList();
            foreach (ConstantProperties cp in cpa)
            { if (!AvailableCompounds.ContainsKey(cp.Name)) AvailableCompounds.Add(cp.Name, cp); }

            var bddb = new Thermodynamics.Databases.Biodiesel();
            bddb.Load();
            cpa = bddb.Transfer();
            addedcomps = AvailableCompounds.Keys.Select((x) => x.ToLower()).ToList();
            foreach (ConstantProperties cp in cpa)
            { if (!AvailableCompounds.ContainsKey(cp.Name)) AvailableCompounds.Add(cp.Name, cp); }

            var chedl = new Thermodynamics.Databases.ChEDL_Thermo();
            chedl.Load();
            cpa = chedl.Transfer().ToArray();

            addedcomps = AvailableCompounds.Keys.Select((x) => x.ToLower()).ToList();
            casnumbers = AvailableCompounds.Values.Select((x) => x.CAS_Number).ToList();

            foreach (ConstantProperties cp in cpa)
            {
                if (!addedcomps.Contains(cp.Name.ToLower()) && !addedcomps.Contains(cp.Name))
                    if (!casnumbers.Contains(cp.CAS_Number))
                        if (!AvailableCompounds.ContainsKey(cp.Name)) AvailableCompounds.Add(cp.Name, cp);
            }

            var elec = new Thermodynamics.Databases.Electrolyte();
            elec.Load();
            cpa = elec.Transfer().ToArray();
            addedcomps = AvailableCompounds.Keys.Select((x) => x.ToLower()).ToList();
            foreach (ConstantProperties cp in cpa)
            { if (!AvailableCompounds.ContainsKey(cp.Name)) AvailableCompounds.Add(cp.Name, cp); }

            var comps = Thermodynamics.Databases.UserDB.LoadAdditionalCompounds();
            foreach (ConstantProperties cp in comps)
            { if (!AvailableCompounds.ContainsKey(cp.Name)) AvailableCompounds.Add(cp.Name, cp); }

            using (var filestr = Assembly.GetAssembly(elec.GetType()).GetManifestResourceStream("DWSIM.Thermodynamics.FoodProp.xml"))
            {
                var fcomps = Thermodynamics.Databases.UserDB.ReadComps(filestr);
                foreach (var cp in fcomps)
                {
                    cp.CurrentDB = "FoodProp";
                    if (!AvailableCompounds.ContainsKey(cp.Name)) AvailableCompounds.Add(cp.Name, cp);
                }
            }

            csdb.Dispose();
            cpdb.Dispose();
            chedl.Dispose();

        }

        [DispId(0)]
        public string GetVersion()
        {

            var version = Assembly.GetExecutingAssembly().GetName().Version;
            var date = File.GetLastWriteTimeUtc(Assembly.GetExecutingAssembly().Location).ToString();

            return String.Format("DWSIM version {0} ({1})", version, date);

        }

        static Assembly LoadAssembly(object sender, ResolveEventArgs args)
        {
            var directories = new List<string>
            {
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "extenders"),
                Directory.GetParent(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)).FullName,
                Path.Combine(Directory.GetParent(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)).FullName, "extenders"),
                Directory.GetCurrentDirectory(),
                Path.Combine(Directory.GetCurrentDirectory(), "extenders")
            };

            foreach (var dir in directories)
            {
                var fullPath = Path.Combine(dir, new AssemblyName(args.Name).Name + ".dll");
                if (File.Exists(fullPath))
                {
                    var assembly = Assembly.LoadFrom(fullPath);
                    return assembly;
                }
            }

            return null;

        }

        [DispId(1)]
        public IFlowsheet LoadFlowsheet(string filepath, Action UIUpdHandler = null)
        {
            Settings.AutomationMode = true;
            Settings.CultureInfo = "en";
            var fsheet = new Flowsheet2(null, UIUpdHandler);
            fsheet.SupressDataLoading = true;
            fsheet.AvailableCompounds = AvailableCompounds;
            fsheet.AvailablePropertyPackages = AvailablePropertyPackages;
            fsheet.SetResourcesManager(rm);
            fsheet.SetPropertyResourcesManager(prm);
            fsheet.Init();
            if (System.IO.Path.GetExtension(filepath).ToLower().EndsWith("z"))
            {
                fsheet.LoadZippedXML(filepath);
            }
            else
            {
                fsheet.LoadFromXML(XDocument.Load(filepath));
            }
            return fsheet;
        }

        [DispId(2)]
        public IFlowsheet LoadFlowsheet2(string filepath)
        {
            Settings.AutomationMode = true;
            Settings.CultureInfo = "en";
            var fsheet = new Flowsheet2(null, null);
            fsheet.SupressDataLoading = true;
            fsheet.AvailableCompounds = AvailableCompounds;
            fsheet.AvailablePropertyPackages = AvailablePropertyPackages;
            fsheet.SetResourcesManager(rm);
            fsheet.SetPropertyResourcesManager(prm);
            fsheet.Init();
            if (System.IO.Path.GetExtension(filepath).ToLower().EndsWith("z"))
            {
                fsheet.LoadZippedXML(filepath);
            }
            else
            {
                fsheet.LoadFromXML(XDocument.Load(filepath));
            }
            return fsheet;
        }

        [DispId(3)]
        public void ReleaseResources()
        {
            rm = null;
            prm = null;
            AvailablePropertyPackages?.Clear();
            AvailableCompounds?.Clear();
        }

        [DispId(4)]
        public void SaveFlowsheet(IFlowsheet flowsheet, string filepath, bool compressed)
        {
            ((Flowsheet2)flowsheet).SaveSimulation(filepath);
        }

        [DispId(5)]
        public void CalculateFlowsheet(IFlowsheet flowsheet, ISimulationObject sender)
        {
            Settings.CalculatorActivated = true;
            Settings.SolverBreakOnException = true;
            ((Flowsheet2)flowsheet).SolveFlowsheet2();
        }

        [DispId(6)]
        public void CalculateFlowsheet2(IFlowsheet flowsheet)
        {
            Settings.CalculatorActivated = true;
            Settings.SolverBreakOnException = true;
            ((Flowsheet2)flowsheet).SolveFlowsheet2();
        }

        [DispId(7)]
        public void CalculateFlowsheet3(IFlowsheet flowsheet, int timeout_seconds)
        {
            Settings.CalculatorActivated = true;
            Settings.SolverBreakOnException = true;
            Settings.SolverTimeoutSeconds = timeout_seconds;
            ((Flowsheet2)flowsheet).SolveFlowsheet2();
        }

        [DispId(8)]
        public List<Exception> CalculateFlowsheet4(IFlowsheet flowsheet)
        {
            Settings.CalculatorActivated = true;
            Settings.SolverBreakOnException = true;
            return ((Flowsheet2)flowsheet).SolveFlowsheet2();
        }

        [DispId(9)]
        public void SaveFlowsheet2(IFlowsheet flowsheet, string filepath)
        {
            SaveFlowsheet(flowsheet, filepath, true);
        }

        [DispId(10)]
        public IFlowsheet CreateFlowsheet()
        {
            Settings.AutomationMode = true;
            var f = new Flowsheet2(null, null);
            f.SupressDataLoading = true;
            f.AvailableCompounds = AvailableCompounds;
            f.AvailablePropertyPackages = AvailablePropertyPackages;
            f.SetResourcesManager(rm);
            f.SetPropertyResourcesManager(prm);
            f.Init();
            return f;
        }

        public object GetMainWindow()
        {
            throw new NotImplementedException();
        }

        public IFlowsheet LoadFlowsheet(string filepath)
        {
            try
            {
                return LoadFlowsheet(filepath, null);
            }
            catch (Exception ex)
            {
                Logging.Logger.LogError("Automation Error (LoadFlowsheet)", ex);
                throw ex;
            }
        }

        List<Exception> AutomationInterface.CalculateFlowsheet2(IFlowsheet flowsheet)
        {
            try
            {
                return CalculateFlowsheet4(flowsheet);
            }
            catch (Exception ex)
            {
                Logging.Logger.LogError("Automation Error (CalculateFlowsheet2)", ex);
                throw ex;
            }
        }

        List<Exception> AutomationInterface.CalculateFlowsheet3(IFlowsheet flowsheet, int timeout_seconds)
        {
            try
            {
                Settings.SolverTimeoutSeconds = timeout_seconds;
                return CalculateFlowsheet4(flowsheet);
            }
            catch (Exception ex)
            {
                Logging.Logger.LogError("Automation Error (CalculateFlowsheet3)", ex);
                throw ex;
            }
        }

        private List<Assembly> LoadExtenderDLLs()
        {
            List<Assembly> extenderdlls = new List<Assembly>();
            if (Directory.Exists(SharedClasses.Utility.GetExtendersRootDirectory()))
            {
                DirectoryInfo dinfo = new DirectoryInfo(SharedClasses.Utility.GetExtendersRootDirectory());
                FileInfo[] files = dinfo.GetFiles("*Extensions*.dll");
                if (!(files == null))
                {
                    foreach (FileInfo fi in files)
                    {
                        extenderdlls.Add(Assembly.LoadFrom(fi.FullName));
                    }
                }
            }
            return extenderdlls;
        }

        List<IExtenderCollection> GetExtenders(List<Assembly> alist)
        {
            List<Type> availableTypes = new List<Type>();
            foreach (var currentAssembly in alist)
            {
                try
                {
                    availableTypes.AddRange(currentAssembly.GetExportedTypes());
                }
                catch
                { }
            }
            var extList = availableTypes.FindAll(t => t.GetInterfaces().Contains(typeof(IExtenderCollection)));
            return extList.ConvertAll(t => (IExtenderCollection)Activator.CreateInstance(t));
        }

        void LoadExtenders()
        {

            List<IExtenderCollection> extlist = GetExtenders(LoadExtenderDLLs());

            foreach (var extender in extlist)
            {
                try
                {
                    if (extender.Level == ExtenderLevel.MainWindow)
                    {
                        foreach (var item in extender.Collection)
                        {
                            var load = false;
                            if (item is IExtender5) load = ((IExtender5)item).LoadInAutomationMode;
                            if (load)
                            {
                                item.SetMainWindow(null);
                                item.Run();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.Logger.LogError("Extender Initialization", ex);
                }
            }
        }

    }

}