public AutoCreationController(
     IDispatcherExecute dispatcher,
     CreationViewModel viewModel,
     ITypesManager typesManager,
     SessionConfiguration sessionConfiguration,
     OptionsModel options,
     IFactory<SessionCreator> sessionCreatorFactory,
     IDispatcherExecute execute,
     CommonServices svc)
 {
     _dispatcher = dispatcher;
     _viewModel = viewModel;
     _typesManager = typesManager;
     _sessionConfiguration = sessionConfiguration;
     _options = options;
     _sessionCreatorFactory = sessionCreatorFactory;
     _execute = execute;
     _svc = svc;
     
     _viewModel.CommandCreateMutants = new SmartCommand(CommandOk,
        () => _viewModel.TypesTreeMutate.Assemblies != null && _viewModel.TypesTreeMutate.Assemblies.Count != 0
              && _viewModel.TypesTreeToTest.TestAssemblies != null && _viewModel.TypesTreeToTest.TestAssemblies.Count != 0
              && _viewModel.MutationsTree.MutationPackages.Count != 0)
            .UpdateOnChanged(_viewModel.TypesTreeMutate, _ => _.Assemblies)
            .UpdateOnChanged(_viewModel.TypesTreeToTest, _ => _.TestAssemblies)
            .UpdateOnChanged(_viewModel.MutationsTree, _ => _.MutationPackages);
 }
Beispiel #2
0
 public void SetUpFixture()
 {
     SessionConfiguration = new SessionConfiguration();
     SessionConfiguration.Timeout = TimeSpan.FromMilliseconds(1000);
     browser = new BrowserSession(SessionConfiguration);
     browser.Visit("file:///" + new FileInfo(@"html\table.htm").FullName.Replace("\\", "/"));
 }
        public void SetUp()
        {
            stubUrlBuilder = new StubUrlBuilder();
            _stubRestrictedResourceDownloader = new SpyRestrictedResourceDownloader();

            driver = new FakeDriver();
            SessionConfiguration = new SessionConfiguration();
            browserSession = TestSessionBuilder.Build(SessionConfiguration, driver, new SpyTimingStrategy(), new FakeWaiter(), _stubRestrictedResourceDownloader, stubUrlBuilder);
        }
Beispiel #4
0
 public void SetUpFixture()
 {
     var configuration = new SessionConfiguration
         {
             Timeout = TimeSpan.FromMilliseconds(2000),
             Browser = Drivers.Browser.Firefox
         };
     browser = new BrowserSession(configuration);
 }
Beispiel #5
0
        public void SetUp()
        {
            SessionConfiguration = new SessionConfiguration();
            SessionConfiguration.AppHost = "www.google.com";
            SessionConfiguration.Driver = typeof(SeleniumWebDriver);

            SessionConfiguration.Timeout = TimeSpan.FromSeconds(10);

            browser = new BrowserSession(SessionConfiguration);
        }
Beispiel #6
0
        public void SetUp()
        {
            sinatraSite = new SinatraSite(string.Format(@"sites\{0}.rb", "site_with_secure_resources"));

            SessionConfiguration SessionConfiguration = new SessionConfiguration();
            SessionConfiguration.Timeout = TimeSpan.FromMilliseconds(1000);
            SessionConfiguration.Port = 4567;
            browser = new BrowserSession(SessionConfiguration);

            browser.Visit("/");
        }
Beispiel #7
0
        public void SetUp()
        {
            site = new SelfishSite();
            
            var sessionConfiguration = new SessionConfiguration();
            sessionConfiguration.Timeout = TimeSpan.FromMilliseconds(1000);
            sessionConfiguration.Port = site.BaseUri.Port;
            browser = new BrowserSession(sessionConfiguration);

            browser.Visit("/");
        }
Beispiel #8
0
        public void SetUpFixture()
        {
            var configuration = new SessionConfiguration
                                    {
                                        Timeout = TimeSpan.FromMilliseconds(2000),
                                        Driver = typeof(SeleniumWebDriver),
                                        Browser = Browser.Chrome
                                    };
            browser = new BrowserSession(configuration);

        }
Beispiel #9
0
        public void AppHostContainsScheme()
        {
            SessionConfiguration = new SessionConfiguration();
            SessionConfiguration.AppHost = "https://www.google.co.uk/";
            SessionConfiguration.Driver = typeof(SeleniumWebDriver);

            browser = new BrowserSession(SessionConfiguration);

            browser.Visit("/");
            Assert.That(browser.Location.ToString(), Is.EqualTo("https://www.google.co.uk/"));
        }
Beispiel #10
0
        public Connectivity.Session MakeNew(IPEndPoint _ipEndPoint, TcpClient _tcpClient = null,
            SessionConfiguration _sessionConfiguration = null)
        {
            if (_ipEndPoint == null) throw new NullReferenceException("Session requires an IPEndpoint.");

            var tcpClient = _tcpClient;
            if (tcpClient == null)
                tcpClient = new TcpClient();

            if (_sessionConfiguration != null)
                return new Connectivity.Session(tcpClient, _ipEndPoint, new CancellationTokenSource(),
                    _sessionConfiguration);
            return new Connectivity.Session(tcpClient, _ipEndPoint, new CancellationTokenSource(),
                new SessionConfiguration());
        }
Beispiel #11
0
 internal static BrowserSession Build(SessionConfiguration sessionConfiguration, 
                                         Driver driver, 
                                         TimingStrategy timingStrategy, 
                                         Waiter waiter,
                                         RestrictedResourceDownloader restrictedResourceDownloader, 
                                         UrlBuilder urlBuilder, 
                                         DisambiguationStrategy disambiguationStrategy = null)
 {
     disambiguationStrategy = disambiguationStrategy ?? new FirstOrDefaultNoDisambiguationStrategy();
     
     return new BrowserSession(sessionConfiguration, 
                     new StubDriverFactory(driver), 
                     timingStrategy, 
                     waiter, 
                     urlBuilder, 
                     disambiguationStrategy,
                     restrictedResourceDownloader);
 }
Beispiel #12
0
        public Session(TcpClient _tcpClient, IPEndPoint _ipEndpoint, CancellationTokenSource _cancellationTokenSource,
            SessionConfiguration _sessionConfiguration = null)
        {
            tcpClient = _tcpClient;

            if (!tcpClient.Connected)
                tcpClient.Connect(_ipEndpoint);

            ApplySessionConfiguration(_sessionConfiguration ?? new SessionConfiguration());

            GetCancellationToken(_cancellationTokenSource);

            LocalEndpointGuid = ShortGuid.New();

            SessionState = (byte) SessionStates.Opening;
                // Set the session state to opening, it will transition to Open once the RemoteEndpointGuid has been received.

            ReadDataAsync(); // Begin a non-blocking read on the Tcpclient of the session.
        }
