Example #1
0
        static int Main(string[] args)
        {
            var consoleParams = new ConsoleParameters(args);

            if (consoleParams.VerboseOutput)
            {
                EnableConsoleDebugLog();
            }

            var root = Kernel.Root;

            // Binding UI interfaces
            root.Bind <IUserOutput>().To <ConsoleUserInterface>().InSingletonScope();
            root.Bind <IParameters>().ToConstant(consoleParams).InSingletonScope();

            // Binding special directories
            var suiteRoot = new LocalFileSystemDirectory(Environment.CurrentDirectory);

            root.Bind <IFileSystemDirectory>()
            .ToConstant(suiteRoot)
            .WhenTargetHas <SuiteRootAttribute>();
            root.Bind <IFileSystemDirectory>()
            .ToConstant(suiteRoot.GetChildDirectory("target", createIfMissing: true))
            .WhenTargetHas <TargetRootAttribute>();

            // Binding core services
            Kernel.RegisterCoreBindings();

            // Binding default cache
            var cacheDir = suiteRoot.GetChildDirectory("cache", createIfMissing: true)
                           .GetChildDirectory(consoleParams.Goal, createIfMissing: true);

            root.Bind <IFileSystemDirectory>()
            .ToConstant(cacheDir)
            .WhenTargetHas <CacheRootAttribute>();
            root.Bind <IBuildCache>().To <FileBuildCache>();

            // Loading fix plugins
            root.Load(GetOrderedModuleList(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Bari.Plugins.*.dll"));

            // Initializing the cache cleaner
            root.Bind <ICleanExtension>().ToConstant(new CacheCleaner(cacheDir, root.Get <IBuilderEnumerator>()));

            var process = root.Get <MainProcess>();

            try
            {
                if (process.Run())
                {
                    return(0);
                }
                else
                {
                    return(1);
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = ConsoleColor.Red;
                System.Console.WriteLine(ex.ToString());
                System.Console.ForegroundColor = ConsoleColor.Gray;

                return(2);
            }
        }
Example #2
0
        static void Main(string[] args)
        {
            Program.Parameters = new ParameterParser <ConsoleParameters>().Parse(args);
            if (Program.Parameters.Debug)
            {
                Console.WriteLine("Will start in debug mode...");
            }
            if (Program.Parameters.Reset)
            {
                if (MessageBox.Show("Are you sure you want to wipe all your data and configuration for the Disconnected Client?", "Confirm Reset", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    var appData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OpenIZDC");
                    var cData   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "OpenIZDC");
                    if (Directory.Exists(appData))
                    {
                        Directory.Delete(cData, true);
                    }
                    if (Directory.Exists(appData))
                    {
                        Directory.Delete(appData, true);
                    }
                }
                return;
            }
            String[] directory =
            {
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),      "OpenIZDC"),
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OpenIZDC")
            };

            foreach (var dir in directory)
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }

            // Token validator
            ServicePointManager.DefaultConnectionLimit             = 2;
            ServicePointManager.MaxServicePointIdleTime            = 100;
            TokenValidationManager.SymmetricKeyValidationCallback += (o, k, i) =>
            {
                return(MessageBox.Show(String.Format("Trust issuer {0} with symmetric key?", i), "Token Validation Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes);
            };
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, error) =>
            {
                if (certificate == null || chain == null)
                {
                    return(false);
                }
                else
                {
                    var valid = s_trustedCerts.Contains(certificate.Subject);
                    if (!valid && (chain.ChainStatus.Length > 0 || error != SslPolicyErrors.None))
                    {
                        if (MessageBox.Show(String.Format("The remote certificate is not trusted. The error was {0}. The certificate is: \r\n{1}\r\nWould you like to temporarily trust this certificate?", error, certificate.Subject), "Certificate Error", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                        {
                            return(false);
                        }
                        else
                        {
                            s_trustedCerts.Add(certificate.Subject);
                        }
                    }

                    return(true);
                    //isValid &= chain.ChainStatus.Length == 0;
                }
            };

            // Start up!!!
            try
            {
#if IE
#else
                var settings = new CefSettings()
                {
                    UserAgent = "OpenIZEmbedded"
                };
                Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
                Cef.EnableHighDPISupport();
#endif

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                frmSplash splash = new frmSplash();
                splash.Show();

                bool         started      = false;
                EventHandler startHandler = (o, e) =>
                {
                    started = true;
                };

                frmDisconnectedClient main = null;
                DateTime start             = new DateTime();

                if (!DcApplicationContext.StartContext(new WinFormsDialogProvider()))
                {
                    if (!DcApplicationContext.StartTemporary(new WinFormsDialogProvider()))
                    {
                        MessageBox.Show("There was an error starting up the Disconnected Client. Please see logs in %localappdata%\\log for more information");
                        Application.Exit();
                        Environment.Exit(666);
                        Cef.Shutdown();
                        return;
                    }
                    else
                    {
                        var minims = XamarinApplicationContext.Current.GetService <MiniImsServer>();


                        if (!minims.IsRunning)
                        {
                            minims.Started += startHandler;
                            while (!started && DateTime.Now.Subtract(start).TotalSeconds < 20 && splash.Visible)
                            {
                                Application.DoEvents();
                            }
                        }

                        if (minims.IsRunning)
                        {
                            main = new frmDisconnectedClient("http://127.0.0.1:9200/org.openiz.core/views/settings/splash.html");
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                else
                {
                    DcApplicationContext.Current.Started += startHandler;
                    while (!started && splash.Visible)
                    {
                        Application.DoEvents();
                    }

                    main = new frmDisconnectedClient("http://127.0.0.1:9200/org.openiz.core/splash.html");
                }

                splash.Close();

                if (XamarinApplicationContext.Current.GetService <MiniImsServer>().IsRunning)
                {
                    Application.Run(main);
                }
            }
            catch (Exception e)
            {
                if (MessageBox.Show(String.Format(DisconnectedClient.Core.Resources.Strings.err_startup, e.Message), "Error", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    var bksvc = XamarinApplicationContext.Current.GetService <IBackupService>();
                    bksvc.Backup(OpenIZ.Mobile.Core.Services.BackupMedia.Public);
                    File.Delete(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "OpenIZDC", "OpenIZ.config"));
                    Directory.Delete(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "OpenIZDC"), true);
                }
                else
                {
                    var bksvc = XamarinApplicationContext.Current.GetService <IBackupService>();
                    bksvc.Backup(OpenIZ.Mobile.Core.Services.BackupMedia.Private);
                    File.Delete(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "OpenIZ.config"));
                    Directory.Delete(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "OpenIZDC"), true);
                }
                Cef.Shutdown();
                Application.Exit();
                Environment.Exit(996);
            }
            finally
            {
                Cef.Shutdown();
            }
        }
Example #3
0
        public static void Main(string[] args)
        {
            Application.Init();

            MainClass.Parameters = new ParameterParser <ConsoleParameters>().Parse(args);
            if (MainClass.Parameters.Debug)
            {
                Console.WriteLine("Will start in debug mode...");
            }
            if (MainClass.Parameters.Reset)
            {
                while (true)
                {
                    Console.Write("Are you sure you want to wipe all your data and configuration for the Disconnected Client? [Y/N]");
                    var resp = Console.ReadKey();
                    switch (resp.Key)
                    {
                    case ConsoleKey.Y:
                        var appData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OpenIZDC");
                        var cData   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "OpenIZDC");
                        if (Directory.Exists(appData))
                        {
                            Directory.Delete(cData, true);
                        }
                        if (Directory.Exists(appData))
                        {
                            Directory.Delete(appData, true);
                        }
                        return;

                    case ConsoleKey.N:
                    case ConsoleKey.Escape:
                        return;
                    }
                }
            }
            String[] directory =
            {
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),      "OpenIZDC"),
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OpenIZDC")
            };

            foreach (var dir in directory)
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }

            // Token validator
            TokenValidationManager.SymmetricKeyValidationCallback += (o, k, i) =>
            {
                return(new GtkDialogProvider().Confirm(String.Format("Trust issuer {0} with symmetric key?", i), "Token Validation Error"));
            };
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, error) =>
            {
                System.Diagnostics.Debugger.Break();
                if (certificate == null || chain == null)
                {
                    return(false);
                }
                else
                {
                    var valid = s_trustedCerts.Contains(certificate.Subject);
                    if (!valid && (chain.ChainStatus.Length > 0 || error != SslPolicyErrors.None))
                    {
                        if (!new GtkDialogProvider().Confirm(String.Format("The remote certificate is not trusted. The error was {0}. The certificate is: \r\n{1}\r\nWould you like to temporarily trust this certificate?", error, certificate.Subject), "Certificate Error"))
                        {
                            return(false);
                        }
                        else
                        {
                            s_trustedCerts.Add(certificate.Subject);
                        }
                    }

                    return(true);
                    //isValid &= chain.ChainStatus.Length == 0;
                }
            };

            // Start up!!!
            try
            {
                s_splashWindow = new Window(WindowType.Toplevel);
                s_splashWindow.SetSizeRequest(640, 500);
                s_splashWindow.Decorated = false;
                s_splashWindow.SetPosition(WindowPosition.CenterAlways);
                s_splashWindow.Resizable = false;
                s_splashWindow.ModifyBg(StateType.Normal, new Gdk.Color(255, 255, 255));
                // Add image to the splash window
                var vbox = new VBox();

                var productLabel    = new Label(Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyTitleAttribute>().Title);
                var fontDescription = FontDescription.FromString("Sans Bold 24");
                productLabel.ModifyFont(fontDescription);

                var versionLabel = new Label(String.Format("{0} ({1})", Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion));
                var logoImage    = new Image(Assembly.GetEntryAssembly(), "GtkClient.lib.logo_lg.png");
                logoImage.SetPadding(10, 10);
                m_statusLabel = new Label("Starting Up...");
                m_statusLabel.SetPadding(10, 10);

                vbox.PackStart(productLabel);
                vbox.PackStart(versionLabel);
                vbox.PackStart(logoImage);
                vbox.PackEnd(m_statusLabel);


                ApplicationContext.ProgressChanged += ApplicationContext_ProgressChanged;

                s_splashWindow.Add(vbox);

                s_splashWindow.ShowAll();
                Application.Invoke(StartContext);
                Application.Run();
            }
            catch (Exception e)
            {
                new GtkDialogProvider().Alert(e.ToString());
            }
        }
