Source

BlueGo / BlueGo / FormMain.cs

Full commit
   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
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using BlueGo.GUI;
using System.Net.Mail;
using System.Management;
using System.Xml.Linq;
using System.Xml;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace BlueGo
{
    public partial class FormMain : Form
    {    
        string Qt4_8_3DownloadURL = @"http://releases.qt-project.org/qt4/source/qt-everywhere-opensource-src-4.8.3.zip";
        string Qt4_8_3ZipFilename = "qt-everywhere-opensource-src-4.8.3.zip";

        string jomURL = @"ftp://ftp.qt.nokia.com/jom/jom108.zip";

        int coreCount = 0;

        static bool is64BitProcess = (IntPtr.Size == 8);
        static bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();

        [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool IsWow64Process(
            [In] IntPtr hProcess,
            [Out] out bool wow64Process
        );

        public static bool InternalCheckIsWow64()
        {
            if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
                Environment.OSVersion.Version.Major >= 6)
            {
                using (Process p = Process.GetCurrentProcess())
                {
                    bool retVal;
                    if (!IsWow64Process(p.Handle, out retVal))
                    {
                        return false;
                    }
                    return retVal;
                }
            }
            else
            {
                return false;
            }
        }



    

        // perl strawbery

        public FormMain()
        {
            InitializeComponent();

            
            foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
            {
                coreCount += int.Parse(item["NumberOfCores"].ToString());
            }
        }

        void sendMail()
        {
            if (!BlueGo.GUI.PreferencesManager.Instance.SendReportEmail)
                return;

            string strVon = PreferencesManager.Instance.User;
            string strAn = PreferencesManager.Instance.Subscriber;
            string strSmtpServer = PreferencesManager.Instance.SmtpServer;
            string strUser = PreferencesManager.Instance.User;
            string strPasswort = PreferencesManager.Instance.Password;

            string host = strSmtpServer;
            int port = int.Parse(PreferencesManager.Instance.Port);

            SmtpClient client = new SmtpClient(host, port);

            System.Net.NetworkCredential nc = new System.Net.NetworkCredential(strUser, strPasswort);
            client.Credentials = nc;

            client.EnableSsl = true;
            
            MailMessage mail = new MailMessage();
            MailAddress from = new MailAddress(strVon);
            mail.To.Add(strAn);
            mail.From = from;
            mail.Subject = "BUWDeployment";

            mail.Body = "Hello it´s me the BUWDeployer";

            // collect some info for mail
            string ComputerName = System.Windows.Forms.SystemInformation.ComputerName.ToString();
            IPHostEntry Host = Dns.GetHostEntry(Dns.GetHostName());

            mail.Body += "\n";
            mail.Body += "Computer Name: " + ComputerName;

            foreach (IPAddress ipaddress in Host.AddressList)
            {
                mail.Body += "\n";
                mail.Body += "IP           : " + ipaddress.ToString();   
            }

            mail.Body += "\n";
            mail.Body += "ProcessorCount: " + Environment.ProcessorCount;
            mail.Body += "\n";
            mail.Body += "Is64BitOperatingSystem: " + Environment.Is64BitOperatingSystem;
            mail.Body += "\n";
            mail.Body += "OSVersion: " + Environment.OSVersion;
            mail.Body += "\n";
            mail.Body += "UserName: " + Environment.UserName;
            mail.Body += "Cpu Caption: " + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuCaption();
            mail.Body += "\n";
            mail.Body += "Cpu Cores: " + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuCores();
            mail.Body += "\n";
            mail.Body += "Cpu Id: " + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuId();
            mail.Body += "\n";
            mail.Body += "Cpu Socket Designation" + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuSocketDesignation();
            mail.Body += "\n";
            mail.Body += "Cpu's current operating voltage: " + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuVoltage();
            mail.Body += "\n";
            mail.Body += "Cpu's Manufacturer: " + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuManufacturer();
            mail.Body += "\n";
            mail.Body += "Cpu Number of logical processors: " + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuNumberOfLogicalProcessors();
            mail.Body += "\n";
            mail.Body += "Cpu's Data width (32 or 64bit): " + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuDataWidth();
            mail.Body += "\n";
            mail.Body += "Cpu speed is (in mega-hertz): " + WMI_ProcessorInformation.WMI_Processor_Information.GetCpuClockSpeed();
            mail.Body += "\n";

            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration");

            string graphicsCard = string.Empty;
            foreach (ManagementObject mo in searcher.Get())
            {
                foreach (PropertyData property in mo.Properties)
                {
                    if (property.Name == "Description")
                    {
                        graphicsCard = property.Value.ToString();

                        mail.Body += "\n";
                        mail.Body += "graphicsCard: " + graphicsCard;
                    }
                }
            }


            try
            {
                client.Send(mail);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        void sendMail(string Text)
        {
            string strVon = PreferencesManager.Instance.User;
            string strAn = PreferencesManager.Instance.Subscriber;
            string strSmtpServer = PreferencesManager.Instance.SmtpServer;
            string strUser = PreferencesManager.Instance.User;
            string strPasswort = PreferencesManager.Instance.Password;

            string host = strSmtpServer;
            int port = int.Parse(PreferencesManager.Instance.Port);


            SmtpClient client = new SmtpClient(host, port);

            System.Net.NetworkCredential nc = new System.Net.NetworkCredential(strUser, strPasswort);
            client.Credentials = nc;

            client.EnableSsl = true;

            MailMessage mail = new MailMessage();
            MailAddress from = new MailAddress(strVon);
            mail.To.Add(strAn);
            mail.From = from;
            mail.Subject = "BUWDeployment";

            mail.Body = Text;

            string ComputerName = System.Windows.Forms.SystemInformation.ComputerName.ToString();
            mail.Body += "\n";
            mail.Body += "Computer Name: " + ComputerName;

            try
            {
                client.Send(mail);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public static void Decompress(string filename, string destinationFolder)
        {
            string sevenZipExePath = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + "7z.exe";

            if (!System.IO.File.Exists(sevenZipExePath))
            {
                throw new Exception("Could not locate 7zip - maybe installation failed. Tried to use 7z.exe from " + sevenZipExePath );
            }

            if(!is64BitOperatingSystem)
            {
                throw new Exception("Expecting a 64 bit operating system. You are running not a x64 operating system. 7z ");
            }

            // path needs not
            //CheckDestinationFolder(destinationFolder);

            try
            {
                Process p = new Process();
                ProcessStartInfo info = new ProcessStartInfo(sevenZipExePath, "x -o" + destinationFolder + " " + filename);
                p.StartInfo = info;
                p.Start();
                p.WaitForExit();

                if (p.ExitCode != 0)
                    throw new Exception("Decompressing failed. Maybe download is invalid.");
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        void DownloadAndBuildQT4_8_3_x64()
        {
            string destinationFolder = DetermineDestinationFolder();

            if (!Directory.Exists(destinationFolder))
            {
                Directory.CreateDirectory(destinationFolder);
            }
            message("downloading QT");

            string thirdpartyDirectoryPath = PreferencesManager.Instance.ThirdPartyDownloadFolder;

            // Download Qt
            DownloadFileFromURL(Qt4_8_3DownloadURL, destinationFolder + Qt4_8_3ZipFilename);

            message("extracting QT");

            // Extract Qt
            Decompress(destinationFolder + Qt4_8_3ZipFilename, destinationFolder);

            eCompiler compilerType = DetermineSelectedCompiler();
            if(compilerType == eCompiler.VS2012)
            {
                // patch Qt 4.8.3
                message("patching Qt 4.8.3");

                System.Reflection.Assembly a = System.Reflection.Assembly.GetEntryAssembly();
                string baseDir = System.IO.Path.GetDirectoryName(a.Location);
                string qmakeConfigPath = baseDir + @"\qt4.8.3vs2012patch\qmake.conf";
                
                if (!File.Exists(qmakeConfigPath))
                    throw new Exception("File " + qmakeConfigPath + " does not exist");

                File.Copy(
                    qmakeConfigPath,
                    destinationFolder + @"qt-everywhere-opensource-src-4.8.3\mkspecs\win32-msvc2010\qmake.conf", true);

                File.Copy(
                  @"qt4.8.3vs2012patch\HashSet.h",
                  destinationFolder + @"qt-everywhere-opensource-src-4.8.3\src\3rdparty\webkit\Source\JavaScriptCore\wtf\HashSet.h", true);
            }

            message("configure qt");

            configureQT_4_8_3();
            
            message("building qt");

            buildQT4_8_3();

            message("Finished buidling qt  - - - DONE");

            UnlockQtBuildButton();
        }

        string DetermineDestinationFolder()
        {
            string destinationFolder = PreferencesManager.Instance.ThirdPartyDownloadFolder + "/vs2010/x64/";

            eCompiler compilerType = DetermineSelectedCompiler();
            if (compilerType == eCompiler.VS2012)
            {
                destinationFolder = PreferencesManager.Instance.ThirdPartyDownloadFolder + "/vs2012/x64/";
            }
            else if (compilerType == eCompiler.VS2010)
            {
                destinationFolder = PreferencesManager.Instance.ThirdPartyDownloadFolder + "/vs2010/x64/";
            }
            else
                throw new Exception("Invalid compiler");

            return destinationFolder;
        }

        void DownloadAndBuildBoost_x64()
        {
            try
            {
                // Where to download and build boost?
                string destinationFolder = DetermineDestinationFolder();

                if (!Directory.Exists(destinationFolder))
                {
                    Directory.CreateDirectory(destinationFolder);
                }

                message("Downloading boost...");

                eBoostVersion boostVersion = DetermineSelectedBoostVersion();

                string boostDownloadURL = BoostInfo.GetBoostDownloadURL(boostVersion);
                string boostZIPFilename = BoostInfo.GetBoostZipFileName(boostVersion);

                // todo: Remove old build folder
                //if (boostVersion == eBoostVersion.Boost1_51_0)
                //{
                    //string destinationDir = destinationFolder + "boost_1_51_0";
                    //if(Directory.Exists(destinationDir))
                    //{
                    //    Directory.Delete(destinationDir, true);
                    //}
                //}

                // Download boost
                // Check if URL is valid
                bool validUrl = RemoteFileExists(boostDownloadURL);
                if (!validUrl)
                {
                    throw new Exception("Url " + boostDownloadURL + " is not valid.");
                }
                       
                DownloadFileFromURL(boostDownloadURL, destinationFolder + boostZIPFilename);

                message("Start to unzip boost...");

                if(boostVersion == eBoostVersion.Boost1_51_0)
                {
                    FileInfo fi = new FileInfo(destinationFolder + boostZIPFilename);
                    long fileLength = fi.Length;

                    if (fileLength != 91365553)
                    {
                        MessageBox.Show("Invalid file size of " + boostZIPFilename + " Size in bytes should be 91365553");
                        //throw new Exception("Invalid file size of " + boostZIPFilename + " Size in bytes should be 91365553");
                    }
                }

                // Unzip Boost 
                Decompress(destinationFolder + "/" + boostZIPFilename, destinationFolder);

                message("boost has been unzipped!");


                message("start building boost...");

                // Build boost
                if (boostVersion == eBoostVersion.Boost1_51_0)
                {
                    buildBoost_1_51_0_x64(destinationFolder);
                }
                else
                {
                    bootstrapBoost_1_52_0_x64(destinationFolder);
                    buildBoost_1_52_0_x64(destinationFolder);
                }

                message("boost successfully built!");

                UnlockBoostBuildButton();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        ///
        /// Checks the file exists or not.
        ///
        /// The URL of the remote file.
        /// True : If the file exits, False if file not exists
        private bool RemoteFileExists(string url)
        {
            try
            {
                //Creating the HttpWebRequest
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //Setting the Request method HEAD, you can also use GET too.
                request.Method = "HEAD";
                //Getting the Web Response.
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //Returns TURE if the Status code == 200
                return (response.StatusCode == HttpStatusCode.OK);
            }
            catch
            {
                //Any exception will returns false.
                return false;
            }
        }

        private void buildBoost_1_51_0_x64(string destinationFolder)
        {
            Process p = new Process();
            ProcessStartInfo info = null;
            
            eCompiler compilerType = DetermineSelectedCompiler();
            if (compilerType == eCompiler.VS2012)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" amd64");
            if (compilerType == eCompiler.VS2010)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" amd64");
                       
            info.RedirectStandardInput = true;
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;

            p.StartInfo = info;
            p.Start();

            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    if(compilerType == eCompiler.VS2010)
                    {
                        eBoostVersion version = DetermineSelectedBoostVersion();
                        string extractFolderName = BoostInfo.GetBoostInfo(version).ExtractFolderName;


                        sw.WriteLine("cd " + destinationFolder + extractFolderName); //"boost_1_51_0-x64");
                        sw.WriteLine("bootstrap");
                        sw.WriteLine(@".\b2 -j" + Math.Max(2, coreCount) + " --toolset=msvc-10.0 address-model=64 --build-type=complete stage");
                    }
                    else
                    {
                        eBoostVersion version = DetermineSelectedBoostVersion();
                        string extractFolderName = BoostInfo.GetBoostInfo(version).ExtractFolderName;

                        // go to boost root directory
                        sw.WriteLine("cd " + destinationFolder + extractFolderName);

                        // should work like this 

                        //sw.WriteLine("bootstrap.bat");
                        //sw.WriteLine(@".\b2 -j" + Math.Max(2, coreCount) + " --toolset=msvc-11.0 address-model=64 --build-type=complete stage"); // todo find out number of cores...

                        // workaround

                        // change directory to boost_1_51_0-x64\tools\build\v2
                        string path = System.Windows.Forms.Application.StartupPath;
                        File.Copy(path + "\\b2.exe", destinationFolder + extractFolderName + "\\b2.exe");
                        sw.WriteLine(@".\b2 -j" + Math.Max(2, coreCount) + " --toolset=msvc-11.0 address-model=64 --build-type=complete stage"); // todo find out number of cores...
                    }
                }
            }

            readStandardOutput(p);
            readStandardError(p);

            p.WaitForExit();
            p.Close();
        }
        
        private void bootstrapBoost_1_52_0_x64(string destinationFolder)
        {
            Process p = new Process();
            ProcessStartInfo info = null;

            eCompiler compilerType = DetermineSelectedCompiler();
            if (compilerType == eCompiler.VS2012)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" amd64");
            if (compilerType == eCompiler.VS2010)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" amd64");

            info.RedirectStandardInput = true;
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;

            p.StartInfo = info;
            p.Start();

            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    eBoostVersion version = DetermineSelectedBoostVersion();
                    string extractFolderName = BoostInfo.GetBoostInfo(version).ExtractFolderName;

                    sw.WriteLine("cd " + destinationFolder + extractFolderName + @"\tools\build\v2"); //"boost_1_51_0-x64");
                    sw.WriteLine("bootstrap");
                }
            }

            readStandardOutput(p);
            readStandardError(p);

            p.WaitForExit();
            p.Close();
        }

        private void buildBoost_1_52_0_x64(string destinationFolder)
        {
            Process p = new Process();
            ProcessStartInfo info = null;

            eCompiler compilerType = DetermineSelectedCompiler();
            if (compilerType == eCompiler.VS2012)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" amd64");
            if (compilerType == eCompiler.VS2010)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" amd64");

            info.RedirectStandardInput = true;
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;

            p.StartInfo = info;
            p.Start();

            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    eBoostVersion version = DetermineSelectedBoostVersion();
                    string extractFolderName = BoostInfo.GetBoostInfo(version).ExtractFolderName;

                    File.Copy(destinationFolder + extractFolderName + @"\tools\build\v2" + "\\b2.exe", destinationFolder + extractFolderName + "\\b2.exe");
                    sw.WriteLine("cd " + destinationFolder + extractFolderName);
                    sw.WriteLine(@".\b2 -j" + Math.Max(2, coreCount) + " toolset=msvc --build-type=complete stage");
                }
            }

            readStandardOutput(p);
            readStandardError(p);

            p.WaitForExit();
            p.Close();
        }

        private void buildBoost_x642(string destinationFolder)
        { 
            Process p = new Process();
            ProcessStartInfo info = null;

            eCompiler compilerType = DetermineSelectedCompiler();
            if (compilerType == eCompiler.VS2012)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" amd64");
            if (compilerType == eCompiler.VS2010)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" amd64");
                       
            info.RedirectStandardInput = true;
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;

            p.StartInfo = info;
            p.Start();

            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    if(compilerType == eCompiler.VS2010)
                    {
                        eBoostVersion version = DetermineSelectedBoostVersion();
                        string extractFolderName = BoostInfo.GetBoostInfo(version).ExtractFolderName;


                        sw.WriteLine("cd " + destinationFolder + extractFolderName); //"boost_1_51_0-x64");
                        sw.WriteLine("bootstrap");
                        sw.WriteLine(@".\b2 -j" + Math.Max(2,coreCount) + " --toolset=msvc-10.0 address-model=64 --build-type=complete stage"); 
                    }
                    else
                    {

                        eBoostVersion version = DetermineSelectedBoostVersion();
                        string extractFolderName = BoostInfo.GetBoostInfo(version).ExtractFolderName;


                        sw.WriteLine("cd " + destinationFolder + extractFolderName); 
                        sw.WriteLine("bootstrap");
                        sw.WriteLine(@".\b2 -j" + Math.Max(2, coreCount) + " --toolset=msvc-11.0 address-model=64 --build-type=complete stage"); 

                        /*
                        eBoostVersion version = DetermineSelectedBoostVersion();
                        string extractFolderName = BoostInfo.GetBoostInfo(version).ExtractFolderName;

                        // go to boost root directory
                        sw.WriteLine("cd " + destinationFolder + extractFolderName);
                    
                        // should work like this 

                        //sw.WriteLine("bootstrap.bat");
                        //sw.WriteLine(@".\b2 -j" + Math.Max(2, coreCount) + " --toolset=msvc-11.0 address-model=64 --build-type=complete stage"); // todo find out number of cores...

                        // workaround

                        // change directory to boost_1_51_0-x64\tools\build\v2
                        string path = System.Windows.Forms.Application.StartupPath;
                        File.Copy(path + "\\b2.exe", destinationFolder + extractFolderName + "\\b2.exe");
                        sw.WriteLine(@".\b2 -j" + Math.Max(2, coreCount) + " --toolset=msvc-11.0 address-model=64 --build-type=complete stage"); // todo find out number of cores...
                         */
                    }
                }
            }

            readStandardOutput(p);
            readStandardError(p);

            p.WaitForExit();
            p.Close();
        }

        private void buildBoost1_49_0_gcc(string destinationFolder)
        {
            Process p = new Process();
            ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
            info.RedirectStandardInput = true;
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;

            p.StartInfo = info;
            p.Start();

            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    sw.WriteLine("cd " + destinationFolder + "boost_1_49_0-x86");
                    sw.WriteLine("bootstrap.bat gcc");
                    sw.WriteLine(@".\b2 -j" + Math.Max(2, coreCount) + " --toolset=gcc address-model=32 --build-type=complete stage"); // todo find out number of cores...
                }
            }

            readStandardOutput(p);
            readStandardError(p);

            p.WaitForExit();
            p.Close();
        }

        void message(string msg)
        {
            SetWindowTitleStatusInfo(msg);
            
            if(BlueGo.GUI.PreferencesManager.Instance.SendReportEmail)
                sendMail(msg);

            this.Invoke((MethodInvoker)delegate
            {
                listBox1.Items.Add(msg);
                //listBox1.EnsureVisible(listBox1.Items.Count - 1);
            });
        }

        private void readStandardOutput(Process p)
        {
            using (StreamReader sr = p.StandardOutput)
            {
                while (sr.BaseStream.CanRead)
                {
                    string test = sr.ReadLine();

                    if (test == null)
                        break;

                    this.Invoke((MethodInvoker)delegate
                    { 
                        listBox1.Items.Add(test);
                    });
                }
            }
        }

        private void readStandardError(Process p)
        {
            using (StreamReader sr = p.StandardError)
            {
                while (sr.BaseStream.CanRead)
                {
                    string test = sr.ReadLine();

                    if (test == null)
                        break;

                    this.Invoke((MethodInvoker)delegate
                    {
                        listBox1.Items.Add(test);
                    });
                }
            }
        }

        /// <summary>
        /// Function to download a file from URL and save it to local drive
        /// </summary>
        /// <param name="_URL">URL address to download file</param>
        public void DownloadFileFromURL(string _URL, string _SaveAs)
        {
            try
            {
                System.Net.WebClient _WebClient = new System.Net.WebClient();
                // Downloads the resource with the specified URI to a local file.
                _WebClient.DownloadFile(_URL, _SaveAs);
            }
            catch (Exception exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", exception.ToString());

                throw new Exception("Download failed." + exception.ToString());
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                //this.notifyIcon1.ContextMenu = contextMenuStrip1;
                this.ShowInTaskbar = false;
                this.WindowState = FormWindowState.Minimized;
                this.notifyIconBlueDeployment.Visible = true;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.ShowInTaskbar = true;
            this.notifyIconBlueDeployment.Visible = false;
            this.WindowState = FormWindowState.Normal;
        }

        private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_FormPreferences.Clean();
            m_FormPreferences.ShowDialog();
        }

        private void configureQT_4_8_3()
        {
            string destinationFolder = PreferencesManager.Instance.ThirdPartyDownloadFolder + "/vs2010/x64/";
            eCompiler compiler = DetermineSelectedCompiler();
            if (compiler == eCompiler.VS2012)
                destinationFolder = PreferencesManager.Instance.ThirdPartyDownloadFolder + "/vs2012/x64/";
            if (compiler == eCompiler.VS2010)
                destinationFolder = PreferencesManager.Instance.ThirdPartyDownloadFolder + "/vs2010/x64/";

            Process p = new Process();
            ProcessStartInfo info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" amd64");
            info.RedirectStandardInput = true;
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;

            p.StartInfo = info;
            p.Start();


            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    sw.WriteLine("cd " + destinationFolder + "qt-everywhere-opensource-src-4.8.3");
                    sw.WriteLine("configure -mp -opensource -nomake demos -nomake examples -platform win32-msvc2010");
                    sw.WriteLine("y");

                   // sw.WriteLine(@"jom && jom clean");
                }
            }
            
            readStandardOutput(p);
            readStandardError(p);

            //readStandardOutput(p);
            //readStandardError(p);

            p.WaitForExit();
            p.Close();
        }

        private void buildQT4_8_3()
        {
            string destinationFolder = DetermineDestinationFolder();
            eCompiler compiler = DetermineSelectedCompiler();
       
            Process p = new Process();
            ProcessStartInfo info = null;

            if (compiler == eCompiler.VS2010)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" amd64");
            else if (compiler == eCompiler.VS2012)
                info = new ProcessStartInfo("cmd.exe", @"%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" amd64");
            else
                throw new Exception("unknown compiler.");
           
            info.RedirectStandardInput = true;
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = false;

            p.StartInfo = info;
            p.Start();


            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    sw.WriteLine("cd " + destinationFolder + "qt-everywhere-opensource-src-4.8.3");
                    sw.WriteLine(@"nmake");
                }
            }
            
            readStandardOutput(p);

            p.WaitForExit();
            p.Close();
        }

        BlueGo.GUI.FormPrefernces m_FormPreferences = new BlueGo.GUI.FormPrefernces();
 
        List<BlueGo.Data.ApplicationInfo> appInfoList = new List<BlueGo.Data.ApplicationInfo>();

        private void CheckForUpdates()
        {
            try
            {
                WebClient client = new WebClient();
                Stream data = client.OpenRead("http://www.vertexwahn.de/bluego.xml");
                StreamReader reader = new StreamReader(data);
                XmlTextReader xmlReader = new XmlTextReader(reader);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlReader);

                XmlNode xmlInfo = xmlDoc.SelectSingleNode("BlueGo/Info");
                string strVersion = xmlInfo.Attributes["Version"].InnerText;
                string strDownloadLink = xmlInfo.Attributes["DownloadLink"].InnerText;

                if (strVersion != "0.0.5")
                {
                    MessageBox.Show("New version is available (BlueGo " + strVersion + "). It can be downloaded from " + strDownloadLink, "BlueGo");
                }

                reader.Close();
                data.Close();
                reader.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            CheckForUpdates();

            // Fill gui elements
            foreach(BoostInfo bi in BoostInfo.CreateBoostInfoList())
            {
                comboBoxbBoostVersion.Items.Add(BoostInfo.BoostVersionToString(bi.Version));
            }

            if (comboBoxbBoostVersion.Items.Count > 0)
                comboBoxbBoostVersion.SelectedIndex = 0;

            if (comboBoxPlatform.Items.Count > 0)
                comboBoxPlatform.SelectedIndex = 0;

            if (comboBoxCompiler.Items.Count > 0)
                comboBoxCompiler.SelectedIndex = 0;

            if (comboBoxQtVersion.Items.Count > 0)
                comboBoxQtVersion.SelectedIndex = 0;

            appInfoList = BlueGo.Data.ApplicationInfo.Load("applications.xml");

            foreach (BlueGo.Data.ApplicationInfo ai in appInfoList)
            {
                checkedListBoxApplications.Items.Add(ai.Name);
            }
        }

        private void buttonDonloadApplications_Click(object sender, EventArgs e)
        {
            buttonDonloadApplications.Enabled = false;

            if (!Directory.Exists(PreferencesManager.Instance.ApplicationDownloadFolder))
            {
                Directory.CreateDirectory(PreferencesManager.Instance.ApplicationDownloadFolder);
            }

            for(int i = 0; i < checkedListBoxApplications.Items.Count; i++)
            {
                if( checkedListBoxApplications.GetItemChecked(i) )
                {
                    // Download boost
                    DownloadFileFromURL(appInfoList[i].DownloadUrl, PreferencesManager.Instance.ApplicationDownloadFolder + "\\" + appInfoList[i].Filename);
                }
            }
            
            buttonDonloadApplications.Enabled = true;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("BlueGo by Vertexwahn", "BlueGo");
        }

        static void GetInstalled()
        {
            string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
            {
                foreach (string skName in rk.GetSubKeyNames())
                {
                    using (RegistryKey sk = rk.OpenSubKey(skName))
                    {
                        Console.WriteLine(sk.GetValue("DisplayName"));
                    }
                }
            }
        }

        private void buttonQT_Click(object sender, EventArgs e)
        {
            eCompiler compiler = DetermineSelectedCompiler();

            if (!Compiler.IsPresent(compiler))
            {
                ReportCompilerNotPresent(compiler);
                return; // Compiler not present we can not do anything useful
            }
            
            // prevent that user double clicks the qt build button
            buttonBuildQT.Enabled = false;

            // check if perl is available
            if( !System.IO.Directory.Exists(@"C:\strawberry\perl") )
            {
                if (MessageBox.Show("Warning: Perl must be installed in order to build qt. Do you want to continue? (You can use http://strawberryperl.com/) ", "Warning", MessageBoxButtons.OKCancel) != DialogResult.OK)
                {
                    buttonBuildQT.Enabled = true;
                    return;
                }

            }
                    
            Thread t = new Thread(new ThreadStart(DownloadAndBuildQT4_8_3_x64));
            t.Start(); 
        }

        private eBoostVersion DetermineSelectedBoostVersion()
        {
            string text = "";
            this.Invoke((MethodInvoker)delegate()
            {
                text = comboBoxbBoostVersion.Text;
            });


            foreach (BoostInfo bi in BoostInfo.CreateBoostInfoList())
            {
                if (BoostInfo.BoostVersionToString(bi.Version) == text)
                    return bi.Version;
            }

            throw new Exception("Unknown Boost Version.");
        }

        eCompiler DetermineSelectedCompiler()
        {
            string text = "";
            this.Invoke((MethodInvoker)delegate()
            {
                text = comboBoxCompiler.Text;
            });

            if (text == "Microsoft Visual Studio 2010")
            {
                return eCompiler.VS2010;
            }

            if (text == "Microsoft Visual Studio 2012")
            {
                return eCompiler.VS2012;
            }

            throw new Exception("Invalid compiler selected");
            //return eCompiler.Unknown;
        }

        void ReportCompilerNotPresent(eCompiler compiler)
        {
            MessageBox.Show("Error: Selected Compiler is not present.", "BlueGo",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void buttonBoostBuild_Click(object sender, EventArgs e)
        { 
            eCompiler compiler = DetermineSelectedCompiler();

            if (!Compiler.IsPresent(compiler))
            {
                ReportCompilerNotPresent(compiler);
                return; // Compiler not present we can not do anything useful
            }

            // Lock GUI
            buttonBoostBuild.Enabled = false;

            Thread t = new Thread(new ThreadStart(DownloadAndBuildBoost_x64));
            t.Start();
        }

        private static void CheckDestinationFolder(string destinationFolder)
        {
            if (!System.IO.File.Exists(destinationFolder))
            {
                throw new Exception("Destination folder does not exist " + destinationFolder);
            }
        }

        private void SetWindowTitleStatusInfo(String statusInfo)
        {
            string windowTitle = "BlueGo (0.0.5) [" + statusInfo + "]";
        
            this.Invoke((MethodInvoker)delegate()
            {
                this.Text = windowTitle;
            });
        }

        private void UnlockBoostBuildButton()
        {
            this.Invoke((MethodInvoker)delegate()
            {
                this.buttonBoostBuild.Enabled = true;
            });
        }

        private void UnlockQtBuildButton()
        {
            this.Invoke((MethodInvoker)delegate()
            {
                buttonBuildQT.Enabled = false;
            });
        }
    }
}