Beispiel #13
0
        protected void BeforeScenario()
        {
            // Check for a session configuration that was injected in and if one exists, use it
            SessionConfiguration config = _objectContainer.Resolve <SessionConfiguration>();
            var browser = config != null ? new BrowserSession(config) : new BrowserSession();

            _objectContainer.RegisterInstanceAs <BrowserSession>(browser);

            // Apply zukini specific settings
            if (ZukiniConfig.MaximizeBrowser)
            {
                browser.MaximiseWindow();
            }

            // Create a property bucket so we have a place to store values between steps
            var propertyBucket = new PropertyBucket();

            _objectContainer.RegisterInstanceAs <PropertyBucket>(propertyBucket);

            Console.WriteLine("Unique Test Id: {0}", propertyBucket.TestId);
        }
Beispiel #14
0
        static void Main()
        {
            Playback playback = new Playback();

            playback.AddXeTarget <MyTarget>();
            playback.GetObservable <MyXEvent>().Subscribe(e => Console.WriteLine(e.x));
            playback.Start();

            SessionConfiguration cfg = new SessionConfiguration(@"xeconfig.xml");

            for (int i = 0; i < 10; i++)
            {
                if (MyXEvent.IsEnabled)
                {
                    MyXEvent evt = new MyXEvent(3, enumCol.b);
                    evt.Publish();
                }
            }

            Console.ReadLine();
        }
Beispiel #15
0
        public static async Task <bool> TEST_ServerWorksIfClientDoesntAccept()
        {
            bool   fSuccess   = true;
            string serverName = ReverseServer.MakeServerAddress();

            Logger.logger.Log($"Server name is '{serverName}'");
            var         server         = new ReverseServer(serverName);
            Task <bool> subprocessTask = Utils.RunSubprocess(
                currentAssembly: Assembly.GetExecutingAssembly(),
                environment: new Dictionary <string, string>
            {
                { Utils.DiagnosticsMonitorAddressEnvKey, serverName },
                { Utils.DiagnosticsMonitorPauseOnStartEnvKey, "0" }
            },
                duringExecution: async(int pid) =>
            {
                var config = new SessionConfiguration(
                    circularBufferSizeMB: 10,
                    format: EventPipeSerializationFormat.NetTrace,
                    providers: new List <Provider> {
                    new Provider("Microsoft-DotNETCore-SampleProfiler")
                });
                Logger.logger.Log("Starting EventPipeSession over standard connection");
                using Stream stream = EventPipeClient.CollectTracing(pid, config, out var sessionId);
                Logger.logger.Log($"Started EventPipeSession over standard connection with session id: 0x{sessionId:x}");
                using var source = new EventPipeEventSource(stream);
                Task readerTask  = Task.Run(() => source.Process());
                await Task.Delay(500);
                Logger.logger.Log("Stopping EventPipeSession over standard connection");
                EventPipeClient.StopTracing(pid, sessionId);
                await readerTask;
                Logger.logger.Log("Stopped EventPipeSession over standard connection");
            }
                );

            fSuccess &= await subprocessTask;
            server.Shutdown();

            return(true);
        }
        protected override void PopulateData()
        {
            var sessionConfig = new SessionConfiguration(SessionOptions.Default | SessionOptions.AutoActivation);

            using (var session = Domain.OpenSession(sessionConfig))
                using (var transaction = session.OpenTransaction()) {
                    var author = new Author()
                    {
                        FirstName = "Ivan",
                        LastName  = "Goncharov",
                        Biography = "Some biography of Ivan Alexandrovich"
                    };
                    var book = new Book()
                    {
                        Title       = "Oblomov",
                        Description = "A drama about how human's lazyness and absence of strenght may affect his life.",
                        BookFile    = new byte[] { 3, 3, 3, 3, 3, 3, 3 },
                        Author      = author
                    };

                    _ = new Chapter()
                    {
                        Title = "Chapter #1", Description = "Detailed description of Chapter #1", Owner = book
                    };
                    _ = new Chapter()
                    {
                        Title = "Chapter #2", Description = "Detailed description of Chapter #2", Owner = book
                    };
                    _ = new Chapter()
                    {
                        Title = "Chapter #3", Description = "Detailed description of Chapter #3", Owner = book
                    };

                    oblomovKey   = book.Key;
                    goncharovKey = author.Key;

                    transaction.Complete();
                }
        }
Beispiel #17
0
        private void ApplySessionConfiguration(SessionConfiguration _sessionConfiguration)
        {
            if (_sessionConfiguration.MaxReconnectAttempts > 0)
                MaxReconnectAttempts = _sessionConfiguration.MaxReconnectAttempts;

            if (_sessionConfiguration.ReconnectionCounterResetInterval >= 10)
                ReconnectionCounterResetInterval = _sessionConfiguration.ReconnectionCounterResetInterval;

            if (_sessionConfiguration.ConnectionTimeout >= 1000)
                ConnectionTimeout = _sessionConfiguration.ConnectionTimeout;

            if (_sessionConfiguration.KeepaliveSendInterval >= 1)
                KeepaliveSendInterval = _sessionConfiguration.KeepaliveSendInterval;

            if (_sessionConfiguration.KeepaliveDeadTime >= 4)
                KeepaliveDeadTime = _sessionConfiguration.KeepaliveDeadTime;

            if (_sessionConfiguration.MaxDataKeyValueStoreDepth <= 25)
                MaxDataKeyValueStoreDepth = _sessionConfiguration.MaxDataKeyValueStoreDepth;

            UseKeepalives = _sessionConfiguration.UseKeepalives;
        }
Beispiel #18
0
        protected override DomainConfiguration BuildConfiguration()
        {
            var configuration = base.BuildConfiguration();

            configuration.Types.Register(typeof(InventoryBalance).Assembly, typeof(InventoryBalance).Namespace);
            configuration.UpgradeMode = DomainUpgradeMode.Recreate;

            var defaultSessionConfig = configuration.Sessions.Default;

            if (defaultSessionConfig == null)
            {
                defaultSessionConfig = new SessionConfiguration(WellKnown.Sessions.Default, SessionOptions.ServerProfile);
                configuration.Sessions.Add(defaultSessionConfig);
            }

            defaultSessionConfig.DefaultIsolationLevel = IsolationLevel.Snapshot;
            defaultSessionConfig.DefaultCommandTimeout = 60 * 60; // 60 min.

            defaultSessionConfig.BatchSize = 1;                   //force to use SimpleCommandProcessor

            return(configuration);
        }