Example #4
0
        static int Main(string[] args)
        {
            var consoleParams = new ConsoleParameters(args);

            if (consoleParams.VerboseOutput)
            {
                EnableConsoleDebugLog();
            }

            var root = Kernel.Root;

            // Binding UI interfaces
            root.Bind <IUserOutput>().To <ConsoleUserInterface>().InSingletonScope();
            root.Bind <IParameters>().ToConstant(consoleParams).InSingletonScope();

            // Binding special directories
            var suiteRoot = new LocalFileSystemDirectory(Environment.CurrentDirectory);

            root.Bind <IFileSystemDirectory>()
            .ToConstant(suiteRoot)
            .WhenTargetHas <SuiteRootAttribute>();
            root.Bind <IFileSystemDirectory>()
            .ToConstant(suiteRoot.GetChildDirectory("target", createIfMissing: true))
            .WhenTargetHas <TargetRootAttribute>();

            // Binding core services
            Kernel.RegisterCoreBindings();

            // Binding default cache
            var cacheDir = new Lazy <IFileSystemDirectory>(() =>
                                                           suiteRoot.GetChildDirectory("cache", createIfMissing: true)
                                                           .GetChildDirectory(root.Get <Suite>().ActiveGoal.Name, createIfMissing: true));

            root.Bind <Lazy <IFileSystemDirectory> >()
            .ToConstant(cacheDir)
            .WhenTargetHas <CacheRootAttribute>();
            root.Bind <IBuildCache>().To <FileBuildCache>();

            // Loading fix plugins
            var pluginLoader = root.Get <IPluginLoader>();

            foreach (var module in GetOrderedModuleList(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Bari.Plugins.*.dll"))
            {
                pluginLoader.Load(module);
            }

            // Initializing builder store
            Kernel.InitializeBuilderStore();

            // Initializing the cache cleaner
            root.Bind <ICleanExtension>().ToConstant(new CacheCleaner(cacheDir, root.Get <IBuilderEnumerator>(), () => root.Get <ISoftCleanPredicates>()));

            var process = root.Get <MainProcess>();

            try
            {
                if (process.Run())
                {
                    return(0);
                }
                else
                {
                    return(1);
                }
            }
            catch (Exception ex)
            {
                var output = root.Get <IUserOutput>();
                output.Error(ex.ToString());

                return(2);
            }
        }
Example #5
0
        static async Task Main()
        {
            // in the next 60 lines I am just building the project and resolving the vstest console
            // this is specific to this approach, and is not mandatory to be done this way,
            // I am just trying to make the project portable
            Console.WriteLine("Running dotnet --version");
            var dotnetVersion = RunCommand("dotnet", "--version").Trim();

            Console.WriteLine(dotnetVersion);
            Console.WriteLine("Running dotnet --list-sdks");
            var sdks = RunCommand("dotnet", "--list-sdks")
                       .Split(Environment.NewLine)
                       .Select(line => line.Trim())
                       .Where(line => !string.IsNullOrWhiteSpace(line))
                       .ToList();

            sdks.ForEach(Console.WriteLine);

            var currentSdk = sdks.First(line => line.StartsWith(dotnetVersion));
            var sdkPath    = currentSdk.Replace($"{dotnetVersion} [", "").TrimEnd(']');

            Console.WriteLine($"Sdk path is: {sdkPath}");

            var vstestConsolePath = Path.Combine(sdkPath, dotnetVersion, "vstest.console.dll");

            Console.WriteLine($"Test console path is: {vstestConsolePath}");


            Console.WriteLine($"Finding test project.");
            var here            = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var testProjectName = "TestProject1";
            var testProjectPath = Path.GetFullPath(Path.Combine(here, "..", "..", "..", "..", testProjectName, $"{testProjectName}.csproj"));

            Console.WriteLine($"Building test project in path: {testProjectPath}");
            var buildOutput = RunCommand("dotnet", $"build {testProjectPath}");

            Console.WriteLine(buildOutput);

            var dllpath = buildOutput.Split(Environment.NewLine)
                          .Select(line => line.Trim())
                          .First(line => line.EndsWith($"{testProjectName}.dll"))
                          .Replace($"{testProjectName} ->", "")
                          .Trim();

            Console.WriteLine($"Test project dll: {dllpath}");

            var logPath = Path.Combine(here, "logs", "log.txt");

            Directory.CreateDirectory(Path.GetDirectoryName(logPath));
            var consoleParameters = new ConsoleParameters {
                LogFilePath = logPath
            };

            // make the timeout shorter to see errors faster in case we do something wrong
            // and the runner won't start, you can look at the logs after the run, or use
            // DebugView++ to see them in real time
            Environment.SetEnvironmentVariable("VSTEST_CONNECTION_TIMEOUT", "20");

            // THIS is where the interesting code starts :) We make a console wrapper,
            // and point it at our console path, this can be either vstest.console.exe
            // if we are taking it from VS installation, or from Microsoft.TestPlaform
            // nuget package,
            // or vstest.console.dll if we are using the one from dotnet sdk.
            var wrapper = new VsTestConsoleWrapper(vstestConsolePath, consoleParameters);

            Console.WriteLine($"Discovering tests.");
            var discoveryHandler = new DiscoveryHandler();

            // Discover all tests from the assembly.
            // Make sure you don't provide null for the runsettings.
            // Make sure your dll paths are not sorrounded by whitespace.
            // Use the sync api.
            wrapper.DiscoverTests(new[] { dllpath }, "", discoveryHandler);

            var tests = discoveryHandler.DiscoveredTests;

            Console.WriteLine($"Found {tests.Count} tests.");


            var half = tests.Count / 2;

            // split them to two batches
            var firstHalf  = tests.Take(half).ToList();
            var secondHalf = tests.Skip(half).ToList();

            var run1Handler = new RunHandler();
            var run2Handler = new RunHandler();

            // Running each batch
            // Make sure you provide provide at least the root tag for the runsettings.
            wrapper.RunTests(firstHalf, "<RunSettings></RunSettings>", run1Handler);
            Console.WriteLine("First half:");
            run1Handler.TestResults.ForEach(WriteTestResult);

            wrapper.RunTests(secondHalf, "<RunSettings></RunSettings>", run2Handler);
            Console.WriteLine("Second half:");
            run2Handler.TestResults.ForEach(WriteTestResult);

            // Trying it with async
            run1Handler.TestResults.Clear();
            run2Handler.TestResults.Clear();

            // Make sure you provide provide at least the root tag for the runsettings.
            var run1 = wrapper.RunTestsAsync(firstHalf, "<RunSettings></RunSettings>", run1Handler);
            // there is a bug that will report using one of the handlers when the requests come too close together
            // this won't happen for third request. BUT it should not matter to you if you use the same handler for all
            // batches as it is usual.
            var run2 = wrapper.RunTestsAsync(secondHalf, "<RunSettings></RunSettings>", run2Handler);
            await Task.WhenAll(run1, run2);


            Console.WriteLine("First half async:");
            run1Handler.TestResults.ForEach(WriteTestResult);
            Console.WriteLine("Second half async:");
            run2Handler.TestResults.ForEach(WriteTestResult);

            Console.WriteLine("Done.");
            Console.ReadLine();
        }
        public void TraceLevelShouldHaveVerboseAsDefaultValue()
        {
            var consoleParameters = new ConsoleParameters(new FileHelper());

            Assert.AreEqual(consoleParameters.TraceLevel, TraceLevel.Verbose);
        }