/// <summary>
        /// Gets the or create instance.
        /// </summary>
        /// <returns>The or create instance.</returns>
        /// <param name="clientContextConfig">Client context config.</param>
        /// <param name="regionEndpoint">Region endpoint.</param>
        /// <param name="credentials">Credentials.</param>
        private static MobileAnalyticsManager GetOrCreateInstanceHelper(string appId,
                                                                        AWSCredentials credential,
                                                                        RegionEndpoint regionEndpoint
                                                                        )
        {
            MobileAnalyticsManager managerInstance = null;
            bool isNewInstance = false;

            lock (_lock)
            {
                if (_instanceDictionary.ContainsKey(appId))
                {
                    managerInstance = _instanceDictionary[appId];
                }
                else
                {
                    managerInstance            = new MobileAnalyticsManager(appId, credential, regionEndpoint);
                    _instanceDictionary[appId] = managerInstance;
                    isNewInstance = true;
                }
            }

            if (isNewInstance)
            {
                managerInstance.Session.Start();
            }

            BackgroundRunner.StartWork();

            return(managerInstance);
        }
        private async Task EnsureAllProjectsAreAllocated()
        {
            var projects = await projectRepo.GetAll();

            if (projects != null)
            {
                var notAllocatedProjects = new List <Project>(projects)
                                           .Where(x => this.runners.Any(y => y.Name == x.Name) == false)
                                           .ToList();
                foreach (var p in notAllocatedProjects)
                {
                    Log.Information($"A new project is discovered named {p.Name}");

                    var newRunner = new BackgroundRunner(p.Name, new BuildAndDeployAction(), new BuildAndDeployActionPayload
                    {
                        ProjectId         = p.Id,
                        ProjectRepository = projectRepo,
                        ServiceProvider   = services,
                    });

                    this.runners.Add(newRunner);
                    newRunner.Start();
                }
            }
        }