Beispiel #19
0
        /// <summary>
        /// Creates a Coypu <see cref="BrowserSession"/> using the configuration given by <paramref name="browserConfiguration"/>.
        /// </summary>
        /// <param name="browserConfiguration">The browser configuration to use.</param>
        /// /// <param name="coypuConfiguration">The Coypu configuration to use.</param>
        /// <returns>A new Coypu <see cref="BrowserSession"/>.</returns>
        public static BrowserSession CreateBrowser(
            [NotNull] IBrowserConfiguration browserConfiguration,
            [NotNull] ICoypuConfiguration coypuConfiguration)
        {
            ArgumentUtility.CheckNotNull("browserConfiguration", browserConfiguration);
            ArgumentUtility.CheckNotNull("coypuConfiguration", coypuConfiguration);

            var sessionConfiguration = new SessionConfiguration
            {
                Browser                   = browserConfiguration.Browser,
                RetryInterval             = coypuConfiguration.RetryInterval,
                Timeout                   = coypuConfiguration.SearchTimeout,
                ConsiderInvisibleElements = WebTestingConstants.ShouldConsiderInvisibleElements,
                Match         = WebTestingConstants.DefaultMatchStrategy,
                TextPrecision = WebTestingConstants.DefaultTextPrecision
            };

            if (sessionConfiguration.Browser == Browser.Chrome)
            {
                // Todo RM-6337: Switch back to always using the default Chrome driver as soon as the ActaNova language problem has been solved.
                if (ConfigurationManager.AppSettings["CustomChromeUserDataDir"] != null)
                {
                    sessionConfiguration.Driver = typeof(CustomChromeDriver);
                    return(new BrowserSession(sessionConfiguration, new CustomChromeDriver()));
                }

                sessionConfiguration.Driver = typeof(SeleniumWebDriver);
                return(new BrowserSession(sessionConfiguration));
            }

            if (sessionConfiguration.Browser == Browser.InternetExplorer)
            {
                sessionConfiguration.Driver = typeof(CustomInternetExplorerDriver);
                return(new BrowserSession(sessionConfiguration, new CustomInternetExplorerDriver()));
            }

            throw new NotSupportedException(string.Format("Only browsers '{0}' and '{1}' are supported.", Browser.Chrome, Browser.InternetExplorer));
        }
        public void ClientProfileVersionsTest()
        {
            RebuildDomain();
            var sessionConfiguration = new SessionConfiguration(SessionOptions.ClientProfile | SessionOptions.AutoActivation | SessionOptions.ValidateEntityVersions);

            int thread1Version;
            int thread2Version;

            using (var session = Domain.OpenSession(sessionConfiguration)) {
                var bookForEditLater = new Book();
                var version          = bookForEditLater.Version;
                session.SaveChanges();
            }

            var thread1 = new Thread(
                o => {
                var domain1 = (Domain)o;
                using (var session = domain1.OpenSession(sessionConfiguration)) {
                    var book = session.Query.All <Book>().First();
                    Thread.Sleep(10);
                    book.Title = "first thread";
                    session.SaveChanges();
                }
            });
            var thread2 = new Thread(
                o => {
                var domain1 = (Domain)o;
                using (var session = domain1.OpenSession(sessionConfiguration)) {
                    var book = session.Query.All <Book>().First();
                    Thread.Sleep(10);
                    book.Title = "second thread";
                    Assert.Throws <VersionConflictException>(session.SaveChanges);
                }
            });

            thread1.Start(Domain);
            thread2.Start(Domain);
        }
Beispiel #21
0
        private void Check_robust_content_query <T>(bool stubResult, string actualContent, Func <T, Options, bool> subject, T toLookFor)
        {
            var window = new StubElement {
                Text = actualContent
            };

            driver.StubCurrentWindow(window);

            SpyTimingStrategy.StubQueryResult(true, !stubResult);

            var individualTimeout = TimeSpan.FromMilliseconds(DateTime.UtcNow.Millisecond);
            var options           = new SessionConfiguration {
                Timeout = individualTimeout
            };

            var actualImmediateResult = subject(toLookFor, options);

            Assert.That(actualImmediateResult, Is.EqualTo(!stubResult), "Result was not found robustly");

            var queryResult = RunQueryAndCheckTiming <bool>(individualTimeout);

            Assert.That(queryResult, Is.EqualTo(stubResult));
        }
Beispiel #22
0
        public static void BeforeTestRun()
        {
            Assert.That(Directory.Exists(WebPath), WebPath + " not found!");

            BackupExistingDatabase();

            AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetFullPath(Path.Combine(WebPath, "App_Data")));

            _seleniumServer = new SeleniumServerProcess();
            _seleniumServer.Start();

            var sessionConfiguration = new SessionConfiguration
            {
                AppHost = "localhost",
                Port    = _port,
                Browser = Browser.Firefox,
                //Browser = Browser.HtmlUnitWithJavaScript,
                Timeout       = TimeSpan.FromSeconds(15),
                RetryInterval = TimeSpan.FromSeconds(1),
            };

            _browser = new BrowserSession(sessionConfiguration);
        }
        private SessionConfiguration Create(string plugin)
        {
            SessionConfiguration config = null;

            switch (plugin)
            {
            case PluginsSection.Dnp3Master:
            case PluginsSection.Dnp3Outstation:
                config = new Dnp3SessionConfiguration(plugin);
                break;

            case PluginsSection.ModbusMaster:
            case PluginsSection.ModbusOutstation:
                config = new ModbusSessionConfiguration(plugin);
                break;

            case PluginsSection.GoosePub:
            case PluginsSection.GooseSub:
                config = new GooseSessionConfiguration(plugin);
                break;

            case PluginsSection.IccpClient:
            case PluginsSection.IccpServer:
                config = new IccpSessionConfiguration(plugin);
                break;

            default:
                throw new InvalidOperationException($"Plugin is not supported to have session configuration. [{plugin}]");
            }

            config.PropertyChanged += (sender, e) =>
            {
                NotifyPropertyChanged();
            };

            return(config);
        }
        public void AllowSwitchingOnEntitySetAddTest()
        {
            var sessionCfg = new SessionConfiguration();

            sessionCfg.Options |= SessionOptions.AllowSwitching;
            sessionCfg.Options |= SessionOptions.AutoActivation;

            using (var sessionA = Domain.OpenSession(sessionCfg))
                using (var tx1 = sessionA.OpenTransaction()) { // Open & activate
                    var personA      = sessionA.Query.All <Person>().First();
                    var notification = sessionA.Query.All <Notification>().First(n => n.Id.In(detachedNotificationKeys));

                    using (var sessionB = Domain.OpenSession(sessionCfg)) { // Open & activate
                        // Session switching (from sessionB to sessionA) will be detected here, but allowed
                        using (var tx = Session.Demand().OpenTransaction()) {
                            _ = personA.Notifications.Add(notification);
                        }
                    }
                }

            sessionCfg          = new SessionConfiguration();
            sessionCfg.Options |= SessionOptions.AllowSwitching;
            sessionCfg.Options |= SessionOptions.AutoActivation;

            using (var sessionA = Domain.OpenSession(sessionCfg))
                using (var tx1 = sessionA.OpenTransaction()) { // Open & activate
                    var personA      = sessionA.Query.All <Person>().First();
                    var notification = new Notification();

                    using (var sessionB = Domain.OpenSession(sessionCfg)) { // Open & activate
                        // Session switching (from sessionB to sessionA) will be detected here, but allowed
                        using (var tx = Session.Demand().OpenTransaction()) {
                            _ = personA.Notifications.Add(notification);
                        }
                    }
                }
        }
        public void MainTest()
        {
            // Creatign new Domain configuration
            var config = DomainConfigurationFactory.CreateWithoutSessionConfigurations();

            // Modifying it by registering the persistent types
            config.Types.Register(typeof(MyEntity).Assembly, typeof(MyEntity).Namespace);
            // And finally building the domain
            var domain = Domain.Build(config);

            using (var session = domain.OpenSession()) {
                // Session don't activated by default
                Debug.Assert(Session.Current == null);
            }

            var sessionConfiguration = new SessionConfiguration(SessionOptions.ServerProfile | SessionOptions.AutoActivation);

            using (var session = domain.OpenSession(sessionConfiguration))
                using (var transactionScope = session.OpenTransaction()) {
                    Debug.Assert(Session.Current == session);
                    var helloWorld = new MyEntity {
                        Text = "Hello World!"
                    };
                    // Marking transaction as committable
                    transactionScope.Complete();
                }

            // Reading all persisted objects from another Session
            using (var session = domain.OpenSession())
                using (var transactionScope = session.OpenTransaction()) {
                    foreach (var myEntity in session.Query.All <MyEntity>())
                    {
                        Console.WriteLine(myEntity.Text);
                    }
                    transactionScope.Complete();
                }
        }
