private void Run <T>(AutoStopwatch parent, Func <Random, T> getRandomValue) where T : struct, IComparable <T>
        {
            for (int exp = MIN_EXP; exp <= MAX_EXP; exp += EXP_STEP)
            {
                using (var child = parent.CreateChild(prefix: $"{typeof(T).Name} ", postfix: $" (2^{exp})"))
                {
                    T[] randomData1, randomData2;
                    using (var awCompare = child.CreateChild(stepName: "Create Data"))
                    {
                        randomData1 = new T[1 << exp];
                        randomData2 = new T[1 << exp];
                        var random = new Random();
                        for (int i = 0; i < randomData1.Length; i++)
                        {
                            randomData1[i] = getRandomValue(random);
                            randomData2[i] = getRandomValue(random);
                        }
                    }

                    var v = this.RunGenericVectorized(child, randomData1, randomData2);
                    var c = this.RunGenericConventional(child, randomData1, randomData2);

                    using (var awCompare = child.CreateChild(stepName: "Compare Results"))
                    {
                        ArrayComparer.Compare(v.add, c.add);
                        ArrayComparer.Compare(v.sub, c.sub);
                        ArrayComparer.Compare(v.mul, c.mul);
                        ArrayComparer.Compare(v.div, c.div);
                    }
                }
            }
        }
        public void Run(AutoStopwatch parent)
        {
            this.Run <byte>(parent, RandomHelper.NextByte);
            this.Run <short>(parent, RandomHelper.NextShort);
            this.Run <int>(parent, RandomHelper.NextInt);
            this.Run <long>(parent, RandomHelper.NextLong);
            this.Run <double>(parent, RandomHelper.NextDouble);
            this.Run <float>(parent, RandomHelper.NextFloat);

            this.RunByte(parent);
            this.RunInt(parent);
            this.RunLong(parent);
            this.RunDouble(parent);
            this.RunFloat(parent);
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            bool closeServer = args.Contains("done");
            bool download    = args.Contains("download");

            if (!args.Any() || !(File.Exists(args[0]) || download))
            {
                Console.WriteLine("Existing file name expected!");
                return;
            }

            string    fileName = args[0];
            TcpClient client   = null;

            var watch = new AutoStopwatch();

            try
            {
                string server = ConfigurationManager.AppSettings["Tcp.Server"] ?? ADDRESS;
                var    port   = int.Parse(ConfigurationManager.AppSettings["Tcp.Port"] ?? PORT.ToString());

                client = new TcpClient(server, port);
                using (var stream = client.GetStream())
                {
                    Console.WriteLine("Connected to {0}:{1}", server, port);
                    if (download)
                    {
                        DownloadFile(stream, fileName, closeServer, len => watch.Restart(len));
                    }
                    else
                    {
                        var fi = new FileInfo(fileName);
                        watch = new AutoStopwatch(fi.Length);
                        UploadFile(stream, fi, closeServer);
                    }
                }

                watch.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                client?.Close();
            }
        }
        public override void CreateControl()
        {
            base.CreateControl();

            if (!_controlCreated && !DesignMode)
            {
                if (!ParagonRuntime.IsInitialized)
                {
                    ParagonRuntime.Initialize();
                }

                _client = new CefWebClient(this);

                if (!IsPopup && _browser == null)
                {
                    var settings = new CefBrowserSettings
                    {
                        Java = CefState.Disabled
                    };

                    using (AutoStopwatch.TimeIt("Creating browser"))
                    {
                        var info = CefWindowInfo.Create();
                        var ea   = new BrowserCreateEventArgs();

                        using (AutoStopwatch.TimeIt("Raising BeforeBrowserCreate event"))
                        {
                            BeforeBrowserCreate.Raise(this, ea);
                        }

                        _router     = ea.Router;
                        _currentUrl = _sourceUrl;

                        if (IntPtr.Zero != ParentHandle)
                        {
                            RECT rect = new RECT();
                            Win32Api.GetClientRect(ParentHandle, ref rect);
                            info.SetAsChild(ParentHandle, new CefRectangle(rect.Left, rect.Top, rect.Width, rect.Height));
                        }

                        Logger.Info(string.Format("OnHandleCreated - Creating a browser with url {0}", _currentUrl));
                        CefBrowserHost.CreateBrowser(info, _client, settings, _currentUrl);
                    }
                }

                _controlCreated = true;
            }
        }
        private void LoadEventPage()
        {
            if (_eventPageBrowser != null)
            {
                return;
            }

            _eventPageBrowser = _createNewBrowser();
            _eventPageBrowser.BeforeBrowserCreate     += OnBeforeEventPageBrowserCreate;
            _eventPageBrowser.LoadEnd                 += OnEventPageBrowserLoad;
            _eventPageBrowser.RenderProcessTerminated += OnRenderProcessTerminated;

            using (AutoStopwatch.TimeIt("Creating browser control"))
            {
                _eventPageBrowser.CreateControl();
            }
        }
        static void Main(string[] args)
        {
            var testsToRun = SelectTests();

            var aw = new AutoStopwatch("Main");

            using (aw)
            {
                foreach (var t in testsToRun)
                {
                    t.Run(aw);
                }
            }

            var text = new StringBuilder();

            aw.Print(text);
            Console.WriteLine(text.ToString());
        }
 public CreateWindowRequest(
     string startUrl,
     CreateWindowOptions options,
     JavaScriptPluginCallback windowCreatedCallback,
     string id = null)
 {
     _stopwatch = AutoStopwatch.TimeIt("Creating app window");
     RequestId  = id;
     if (string.IsNullOrEmpty(id))
     {
         RequestId = Guid.NewGuid().ToString();
     }
     StartUrl = startUrl;
     Options  = options;
     if (windowCreatedCallback != null)
     {
         _callbackReference     = new WeakReference(windowCreatedCallback, true);
         _windowCreatedCallback = windowCreatedCallback;
     }
 }