Example #3
0
        public void Start(IProgram runnable, IChannel channel, RunningOptions options)
        {
            this.options  = options;
            this.runnable = runnable;
            this.channel  = channel;

            var timeRemaining = runnable.Duration(options);

            etaLabel.Text = timeRemaining.ToString();

            programLabel.Text   = runnable.Name;
            generatorLabel.Text = channel.ToString();
            amplitudeLabel.Text = $"10 V";
            waveformLabel.Text  = "Sine";
            statusLabel.Text    = "Running";
            pauseButton.Text    = "Pause";
            pauseButton.Enabled = true;
            stopButton.Enabled  = true;

            runner           = new BackgroundRunner();
            runner.Progress += new ProgressChanged((a, b, c, d, e) => this.BeginInvoke(new ProgressChanged(ProgressUpdated), a, b, c, d, e));


            runner.Start(runnable, channel, options);
        }
        public void TestRecordEvent()
        {
            // Need to make sure that background runner does not attempt to deliver events during
            // test (and consequently delete them from local storage). Restart Background runner
            // and sleep until after it checks for events to send.
            BackgroundRunner.AbortBackgroundThread();
            System.Reflection.FieldInfo fieldInfo        = typeof(MobileAnalyticsManager).GetField("_backgroundRunner", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            BackgroundRunner            backgroundRunner = fieldInfo.GetValue(null) as BackgroundRunner;

            backgroundRunner.StartWork();
            Thread.Sleep(1000);

            string appID = Guid.NewGuid().ToString();
            MobileAnalyticsManager manager    = MobileAnalyticsManager.GetOrCreateInstance(appID, TestRunner.Credentials, RegionEndpoint.USEast1);
            SQLiteEventStore       eventStore = new SQLiteEventStore(new MobileAnalyticsManagerConfig());

            try
            {
                CustomEvent customEvent = new CustomEvent("TestRecordEvent");
                customEvent.AddAttribute("LevelName", "Level5");
                customEvent.AddAttribute("Successful", "True");
                customEvent.AddMetric("Score", 12345);
                customEvent.AddMetric("TimeInLevel", 64);
                manager.RecordEvent(customEvent);

                MonetizationEvent monetizationEvent = new MonetizationEvent();
                monetizationEvent.Quantity           = 10.0;
                monetizationEvent.ItemPrice          = 2.00;
                monetizationEvent.ProductId          = "ProductId123";
                monetizationEvent.ItemPriceFormatted = "$2.00";
                monetizationEvent.Store         = "Amazon";
                monetizationEvent.TransactionId = "TransactionId123";
                monetizationEvent.Currency      = "USD";
                manager.RecordEvent(monetizationEvent);
            }
            catch (Exception e)
            {
                Console.WriteLine("Catch exception: " + e.ToString());
                Assert.Fail();
            }

            // sleep a while to make sure event is stored
            Thread.Sleep(TimeSpan.FromSeconds(1));

            // Event store should have one custom event, one monetization event and one session start event.
            Assert.AreEqual(3, eventStore.NumberOfEvents(appID));


            eventStore.Dispose();
        }
Example #5
0
        public TestPresenter(TestPlace place, Services services)
        {
            this.place    = place;
            this.services = services;

            backgroundRunner = new BackgroundRunner(services.TestView.ProvidedControl);

            backgroundRunner.ListBegin      += new EventHandler(backgroundRunner_ListBegin);
            backgroundRunner.ListEntrySuite += new EventHandler <ListEntrySuiteEventArgs>(backgroundRunner_ListEntrySuite);
            backgroundRunner.ListEntryCase  += new EventHandler <ListEntryCaseEventArgs>(backgroundRunner_ListEntryCase);
            backgroundRunner.ListEnd        += new EventHandler(backgroundRunner_ListEnd);

            backgroundRunner.ReportBegin += new EventHandler(backgroundRunner_ReportBegin);
            backgroundRunner.CasePass    += new EventHandler <CaseEventArgs>(backgroundRunner_CasePass);
            backgroundRunner.CaseFail    += new EventHandler <CaseFailEventArgs>(backgroundRunner_CaseFail);
            backgroundRunner.ReportEnd   += new EventHandler(backgroundRunner_ReportEnd);

            backgroundRunner.Finished        += new EventHandler(backgroundRunner_Finished);
            backgroundRunner.InvalidTestCase += new EventHandler(backgroundRunner_InvalidTestCase);
        }
        public void MultipleThreadOverlap()
        {
            using (RequestContext.Create())
            {
                RequestContext.Current["foo"] = "bar";

                BackgroundRunner runner = new BackgroundRunner();

                runner.Run("foo", "baaz");

                Assert.IsNull(runner.ValueRetrievedBefore,
                    "Checking that value starts null in a different context.");
                Assert.AreEqual("baaz", runner.ValueRetrievedAfter,
                    "Checking that a second thread read a different context.");

                Assert.AreEqual("bar", RequestContext.Current["foo"],
                    "Checking that second thread didn't trash first thread's data.");

            }
        }
Example #7
0
 static void Main(string[] args)
 {
     if (Array.IndexOf(args, "-service") >= 0)
     {
         // Run the application as a service that has been installed with InstallUtil.exe
         BackgroundRunner.RunService();
     }
     else if (Array.IndexOf(args, "-console") >= 0)
     {
         // Run the application as background.
         BackgroundRunner.RunConsole();
     }
     else
     {
         // Run the program with WPF GUI.
         System.Windows.Forms.Application.EnableVisualStyles();
         System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
         App.Main();
     }
 }
Example #8
0
        public void Start(IChannel channel, IHeartRateMonitor hrm, BiofeedbackSettings settings, Action <Biofeedback.Sample[]> finished)
        {
            if (channel is null)
            {
                throw new ArgumentException(nameof(channel));
            }
            if (hrm is null)
            {
                throw new ArgumentException(nameof(hrm));
            }

            finishedAction = finished;
            bf             = new Biofeedback();

            if (channel is null)
            {
                throw new ArgumentException("Couldn't open a channel");
            }

            source = new HrmSource(hrm);

            bf.Enqueue(settings.MinFrequency, settings.MaxFrequency, settings.StepSize);
            int frequencySteps = bf.TotalSteps;

            heatmapControl.NumberOfPoints = frequencySteps;
            heatmapControl.MinX           = settings.MinFrequency;
            heatmapControl.MaxX           = settings.MaxFrequency;
            statusLabel.Text = "Running";
            pauseButton.Text = "Pause";

            biofeedback = new Biofeedback();
            biofeedback.Enqueue(settings.MinFrequency, settings.MaxFrequency, settings.StepSize);
            runner                  = new BackgroundRunner();
            biofeedback.Source      = source;
            biofeedback.OnProgress += new Biofeedback.Progress((f, r, s, t) => BeginInvoke(new Biofeedback.Progress(OnProgress), f, r, s, t));
            biofeedback.OnFinished += new Biofeedback.Finished(r => BeginInvoke(new Biofeedback.Finished(OnFinished), new object[] { r }));
            runner.Progress        += new ProgressChanged((s, t, w, a, e) => BeginInvoke(new ProgressChanged(OnGeneratorProgress), s, t, w, a, e));
            var options = new RunningOptions();

            runner.Start(biofeedback, channel, options);
        }
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 /// <filterpriority>2</filterpriority>
 public override void Dispose()
 {
     base.Dispose();
     BackgroundRunner.RemovePeriodicTask(RefreshConstraints);
 }
 /// <summary>
 /// Initializes a new instance of the RepoConstraintFactory class
 /// </summary>
 /// <param name="contextProvider">the contextprovider object that enables this Factory to access the db using EntityFramework</param>
 /// <param name="factory">the pluginFactory that will provide custom plugins that are required in order to execute some constraints</param>
 public RepoConstraintFactory(IContextBuffer contextProvider, PluginFactory factory) : base(factory)
 {
     this.contextProvider = contextProvider;
     RefreshConstraints();
     BackgroundRunner.AddPeriodicTask(RefreshConstraints, 60000);
 }
 public void Cleanup()
 {
     BackgroundRunner.AbortBackgroundThread();
 }
 protected override void Ready()
 {
     BackgroundRunner.AddPeriodicTask(CheckSchedules, 500);
     LogEnvironment.LogDebugEvent("PeriodScheduler is now online", LogSeverity.Report);
     base.Ready();
 }
 /// <summary>
 /// Führt anwendungsspezifische Aufgaben durch, die mit der Freigabe, der Zurückgabe oder dem Zurücksetzen von nicht verwalteten Ressourcen zusammenhängen.
 /// </summary>
 /// <filterpriority>2</filterpriority>
 public override void Dispose()
 {
     BackgroundRunner.RemovePeriodicTask(CheckSchedules);
     base.Dispose();
 }
        /// <summary>
        /// Completes the satrtup and puts this proxy into an operational state
        /// </summary>
        private void StartupComplete()
        {
            client.SubscribeEvent(remoteObjectName, "PackageProcessed",
                                  new PackageFinishedEventHandler((s, e) =>
            {
                PackageSender ntask;

                lock (processingPackages)
                {
                    var retVal =
                        (from t in processingPackages where t.Package.Id == e.Package.Id select t)
                        .FirstOrDefault();
                    if (retVal != null)
                    {
                        processingPackages.Remove(retVal);
                    }

                    ntask = retVal;
                }

                PackageTrigger trigger;
                lock (unCommittedPackages)
                {
                    trigger = (from t in unCommittedPackages
                               where t.Args.Package.Id == e.Package.Id
                               select t).FirstOrDefault();
                }


                if (ntask != null || trigger != null)
                {
                    if ((e.Tasks.All(Success) && Success(e.Package)) || !e.Tasks.Any(RequireReboot))
                    {
                        bool reTriggered = trigger != null;
                        if (!reTriggered)
                        {
                            lock (unCommittedPackages)
                            {
                                if (unCommittedPackages.All(t => t.Args.Package.Id != e.Package.Id))
                                {
                                    unCommittedPackages.Add(new PackageTrigger
                                    {
                                        Args        = e,
                                        LastTrigger = DateTime.MinValue
                                    });
                                }
                            }
                        }

                        if (reTriggered)
                        {
                            LogEnvironment.LogDebugEvent(string.Format("The calling system did not commit the job {0} yet", e.Package.Id), LogSeverity.Warning);
                        }
                    }
                    else
                    {
                        lock (processingPackages)
                        {
                            processingPackages.Add(ntask);
                        }

                        RebootService();
                    }
                }
            }));
            void OpCallback(object o, EventArgs e)
            {
                if (client.Operational)
                {
                    lock (processingPackages)
                    {
                        processingPackages.ForEach(t => t.Sent = false);
                    }
                }
                else
                {
                    timeOfCommunicationLoss = DateTime.Now;
                }

                ((IBidirectionalClient)o).OperationalChanged -= OpCallback;
            };

            client.OperationalChanged += OpCallback;
            InitializeService();
            BackgroundRunner.AddPeriodicTask(ReTriggerPendingTasks, 20000);
        }
 /// <summary>
 /// Führt anwendungsspezifische Aufgaben durch, die mit der Freigabe, der Zurückgabe oder dem Zurücksetzen von nicht verwalteten Ressourcen zusammenhängen.
 /// </summary>
 /// <filterpriority>2</filterpriority>
 public virtual void Dispose()
 {
     BackgroundRunner.RemovePeriodicTask(ReTriggerPendingTasks);
     OnDisposed();
 }
Example #16
0
 /// <summary>
 /// Starts this Scheduler
 /// </summary>
 protected override void Ready()
 {
     BackgroundRunner.AddPeriodicTask(CheckSchedules, 2000);
     base.Ready();
 }