Beispiel #26
0
        private List <SessionConfiguration> GetSessions()
        {
            var sessions = new List <SessionConfiguration>();

            var cfg = new SessionConfiguration(3301);

            //var def1 = new CrawlerRunDefinition();
            //def1.CrawlerId = 22;
            //def1.SeedUrl = "http://www.bluespiders.net";
            //cfg.Definitions.Add(def1);

            //sessions.Add(cfg);

            //cfg = new SessionConfiguration(505);

            //def1 = new CrawlerRunDefinition();
            //def1.CrawlerId = 54;
            //def1.SeedUrl = "http://www.sharipastorephotography.com";
            //cfg.Definitions.Add(def1);

            //sessions.Add(cfg);

            return(sessions);
        }
Beispiel #27
0
        public void Setup()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("config.json")
                         .Build();


            var sessionConfig = new SessionConfiguration
            {
                Driver  = typeof(SeleniumWebDriver),
                Browser = Coypu.Drivers.Browser.Firefox,
                Timeout = TimeSpan.FromSeconds(50),
                // ConsiderInvisibleElements = true
            };

            if (config["appHost"].Equals("qa1"))
            {
                sessionConfig.AppHost = "https://qa1.lottocap.com.br";
            }
            if (config["appHost"].Equals("qa2"))
            {
                sessionConfig.AppHost = "https://qa2.lottocap.com.br";
            }
            if (config["appHost"].Equals("dev1"))
            {
                sessionConfig.AppHost = "https://dev1.lottocap.com.br";
            }
            if (config["appHost"].Equals("dev2"))
            {
                sessionConfig.AppHost = "https://dev2.lottocap.com.br";
            }

            Browser = new BrowserSession(sessionConfig);

            Browser.MaximiseWindow();
        }
        public void DenySwitchingStructureWriteTest()
        {
            var sessionCfg = new SessionConfiguration();

            sessionCfg.Options |= SessionOptions.AutoActivation;

            using (var sessionA = Domain.OpenSession(sessionCfg))
                using (var tx1 = sessionA.OpenTransaction()) { // Open & activate
                    var personA = sessionA.Query.All <Person>().First();

                    using (var sessionB = Domain.OpenSession(sessionCfg)) { // Open & activate
                        // Session switching (from sessionB to sessionA) will be detected here,
                        // but allowed, since there is no running transaction
                        personA.FullName = new FullName()
                        {
                            FirstName = "abc", LastName = "def"
                        };

                        using (var tx = Session.Demand().OpenTransaction()) {
                            // Session switching (from sessionB to sessionA) will be detected & blocked here
                            AssertEx.Throws <InvalidOperationException>(() => personA.FullName = new FullName {
                                FirstName = "def", LastName = "ghi"
                            });

                            // Blocking session switching check
                            using (Session.Deactivate()) {
                            }
                        }
                    }

                    personA.FullName = new FullName {
                        FirstName = "jkl", LastName = "mno"
                    };
                    Assert.That(personA.Session, Is.EqualTo(personA.FullName.Session));
                }
        }
        public void Initialize()
        {
            var serviceEventName = $"{nameof(SafeExamBrowser)}-{nameof(ServiceOperationTests)}";

            appConfig      = new AppConfig();
            logger         = new Mock <ILogger>();
            runtimeHost    = new Mock <IRuntimeHost>();
            service        = new Mock <IServiceProxy>();
            serviceEvent   = new EventWaitHandle(false, EventResetMode.AutoReset, serviceEventName);
            session        = new SessionConfiguration();
            sessionContext = new SessionContext();
            settings       = new ApplicationSettings();
            userInfo       = new Mock <IUserInfo>();

            appConfig.ServiceEventName       = serviceEventName;
            sessionContext.Current           = session;
            sessionContext.Current.AppConfig = appConfig;
            sessionContext.Next           = session;
            sessionContext.Next.AppConfig = appConfig;
            session.Settings        = settings;
            settings.Service.Policy = ServicePolicy.Mandatory;

            sut = new ServiceOperation(logger.Object, runtimeHost.Object, service.Object, sessionContext, 0, userInfo.Object);
        }
Beispiel #30
0
        public static async Task <bool> TEST_ServerIsResilientToNoBufferAgent()
        {
            // N.B. - this test is only testing behavior on Windows since Unix Domain Sockets get their buffer size from the
            // system configuration and isn't set here.  Tests passing on Windows should indicate it would pass on Unix systems as well.
            string serverName = ReverseServer.MakeServerAddress();

            Logger.logger.Log($"Server name is '{serverName}'");
            var server = new ReverseServer(serverName, 0);

            await RunSubprocess(
                serverName : serverName,
                duringExecution : async(int pid) =>
            {
                var config = new SessionConfiguration(
                    circularBufferSizeMB: 10,
                    format: EventPipeSerializationFormat.NetTrace,
                    providers: new List <Provider> {
                    new Provider("Microsoft-DotNETCore-SampleProfiler")
                });
                Logger.logger.Log("Starting EventPipeSession over standard connection");
                using Stream stream = EventPipeClient.CollectTracing(pid, config, out var sessionId);
                Logger.logger.Log($"Started EventPipeSession over standard connection with session id: 0x{sessionId:x}");
                using var source = new EventPipeEventSource(stream);
                Task readerTask  = Task.Run(() => source.Process());
                await Task.Delay(500);
                Logger.logger.Log("Stopping EventPipeSession over standard connection");
                EventPipeClient.StopTracing(pid, sessionId);
                await readerTask;
                Logger.logger.Log("Stopped EventPipeSession over standard connection");
            }
                );

            server.Shutdown();

            return(true);
        }