Beispiel #8
0
        public static bool ResolveMetadataAndPackage(ParagonCommandLineParser cmdLine, out ApplicationMetadata appMetadata, out IApplicationPackage appPackage)
        {
            appMetadata = null;
            appPackage  = null;

            try
            {
                using (AutoStopwatch.TimeIt("Parsing application metadata"))
                {
                    appMetadata = cmdLine.ParseApplicationMetadata();
                    Logger.Info("The current environment is {0}", appMetadata != null ? appMetadata.Environment : ApplicationEnvironment.Production);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Error parsing command line : {0}", ex.Message),
                                "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            try
            {
                using (AutoStopwatch.TimeIt("Gettting application package"))
                {
                    appPackage = appMetadata.GetApplicationPackage();
                    Logger.Info("The current application package is {0}",
                                appPackage == null || appPackage.Signature == null ? "unsigned" : string.Format("digitally signed by {0} on {1}", appPackage.Signature.Signer.Subject, appPackage.Signature.SigningTime));
                    return(appPackage != null);
                }
            }
            catch (SecurityException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Error parsing manifest file : {0}", ex.Message),
                                "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return(false);
        }
Beispiel #9
0
        private static async Task GenerateFile(string[] dictionary, string fileName, ulong maxSize)
        {
            var   rand      = new Random();
            ulong lineCount = 1;

            using (var file = File.Create(fileName, OutFileBuffer, FileOptions.Asynchronous | FileOptions.SequentialScan))
                using (var sw = new StreamWriter(file, Encoding.UTF8, OutFileBuffer, true))
                    using (var stopWatch = new AutoStopwatch("Test file generation"))
                    {
                        while (file.Length < (long)maxSize)
                        {
                            var lines = GenerateLines(dictionary, rand, lineCount, ChunkSize);
                            await sw.WriteAsync(lines);

                            lineCount += ChunkSize;
                        }

                        stopWatch.WorkAmount = file.Length;
                        Console.WriteLine("File '{0}' of total {1} lines of size {2} generated", fileName, lineCount, BytesFormatter.Format(file.Length));
                    }
        }
Beispiel #10
0
        public async Task MergeSortFile(string inputFile, string outputFile)
        {
            var inputFileLength = new FileInfo(inputFile).Length;

            _inputFileLength = inputFileLength;
            var asw   = new AutoStopwatch("Total work", _inputFileLength);
            var files = await Split(inputFile, Path.GetTempPath());

            try
            {
                await MergeSortFiles(files.Item2, files.Item1, outputFile, Comparator);
            }
            finally
            {
                asw.Dispose();

                foreach (var file in files.Item2)
                {
                    File.Delete(file);
                }
            }
        }
Beispiel #11
0
        protected virtual void RunApplicationInternal(ParagonCommandLineParser cmdLine, IApplicationPackage package, ApplicationMetadata metadata)
        {
            IParagonSplashScreen splash      = null;
            IApplication         application = null;
            Window splashWindow = null;
            var    manifest     = package.Manifest;

#if ENFORCE_PACKAGE_SECURITY
            var isSigned = package.Signature != null;
#endif
            try
            {
                ParagonLogManager.AddApplicationTraceListener(manifest.Id);

                // Load custom WPF theme for the application
                var stylePart   = !string.IsNullOrEmpty(manifest.CustomTheme) ? package.GetPart(manifest.CustomTheme) : null;
                var styleStream = stylePart != null?stylePart.GetStream() : null;

                if (styleStream != null)
                {
                    var theme = XamlReader.Load(styleStream) as ResourceDictionary;
                    if (theme != null)
                    {
#if ENFORCE_PACKAGE_SECURITY
                        if (isSigned)
#endif
                        Application.Current.Resources.MergedDictionaries.Add(theme);
                    }
                }

                // Create and show the splash screen if needed
                if (cmdLine != null && !cmdLine.HasFlag("no-splash") && _createSplashScreen != null)
                {
#if ENFORCE_PACKAGE_SECURITY
                    splash = _createSplashScreen(isSigned ? manifest.Name : manifest.Name + " (Unsigned)", manifest.Version, package.GetIcon());
#else
                    splash = _createSplashScreen(manifest.Name, manifest.Version, package.GetIcon());
#endif
                    splashWindow = (Window)splash;
                    metadata.UpdateLaunchStatus = s =>
                    {
                        if (splash != null && splashWindow != null && splashWindow.IsVisible)
                        {
                            splash.ShowText(s);
                        }
                    };
#if ENFORCE_PACKAGE_SECURITY
                    if (!isSigned)
                    {
                        splashWindow.Style = Application.Current.Resources["AlarmSplashScreenStyle"] as Style;
                    }
#endif
                    splashWindow.Show();
                }

                // Extract the application arguments from the command line
                Dictionary <string, object> args = null;
                if (cmdLine != null && _appArgumentParser != null)
                {
                    string appArgs, appUrl;
                    if (cmdLine.GetValue("args", out appArgs))
                    {
                        args = _appArgumentParser(appArgs);
                    }
                    else if (cmdLine.GetValue("url", out appUrl))
                    {
                        Uri uri;
                        if (Uri.TryCreate(appUrl, UriKind.Absolute, out uri))
                        {
                            if (!string.IsNullOrEmpty(uri.Query))
                            {
                                args = _appArgumentParser(uri.Query.Substring(1));
                            }
                        }
                    }
                }

                //Create and register application
                application = _createApplication(package, metadata, args);
                Register(application);

                // Launch the application
                var stopWatch = AutoStopwatch.TimeIt("Launching");

                application.Launched += delegate
                {
                    if (splashWindow != null)
                    {
                        splashWindow.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            if (splashWindow != null)
                            {
                                splashWindow.Close();
                            }
                        }));
                    }

                    this.RemoveSingleInstanceLaunchMarker(metadata.Id);

                    stopWatch.Dispose();
                };

                application.Launch();

                string protocolUri = null;
                if (cmdLine != null)
                {
                    cmdLine.GetValue("url", out protocolUri);
                    if (!string.IsNullOrEmpty(protocolUri))
                    {
                        application.OnProtocolInvoke(protocolUri);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Info("Error starting paragon application : {0}", ex);

                MessageBox.Show("Unable to start:\n\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                if (splashWindow != null)
                {
                    splashWindow.Close();
                }

                if (application != null)
                {
                    RemoveSingleInstanceLaunchMarker(metadata.Id);
                    application.Close();
                    application = null;
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// Launch the first application in the host process
        /// </summary>
        /// <param name="package"></param>
        /// <param name="metadata"></param>
        public void RunApplication(ParagonCommandLineParser cmdLine, IApplicationPackage package, ApplicationMetadata metadata)
        {
            if (IsInitialized)
            {
                throw new Exception("Application manger is already initialized");
            }

            var manifest = package.Manifest;

            // Initialize the following from the first application manifest
            ProcessGroup         = manifest.ProcessGroup ?? string.Empty;
            CacheFolder          = Path.Combine(_paragonFolder, string.IsNullOrEmpty(manifest.ProcessGroup) ? manifest.Id : manifest.ProcessGroup);
            Environment          = metadata.Environment;
            DisableSpellChecking = manifest.DisableSpellChecking;

            // set browser language from manifest - default is en-US
            // "automatic" will set browser language to os culture info
            if (!string.IsNullOrEmpty(manifest.BrowserLanguage))
            {
                if (string.Equals(manifest.BrowserLanguage, "Automatic", StringComparison.InvariantCultureIgnoreCase))
                {
                    BrowserLanguage = CultureInfo.CurrentCulture.Name;
                }
                else
                {
                    //verify specified culture
                    CultureInfo cultureInfo = null;
                    try
                    {
                        cultureInfo = new CultureInfo(manifest.BrowserLanguage);
                    }
                    catch (Exception)
                    {
                        Logger.Error("Manifest browser language is not valid. Using default browser language en-US");
                    }

                    BrowserLanguage = (cultureInfo != null) ? (cultureInfo.Name) : (BrowserLanguage);
                }

                Logger.Info(string.Format("Browser language being used is {0}", BrowserLanguage));
            }

            string auth_server_whitelist   = null;
            string auth_delegate_whitelist = null;

            if (cmdLine != null)
            {
                cmdLine.GetValue("auth-server-whitelist", out auth_server_whitelist);
                Logger.Info(string.Format("auth-server-whitelist [{0}]", auth_server_whitelist));
                cmdLine.GetValue("auth-delegate-whitelist", out auth_delegate_whitelist);
                Logger.Info(string.Format("auth-delegate-whitelist [{0}]", auth_delegate_whitelist));
            }

            // Initialize CEF
            using (AutoStopwatch.TimeIt("CEF initialization"))
            {
                ParagonRuntime.Initialize(
                    CacheFolder,
                    null,
                    BrowserLanguage,
                    auth_server_whitelist,
                    auth_delegate_whitelist,
                    DisableSpellChecking,
                    Environment == ApplicationEnvironment.Development);
            }

            RunApplicationInternal(cmdLine, package, metadata);
        }
        public static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // Create command line args parser.
            var cmdLine = new ParagonCommandLineParser(Environment.GetCommandLineArgs());

            /*
             * Following statement is due to the Chromium bug: https://code.google.com/p/chromium/issues/detail?id=125614
             * This statement can be removed once we know for sure that the issue has been fixed by Chrome.
             * For now, we are disabling any system setting/command line setting for the TZ variable.
             */
            Environment.SetEnvironmentVariable("TZ", null);

            // Launch a debugger if a --debug flag was passed.
            if (cmdLine.HasFlag("debug"))
            {
                Debugger.Launch();
            }

            // Extract app package.
            ApplicationMetadata appMetadata;
            IApplicationPackage appPackage;

            if (!ApplicationManager.ResolveMetadataAndPackage(cmdLine, out appMetadata, out appPackage))
            {
                Environment.ExitCode = 1;
                return;
            }

            try
            {
                _appManager = ApplicationManager.GetInstance();

                //initialize logger earlier in the start up sequence
                _appManager.InitializeLogger(Environment.ExpandEnvironmentVariables(Settings.Default.CacheDirectory), appPackage);

                // Bail if the app is a singleton and an instance is already running. Cmd line args from
                // this instance will be sent to the singleton isntance by the SingleInstance utility.
                if (_appManager.RedirectApplicationLaunchIfNeeded(appPackage, appMetadata.Environment))
                {
                    return;
                }

                // Initialize the app.
                App app;

                using (AutoStopwatch.TimeIt("Initializing Paragon.App"))
                {
                    app = new App();
                    app.InitializeComponent();
                    app.Startup += delegate
                    {
                        _appManager.Initialize(
                            (name, version, iconStream) => new ParagonSplashScreen(name, version, iconStream),
                            (package, metadata, args) =>
                        {
                            var bootstrapper = new Bootstrapper();
                            var appFactory   = bootstrapper.Resolve <ApplicationFactory>();
                            return(appFactory.CreateApplication(metadata, package, args));
                        },
                            (args) =>
                        {
                            var query = HttpUtility.ParseQueryString(args);
                            return(query.Keys.Cast <string>().ToDictionary <string, string, object>(key => key, key => query[key]));
                        },
                            Environment.ExpandEnvironmentVariables(Settings.Default.CacheDirectory),
                            true,
                            appPackage.Manifest.DisableSpellChecking
                            );

                        _appManager.AllApplicationsClosed += delegate
                        {
                            _appManager.Shutdown("All applications closed");
                            _appManager.ShutdownLogger();
                            app.Shutdown();
                        };

                        _appManager.RunApplication(cmdLine, appPackage, appMetadata);
                    };
                }

                // Run the app (this is a blocking call).
                app.Run();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Error launching application : {0}", ex.InnerException != null
                    ? ex.InnerException.Message : ex.Message), "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                Environment.ExitCode = 1;

                throw;
            }
        }