Beispiel #31
0
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool authorize = true;

            SessionConfiguration oConfig  = new SessionConfiguration();
            AccountModel         oSession = oConfig.GetSessionInfo();

            //RoleInfoModel oRole = (from obj in oSession.UserRoles where obj.Sequence == 1 select obj).FirstOrDefault();

            //foreach (var role in allowedroles)
            //{
            //    if (oRole.RoleName.Equals(role, StringComparison.OrdinalIgnoreCase))
            //    {
            //        authorize = true;
            //        break;
            //    }
            //    else
            //    {
            //        authorize = false;
            //    }
            //}

            return(authorize);
        }
Beispiel #32
0
        public static async Task <bool> TEST_MultipleConnectPortsSuspend()
        {
            bool   fSuccess              = true;
            var    serverAndNames        = new List <(ReverseServer, string)>();
            string dotnetDiagnosticPorts = "";

            for (int i = 0; i < s_NumberOfPorts; i++)
            {
                string serverName = ReverseServer.MakeServerAddress();
                var    server     = new ReverseServer(serverName);
                Logger.logger.Log($"Server {i} address is '{serverName}'");
                serverAndNames.Add((server, serverName));
                dotnetDiagnosticPorts += $"{serverName};";
            }
            Logger.logger.Log($"export DOTNET_DiagnosticPorts={dotnetDiagnosticPorts}");

            var    advertisements = new List <IpcAdvertise>();
            Object sync           = new Object();

            int         subprocessId   = -1;
            Task <bool> subprocessTask = Utils.RunSubprocess(
                currentAssembly: Assembly.GetExecutingAssembly(),
                environment: new Dictionary <string, string>
            {
                { Utils.DiagnosticPortsEnvKey, dotnetDiagnosticPorts }
            },
                duringExecution: async(int pid) =>
            {
                subprocessId = pid;
                // Create an eventpipe session that will tell us when
                // the EEStartupStarted event happens.  This will tell us
                // the the runtime has been resumed.  This should only happen
                // AFTER all suspend ports have sent the resume command.
                var config = new SessionConfiguration(
                    circularBufferSizeMB: 1000,
                    format: EventPipeSerializationFormat.NetTrace,
                    providers: new List <Provider> {
                    new Provider("Microsoft-Windows-DotNETRuntimePrivate", 0x80000000, EventLevel.Verbose),
                    // workaround for https://github.com/dotnet/runtime/issues/44072 which happens because the
                    // above provider only sends 2 events and that can cause EventPipeEventSource (from TraceEvent)
                    // to not dispatch the events if the EventBlock is a size not divisible by 8 (the reading alignment in TraceEvent).
                    // Adding this provider keeps data flowing over the pipe so the reader doesn't get stuck waiting for data
                    // that won't come otherwise.
                    new Provider("Microsoft-DotNETCore-SampleProfiler")
                });
                Logger.logger.Log("Starting EventPipeSession over standard connection");
                using Stream eventStream = EventPipeClient.CollectTracing(pid, config, out var sessionId);
                Logger.logger.Log($"Started EventPipeSession over standard connection with session id: 0x{sessionId:x}");

                var mre = new ManualResetEvent(false);

                Task readerTask = Task.Run(async() =>
                {
                    Logger.logger.Log($"Creating EventPipeEventSource");
                    using var source              = new EventPipeEventSource(eventStream);
                    var parser                    = new ClrPrivateTraceEventParser(source);
                    parser.StartupEEStartupStart += (eventData) => mre.Set();
                    Logger.logger.Log($"Created EventPipeEventSource");
                    Logger.logger.Log($"Starting processing");
                    await Task.Run(() => source.Process());
                    Logger.logger.Log($"Finished processing");
                });

                for (int i = 0; i < s_NumberOfPorts; i++)
                {
                    fSuccess &= !mre.WaitOne(0);
                    Logger.logger.Log($"Runtime HAS NOT resumed (expects: true): {fSuccess}");
                    var(server, _)         = serverAndNames[i];
                    int serverIndex        = i;
                    Stream stream          = await server.AcceptAsync();
                    IpcAdvertise advertise = IpcAdvertise.Parse(stream);
                    lock (sync)
                        advertisements.Add(advertise);
                    Logger.logger.Log($"Server {serverIndex} got advertise {advertise.ToString()}");

                    // send resume command on this connection
                    var message = new IpcMessage(0x04, 0x01);
                    Logger.logger.Log($"Port {serverIndex} sent: {message.ToString()}");
                    IpcMessage response = IpcClient.SendMessage(stream, message);
                    Logger.logger.Log($"Port {serverIndex} received: {response.ToString()}");
                }

                Logger.logger.Log($"Waiting on EEStartupStarted event");
                mre.WaitOne();
                Logger.logger.Log($"Saw EEStartupStarted Event");

                Logger.logger.Log($"Stopping EventPipeSession");
                EventPipeClient.StopTracing(pid, sessionId);
                await readerTask;
                Logger.logger.Log($"Stopped EventPipeSession");

                // runtime should have resumed now
                fSuccess &= mre.WaitOne(0);
                Logger.logger.Log($"Runtime HAS resumed (expects: true): {fSuccess}");
            }
                );


            fSuccess &= await subprocessTask;
            foreach (var(server, _) in serverAndNames)
            {
                server.Shutdown();
            }

            if (advertisements.Count() > 0)
            {
                Guid referenceCookie = advertisements[0].RuntimeInstanceCookie;
                foreach (var adv in advertisements)
                {
                    fSuccess &= (int)adv.ProcessId == subprocessId;
                    fSuccess &= adv.RuntimeInstanceCookie.Equals(referenceCookie);
                }
            }
            else
            {
                fSuccess &= false;
            }

            return(fSuccess);
        }
Beispiel #33
0
        public static async Task <bool> TEST_SuspendDefaultPort()
        {
            bool fSuccess = true;

            int         subprocessId   = -1;
            Task <bool> subprocessTask = Utils.RunSubprocess(
                currentAssembly: Assembly.GetExecutingAssembly(),
                environment: new Dictionary <string, string>
            {
                { Utils.DiagnosticPortSuspend, "1" }
            },
                duringExecution: async(int pid) =>
            {
                subprocessId = pid;
                // Create an eventpipe session that will tell us when
                // the EEStartupStarted event happens.  This will tell us
                // the the runtime has been resumed.  This should only happen
                // AFTER all suspend ports have sent the resume command.
                var config = new SessionConfiguration(
                    circularBufferSizeMB: 1000,
                    format: EventPipeSerializationFormat.NetTrace,
                    providers: new List <Provider> {
                    new Provider("Microsoft-Windows-DotNETRuntimePrivate", 0x80000000, EventLevel.Verbose),
                    // workaround for https://github.com/dotnet/runtime/issues/44072 which happens because the
                    // above provider only sends 2 events and that can cause EventPipeEventSource (from TraceEvent)
                    // to not dispatch the events if the EventBlock is a size not divisible by 8 (the reading alignment in TraceEvent).
                    // Adding this provider keeps data flowing over the pipe so the reader doesn't get stuck waiting for data
                    // that won't come otherwise.
                    new Provider("Microsoft-DotNETCore-SampleProfiler")
                });
                Logger.logger.Log("Starting EventPipeSession over standard connection");
                using Stream eventStream = EventPipeClient.CollectTracing(pid, config, out var sessionId);
                Logger.logger.Log($"Started EventPipeSession over standard connection with session id: 0x{sessionId:x}");

                var mre = new ManualResetEvent(false);

                Task readerTask = Task.Run(async() =>
                {
                    Logger.logger.Log($"Creating EventPipeEventSource");
                    using var source              = new EventPipeEventSource(eventStream);
                    var parser                    = new ClrPrivateTraceEventParser(source);
                    parser.StartupEEStartupStart += (eventData) => mre.Set();
                    Logger.logger.Log($"Created EventPipeEventSource");
                    Logger.logger.Log($"Starting processing");
                    await Task.Run(() => source.Process());
                    Logger.logger.Log($"Finished processing");
                });


                fSuccess &= !mre.WaitOne(0);
                Logger.logger.Log($"Runtime HAS NOT resumed (expects: true): {fSuccess}");

                // send resume command on this connection
                var message = new IpcMessage(0x04, 0x01);
                Logger.logger.Log($"Sent: {message.ToString()}");
                IpcMessage response = IpcClient.SendMessage(ConnectionHelper.GetStandardTransport(pid), message);
                Logger.logger.Log($"Received: {response.ToString()}");

                Logger.logger.Log($"Waiting for EEStartupStarted event");
                mre.WaitOne();
                Logger.logger.Log($"Saw EEStartupStarted event!");

                Logger.logger.Log($"Stopping EventPipeSession");
                EventPipeClient.StopTracing(pid, sessionId);
                await readerTask;
                Logger.logger.Log($"Stopped EventPipeSession");

                // runtime should have resumed now
                fSuccess &= mre.WaitOne(0);
                Logger.logger.Log($"Runtime HAS resumed (expects: true): {fSuccess}");
            }
                );


            fSuccess &= await subprocessTask;

            return(fSuccess);
        }
Beispiel #34
0
 public SeleniumGrid(IObjectContainer objectContainer, SessionConfiguration sessionConfiguration)
     : base(objectContainer)
 {
     _sessionConfiguration = sessionConfiguration;
 }
Beispiel #35
0
 public void SetUpFixture()
 {
     var configuration = new SessionConfiguration
                             {
                                 Timeout = TimeSpan.FromMilliseconds(2000),
                                 Driver = Type.GetType("Coypu.Drivers.Selenium.SeleniumWebDriver, Coypu"),
                                 Browser = Drivers.Browser.Firefox
                             };
     browser = new BrowserSession(configuration);
 }
Beispiel #36
0
 internal BrowserSession BuildSession(RobustWrapper robustWrapper)
 {
     SessionConfiguration = new SessionConfiguration();
     return(TestSessionBuilder.Build(SessionConfiguration, new FakeDriver(), robustWrapper, new FakeWaiter(), null, null));
 }
        /// <summary>
        /// Collects a diagnostic trace from a currently running process.
        /// </summary>
        /// <param name="ct">The cancellation token</param>
        /// <param name="console"></param>
        /// <param name="processId">The process to collect the trace from.</param>
        /// <param name="output">The output path for the collected trace data.</param>
        /// <param name="buffersize">Sets the size of the in-memory circular buffer in megabytes.</param>
        /// <param name="providers">A list of EventPipe providers to be enabled. This is in the form 'Provider[,Provider]', where Provider is in the form: 'KnownProviderName[:Flags[:Level][:KeyValueArgs]]', and KeyValueArgs is in the form: '[key1=value1][;key2=value2]'</param>
        /// <param name="profile">A named pre-defined set of provider configurations that allows common tracing scenarios to be specified succinctly.</param>
        /// <param name="format">The desired format of the created trace file.</param>
        /// <returns></returns>
        private static async Task <int> Collect(CancellationToken ct, IConsole console, int processId, FileInfo output, uint buffersize, string providers, string profile, TraceFileFormat format)
        {
            try
            {
                Debug.Assert(output != null);
                Debug.Assert(profile != null);
                if (processId <= 0)
                {
                    Console.Error.WriteLine("Process ID should not be negative.");
                    return(ErrorCodes.ArgumentError);
                }

                var selectedProfile = ListProfilesCommandHandler.DotNETRuntimeProfiles
                                      .FirstOrDefault(p => p.Name.Equals(profile, StringComparison.OrdinalIgnoreCase));
                if (selectedProfile == null)
                {
                    Console.Error.WriteLine($"Invalid profile name: {profile}");
                    return(ErrorCodes.ArgumentError);
                }

                var providerCollection = Extensions.ToProviders(providers);
                var profileProviders   = new List <Provider>();

                // If user defined a different key/level on the same provider via --providers option that was specified via --profile option,
                // --providers option takes precedence. Go through the list of providers specified and only add it if it wasn't specified
                // via --providers options.
                if (selectedProfile.Providers != null)
                {
                    foreach (Provider selectedProfileProvider in selectedProfile.Providers)
                    {
                        bool shouldAdd = true;

                        foreach (Provider providerCollectionProvider in providerCollection)
                        {
                            if (providerCollectionProvider.Name.Equals(selectedProfileProvider.Name))
                            {
                                shouldAdd = false;
                                break;
                            }
                        }

                        if (shouldAdd)
                        {
                            profileProviders.Add(selectedProfileProvider);
                        }
                    }
                }

                providerCollection.AddRange(profileProviders);

                if (providerCollection.Count <= 0)
                {
                    Console.Error.WriteLine("No providers were specified to start a trace.");
                    return(ErrorCodes.ArgumentError);
                }

                PrintProviders(providerCollection);

                var process       = Process.GetProcessById(processId);
                var configuration = new SessionConfiguration(
                    circularBufferSizeMB: buffersize,
                    format: EventPipeSerializationFormat.NetTrace,
                    providers: providerCollection);

                var shouldExit = new ManualResetEvent(false);
                var failed     = false;
                var terminated = false;

                ct.Register(() => shouldExit.Set());

                ulong sessionId = 0;
                using (Stream stream = EventPipeClient.CollectTracing(processId, configuration, out sessionId))
                    using (VirtualTerminalMode vTermMode = VirtualTerminalMode.TryEnable())
                    {
                        if (sessionId == 0)
                        {
                            Console.Error.WriteLine("Unable to create session.");
                            return(ErrorCodes.SessionCreationError);
                        }

                        var collectingTask = new Task(() => {
                            try
                            {
                                using (var fs = new FileStream(output.FullName, FileMode.Create, FileAccess.Write))
                                {
                                    Console.Out.WriteLine($"Process     : {process.MainModule.FileName}");
                                    Console.Out.WriteLine($"Output File : {fs.Name}");
                                    Console.Out.WriteLine($"\tSession Id: 0x{sessionId:X16}");
                                    lineToClear = Console.CursorTop;
                                    var buffer  = new byte[16 * 1024];

                                    while (true)
                                    {
                                        int nBytesRead = stream.Read(buffer, 0, buffer.Length);
                                        if (nBytesRead <= 0)
                                        {
                                            break;
                                        }
                                        fs.Write(buffer, 0, nBytesRead);

                                        ResetCurrentConsoleLine(vTermMode.IsEnabled);
                                        Console.Out.Write($"\tRecording trace {GetSize(fs.Length)}");

                                        Debug.WriteLine($"PACKET: {Convert.ToBase64String(buffer, 0, nBytesRead)} (bytes {nBytesRead})");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                failed = true;
                                Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
                            }
                            finally
                            {
                                terminated = true;
                                shouldExit.Set();
                            }
                        });
                        collectingTask.Start();

                        Console.Out.WriteLine("Press <Enter> or <Ctrl+C> to exit...");

                        do
                        {
                            while (!Console.KeyAvailable && !shouldExit.WaitOne(250))
                            {
                            }
                        } while (!shouldExit.WaitOne(0) && Console.ReadKey(true).Key != ConsoleKey.Enter);

                        if (!terminated)
                        {
                            EventPipeClient.StopTracing(processId, sessionId);
                        }
                        await collectingTask;
                    }

                Console.Out.WriteLine();
                Console.Out.WriteLine("Trace completed.");

                if (format != TraceFileFormat.NetTrace)
                {
                    TraceFileFormatConverter.ConvertToFormat(format, output.FullName);
                }

                return(failed ? ErrorCodes.TracingError : 0);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
                return(ErrorCodes.UnknownError);
            }
        }
Beispiel #38
0
 internal BrowserSession BuildSession(TimingStrategy timingStrategy)
 {
     SessionConfiguration = new SessionConfiguration();
     return TestSessionBuilder.Build(SessionConfiguration,new FakeDriver(), timingStrategy, new FakeWaiter(), null, null);
 }
 internal static BrowserSession Build(SessionConfiguration SessionConfiguration, Driver driver, RobustWrapper robustWrapper, Waiter waiter,
     RestrictedResourceDownloader restrictedResourceDownloader, UrlBuilder urlBuilder)
 {
     return new BrowserSession(new StubDriverFactory(driver), SessionConfiguration, robustWrapper, waiter, restrictedResourceDownloader, urlBuilder);
 }
Beispiel #40
0
 public void SetUp()
 {
     SessionConfiguration = new SessionConfiguration();
     fullyQualifiedUrlBuilder = new FullyQualifiedUrlBuilder();
 }
 public void SetUpFixture()
 {
     SessionConfiguration = new SessionConfiguration();
     SessionConfiguration.Timeout = TimeSpan.FromMilliseconds(1000);
     browser = new BrowserSession(SessionConfiguration);
 }
Beispiel #42
0
 public void SetUpFixture()
 {
     SessionConfiguration         = new SessionConfiguration();
     SessionConfiguration.Timeout = TimeSpan.FromMilliseconds(1000);
     browser = new BrowserSession(SessionConfiguration);
 }
Beispiel #43
0
        public static async Task <bool> TEST_ReverseConnectionCanRecycleWhileTracing()
        {
            bool   fSuccess   = true;
            string serverName = ReverseServer.MakeServerAddress();

            Logger.logger.Log($"Server name is '{serverName}'");
            Task <bool> subprocessTask = Utils.RunSubprocess(
                currentAssembly: Assembly.GetExecutingAssembly(),
                environment: new Dictionary <string, string>
            {
                { Utils.DiagnosticPortsEnvKey, $"{serverName},nosuspend" }
            },
                duringExecution: async(int pid) =>
            {
                ManualResetEvent mre = new ManualResetEvent(false);
                Task regularTask     = Task.Run(async() =>
                {
                    try
                    {
                        var config = new SessionConfiguration(
                            circularBufferSizeMB: 1000,
                            format: EventPipeSerializationFormat.NetTrace,
                            providers: new List <Provider> {
                            new Provider("Microsoft-DotNETCore-SampleProfiler")
                        });
                        Logger.logger.Log("Starting EventPipeSession over standard connection");
                        using Stream stream = EventPipeClient.CollectTracing(pid, config, out var sessionId);
                        Logger.logger.Log($"Started EventPipeSession over standard connection with session id: 0x{sessionId:x}");
                        // using var source = new EventPipeEventSource(stream);
                        using var memroyStream = new MemoryStream();
                        Task readerTask        = stream.CopyToAsync(memroyStream);//Task.Run(() => source.Process());
                        await Task.Delay(500);
                        Logger.logger.Log("Stopping EventPipeSession over standard connection");
                        EventPipeClient.StopTracing(pid, sessionId);
                        await readerTask;
                        Logger.logger.Log("Stopped EventPipeSession over standard connection");
                    }
                    catch (Exception e)
                    {
                        Logger.logger.Log(e.ToString());
                    }
                    finally
                    {
                        Logger.logger.Log("setting the MRE");
                        mre.Set();
                    }
                });

                Task reverseTask = Task.Run(async() =>
                {
                    while (!mre.WaitOne(0))
                    {
                        var ad1 = await ReverseServer.CreateServerAndReceiveAdvertisement(serverName);
                        Logger.logger.Log(ad1.ToString());
                    }
                });

                await Task.WhenAll(reverseTask, regularTask);
            }
                );

            fSuccess &= await subprocessTask;

            return(fSuccess);
        }
Beispiel #44
0
 public SmokeTestSteps(IObjectContainer objectContainer, IViewFactory viewFactory, SessionConfiguration sessionConfiguration)
     : base(objectContainer)
 {
     _sessionConfiguration = sessionConfiguration;
     _viewFactory          = viewFactory;
 }
Beispiel #45
0
 public static void Start(SessionConfiguration sessionConfig)
 {
     _browserSessions.TryAdd(Thread.CurrentThread.GetHashCode(), new BrowserSession(sessionConfig));
 }
Beispiel #46
0
        public void CustomProfile()
        {
            var configuration = new SessionConfiguration {Driver = typeof (CustomFirefoxProfileSeleniumWebDriver)};

            using (var custom = new BrowserSession(configuration))
            {
                custom.Visit("https://www.relishapp.com/");
                Assert.That(custom.ExecuteScript("return 0;"), Is.EqualTo("0"));
            }
        }
Beispiel #47
0
        private async Task <int> StartMonitor()
        {
            if (_processId == 0)
            {
                _console.Error.WriteLine("ProcessId is required.");
                return(1);
            }

            String providerString;

            if (_counterList.Count == 0)
            {
                CounterProvider defaultProvider = null;
                _console.Out.WriteLine($"counter_list is unspecified. Monitoring all counters by default.");

                // Enable the default profile if nothing is specified
                if (!KnownData.TryGetProvider("System.Runtime", out defaultProvider))
                {
                    _console.Error.WriteLine("No providers or profiles were specified and there is no default profile available.");
                    return(1);
                }
                providerString = defaultProvider.ToProviderString(_interval);
                filter.AddFilter("System.Runtime");
            }
            else
            {
                CounterProvider provider = null;
                StringBuilder   sb       = new StringBuilder("");
                for (var i = 0; i < _counterList.Count; i++)
                {
                    string   counterSpecifier = _counterList[i];
                    string[] tokens           = counterSpecifier.Split('[');
                    string   providerName     = tokens[0];
                    if (!KnownData.TryGetProvider(providerName, out provider))
                    {
                        sb.Append(CounterProvider.SerializeUnknownProviderName(providerName, _interval));
                    }
                    else
                    {
                        sb.Append(provider.ToProviderString(_interval));
                    }

                    if (i != _counterList.Count - 1)
                    {
                        sb.Append(",");
                    }

                    if (tokens.Length == 1)
                    {
                        filter.AddFilter(providerName); // This means no counter filter was specified.
                    }
                    else
                    {
                        string   counterNames    = tokens[1];
                        string[] enabledCounters = counterNames.Substring(0, counterNames.Length - 1).Split(',');

                        filter.AddFilter(providerName, enabledCounters);
                    }
                }
                providerString = sb.ToString();
            }

            ManualResetEvent shouldExit = new ManualResetEvent(false);
            var terminated = false;

            writer.InitializeDisplay();

            Task monitorTask = new Task(() => {
                try
                {
                    var configuration = new SessionConfiguration(
                        circularBufferSizeMB: 1000,
                        format: EventPipeSerializationFormat.NetTrace,
                        providers: Trace.Extensions.ToProviders(providerString));

                    var binaryReader            = EventPipeClient.CollectTracing(_processId, configuration, out _sessionId);
                    EventPipeEventSource source = new EventPipeEventSource(binaryReader);
                    source.Dynamic.All         += Dynamic_All;
                    source.Process();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"[ERROR] {ex.ToString()}");
                }
                finally
                {
                    terminated = true; // This indicates that the runtime is done. We shouldn't try to talk to it anymore.
                    shouldExit.Set();
                }
            });

            monitorTask.Start();
            Console.CancelKeyPress += (sender, args) => {
                args.Cancel = true;
                shouldExit.Set();
            };
            while (!shouldExit.WaitOne(250))
            {
                while (true)
                {
                    if (shouldExit.WaitOne(250))
                    {
                        StopMonitor();
                        return(0);
                    }
                    if (Console.KeyAvailable)
                    {
                        break;
                    }
                }
                ConsoleKey cmd = Console.ReadKey(true).Key;
                if (cmd == ConsoleKey.Q)
                {
                    break;
                }
                else if (cmd == ConsoleKey.P)
                {
                    pauseCmdSet = true;
                }
                else if (cmd == ConsoleKey.R)
                {
                    pauseCmdSet = false;
                }
            }
            if (!terminated)
            {
                StopMonitor();
            }

            return(await Task.FromResult(0));
        }
Beispiel #48
0
 public Hooks(SessionConfiguration sessionConfig, ZukiniConfiguration zukiniConfig)
 {
     _sessionConfiguration = sessionConfig;
     _zukiniConfiguration  = zukiniConfig;
 }
 internal BrowserSession BuildSession(RobustWrapper robustWrapper)
 {
     SessionConfiguration = new SessionConfiguration();
     return TestSessionBuilder.Build(SessionConfiguration,new FakeDriver(), robustWrapper, new FakeWaiter(), null, null);
 }
Beispiel #50
0
        // Constructors

        internal Session(Domain domain, StorageNode selectedStorageNode, SessionConfiguration configuration, bool activate)
            : base(domain)
        {
            Guid = Guid.NewGuid();
            IsDebugEventLoggingEnabled = OrmLog.IsLogged(LogLevel.Debug); // Just to cache this value

            // Both Domain and Configuration are valid references here;
            // Configuration is already locked
            Configuration  = configuration;
            Name           = configuration.Name;
            identifier     = Interlocked.Increment(ref lastUsedIdentifier);
            CommandTimeout = configuration.DefaultCommandTimeout;
            allowSwitching = configuration.Supports(SessionOptions.AllowSwitching);
            storageNode    = selectedStorageNode;

            // Handlers
            Handlers = domain.Handlers;
            Handler  = CreateSessionHandler();

            // Caches, registry
            EntityStateCache               = CreateSessionCache(configuration);
            EntityChangeRegistry           = new EntityChangeRegistry(this);
            EntitySetChangeRegistry        = new EntitySetChangeRegistry(this);
            ReferenceFieldsChangesRegistry = new ReferenceFieldsChangesRegistry(this);
            entitySetsWithInvalidState     = new HashSet <EntitySetBase>();

            // Events
            EntityEvents = new EntityEventBroker();
            Events       = new SessionEventAccessor(this, false);
            SystemEvents = new SessionEventAccessor(this, true);

            // Etc.
            PairSyncManager                 = new SyncManager(this);
            RemovalProcessor                = new RemovalProcessor(this);
            pinner                          = new Pinner(this);
            Operations                      = new OperationRegistry(this);
            NonPairedReferencesRegistry     = new NonPairedReferenceChangesRegistry(this);
            CommandProcessorContextProvider = new CommandProcessorContextProvider(this);

            // Validation context
            ValidationContext = Configuration.Supports(SessionOptions.ValidateEntities)
        ? (ValidationContext) new RealValidationContext()
        : new VoidValidationContext();

            // Creating Services
            Services = CreateServices();

            disposableSet = new DisposableSet();
            remapper      = new KeyRemapper(this);

            disableAutoSaveChanges = !configuration.Supports(SessionOptions.AutoSaveChanges);

            // Perform activation
            if (activate)
            {
                AttachToScope(new SessionScope());
            }

            // Query endpoint
            SystemQuery = Query = new QueryEndpoint(new QueryProvider(this));
        }
 public void SetUp()
 {
     SessionConfiguration = new SessionConfiguration();
     SessionConfiguration.Driver = typeof (FakeDriver);
 }