Example #1
0
        private static int MainImpl(string[] args)
        {
            if (File.Exists(@"c:\debug.testhost.txt"))
            {
                while (true)
                {
                    System.Threading.Thread.Sleep(2000);
                }
            }

            LogInfo("TestHost: Entering Main.");
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomainUnhandledException);
            var command                   = args[0];
            var buildRoot                 = args[1];
            var codeCoverageStore         = args[2];
            var testResultsStore          = args[3];
            var discoveredUnitTestsStore  = args[4];
            var testFailureInfoStore      = args[5];
            var timeFilter                = args[6];
            var slnPath                   = args[7];
            var slnSnapPath               = args[8];
            var discoveredUnitDTestsStore = args[9];
            var ignoredTests              = (args[10] ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            var searchPath = FilePath.NewFilePath(Path.Combine(Path.GetDirectoryName(slnSnapPath), "packages"));

            if (command == "discover")
            {
                var tds = AdapterLoader.LoadDiscoverers(searchPath.Item);
                DiscoverUnitTests(tds, slnPath, slnSnapPath, discoveredUnitTestsStore, discoveredUnitDTestsStore, buildRoot, new DateTime(long.Parse(timeFilter)), ignoredTests);
                LogInfo("TestHost: Exiting Main.");
                return(0);
            }
            else
            {
                var tes            = AdapterLoader.LoadExecutors(searchPath.Item);
                var allTestsPassed = false;
                if (_debuggerAttached)
                {
                    allTestsPassed = RunTests(tes, slnPath, slnSnapPath, buildRoot, testResultsStore, testFailureInfoStore, GetTestToDebug(discoveredUnitTestsStore, discoveredUnitDTestsStore));
                }
                else
                {
                    allTestsPassed = ExecuteTestWithCoverageDataCollection(() => RunTests(tes, slnPath, slnSnapPath, buildRoot, testResultsStore, testFailureInfoStore, PerDocumentLocationXTestCases.Deserialize(FilePath.NewFilePath(discoveredUnitTestsStore))), codeCoverageStore);
                }

                LogInfo("TestHost: Exiting Main.");
                return(allTestsPassed ? 0 : 1);
            }
        }
Example #2
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            // Stop file monitor timer
            if ((object)m_fileMonitor != null)
            {
                m_fileMonitor.Elapsed -= FileMonitor_Elapsed;
                m_fileMonitor.Dispose();
                m_fileMonitor = null;
            }

            // Dispose of fault results writers
            if ((object)m_resultsWriters != null)
            {
                m_resultsWriters.Dispose();
                m_resultsWriters = null;
            }
        }
Example #3
0
        private void ServiceHelper_ServiceStarted(object sender, EventArgs e)
        {
            m_serviceHelper.AddScheduledProcess(ServiceHeartbeatHandler, "ServiceHeartbeat", "* * * * *");
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("ReloadConfig", "Reloads configuration from configuration file", ReloadConfigRequestHandler));
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("ForceEvent", "Forces an event to be processed by the file watcher", ForceEventRequestHandler));
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("MsgServiceMonitors", "Sends a message to all service monitors", MsgServiceMonitorsRequestHandler));

            m_serviceMonitors = new AdapterLoader <IServiceMonitor>();
            m_serviceMonitors.AdapterCreated  += ServiceMonitors_AdapterCreated;
            m_serviceMonitors.AdapterLoaded   += ServiceMonitors_AdapterLoaded;
            m_serviceMonitors.AdapterUnloaded += ServiceMonitors_AdapterUnloaded;
            m_serviceMonitors.Initialize();

            m_configFile  = Path.Combine(Application.StartupPath, "Filewatcher.config");
            m_fileWatcher = new XDAFileWatcher();
            m_fileWatcher.ReadConfigFile(m_configFile);
            m_fileWatcher.StartWatching();
        }
        private void ServiceHelper_ServiceStarted(object sender, EventArgs e)
        {
            // Define a line of asterisks for emphasis
            string stars = new string('*', 79);

            // Get current process memory usage
            long processMemory = Common.GetProcessMemory();

            // Log startup information
            m_serviceHelper.UpdateStatus(
                UpdateType.Information,
                "{14}{14}{0}{14}{14}" +
                "{1} Initializing{14}{14}" +
                "     System Time: {2} UTC{14}{14}" +
                "    Current Path: {3}{14}{14}" +
                "    Machine Name: {4}{14}{14}" +
                "      OS Version: {5}{14}{14}" +
                "    Product Name: {6}{14}{14}" +
                "  Working Memory: {7}{14}{14}" +
                "  Execution Mode: {8}-bit{14}{14}" +
                "      Processors: {9}{14}{14}" +
                "  GC Server Mode: {10}{14}{14}" +
                " GC Latency Mode: {11}{14}{14}" +
                " Process Account: {12}\\{13}{14}{14}" +
                "{0}{14}",
                stars,
                ServiceName,
                DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                FilePath.TrimFileName(FilePath.RemovePathSuffix(FilePath.GetAbsolutePath("")), 61),
                Environment.MachineName,
                Environment.OSVersion.VersionString,
                Common.GetOSProductName(),
                processMemory > 0 ? SI2.ToScaledString(processMemory, 4, "B", SI2.IECSymbols) : "Undetermined",
                IntPtr.Size * 8,
                Environment.ProcessorCount,
                GCSettings.IsServerGC,
                GCSettings.LatencyMode,
                Environment.UserDomainName,
                Environment.UserName,
                Environment.NewLine);

            // Add run-time log as a service component
            m_serviceHelper.ServiceComponents.Add(m_runTimeLog);

            // Define scheduled service processes
            m_serviceHelper.AddScheduledProcess(ServiceHeartbeatHandler, "ServiceHeartbeat", "* * * * *");

            // Define remote client service command requests (i.e., console commands)
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("Restart", "Attempts to restart the host service", RestartServiceHandler));
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("Initialize", "Attempts to re-initialize algorithm processing framework.", ReinitializeAlgorithmHandler, new[] { "Reinitialize" }));
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("Status", "Gets current algorithm processing framework status.", FrameworkStatusHandler, new[] { "list", "ls" }));
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("LogEvent", "Logs remote event log entries.", LogEventRequestHandler, false));

            if (m_allowServiceMonitors)
            {
                // Establish plug-in service monitoring architecture - external implementations of IServiceMonitor will be auto-loaded
                m_serviceMonitors = new AdapterLoader <IServiceMonitor>();
                m_serviceMonitors.AdapterCreated  += ServiceMonitors_AdapterCreated;
                m_serviceMonitors.AdapterLoaded   += ServiceMonitors_AdapterLoaded;
                m_serviceMonitors.AdapterUnloaded += ServiceMonitors_AdapterUnloaded;
                m_serviceMonitors.Initialize();

                // Add service monitoring command
                m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("NotifyMonitors", "Sends a message to all service monitors", NotifyMonitorsRequestHandler));
            }

            // Start algorithm processing framework
            StartAlgorithmProcessing();

            // If any settings have been added to configuration file, we go ahead and save them now
            m_serviceHelper.SaveSettings(true);
            ConfigurationFile.Current.Save();
        }
Example #5
0
        /// <summary>
        /// Starts the fault location engine.
        /// </summary>
        public void Start()
        {
            // Make sure default service settings exist
            ConfigurationFile configFile = ConfigurationFile.Current;

            // System settings
            // TODO: Add description to system settings
            CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"];

            systemSettings.Add("DeviceDefinitionsFile", "DeviceDefinitions.xml", "");
            systemSettings.Add("ProcessDelay", "15", "");
            systemSettings.Add("DropFolder", "Drop", "");
            systemSettings.Add("LengthUnits", "Miles", "");
            systemSettings.Add("DebugLevel", "1", "");
            systemSettings.Add("DebugFolder", "Debug", "");

            // Retrieve file paths as defined in the config file
            m_deviceDefinitionsFile = FilePath.GetAbsolutePath(systemSettings["DeviceDefinitionsFile"].Value);
            m_processDelay          = systemSettings["ProcessDelay"].ValueAs(m_processDelay);
            m_dropFolder            = FilePath.AddPathSuffix(FilePath.GetAbsolutePath(systemSettings["DropFolder"].Value));
            m_lengthUnits           = systemSettings["LengthUnits"].Value;
            m_debugLevel            = systemSettings["DebugLevel"].ValueAs(m_debugLevel);
            m_debugFolder           = FilePath.AddPathSuffix(FilePath.GetAbsolutePath(systemSettings["DebugFolder"].Value));

            // Load the fault results writer defined in systemSettings
            using (AdapterLoader <IFaultResultsWriter> resultsWriters = m_resultsWriters)
            {
                m_resultsWriters = new AdapterLoader <IFaultResultsWriter>();
                m_resultsWriters.AdapterCreated  += (sender, args) => args.Argument.PersistSettings = true;
                m_resultsWriters.AdapterLoaded   += (sender, args) => OnStatusMessage("{0} has been loaded", args.Argument.Name);
                m_resultsWriters.AdapterUnloaded += (sender, args) => OnStatusMessage("{0} has been unloaded", args.Argument.Name);
                m_resultsWriters.Initialize();
            }

            try
            {
                // Make sure file path directories exist
                if (!Directory.Exists(m_dropFolder))
                {
                    Directory.CreateDirectory(m_dropFolder);
                }

                if (m_debugLevel > 0 && !Directory.Exists(m_debugFolder))
                {
                    Directory.CreateDirectory(m_debugFolder);
                }
            }
            catch (Exception ex)
            {
                OnProcessException(new InvalidOperationException(string.Format("Failed to create directory due to exception: {0}", ex.Message), ex));
            }

            // Setup new simple file monitor - we do this since the .NET 4.0 FileWatcher has a bad memory leak :-(
            if ((object)m_fileMonitor == null)
            {
                m_fileMonitor           = new System.Timers.Timer();
                m_fileMonitor.Interval  = 1000;
                m_fileMonitor.AutoReset = false;
                m_fileMonitor.Elapsed  += FileMonitor_Elapsed;
            }

            // Start watching for files
            m_fileMonitor.Start();
        }
Example #6
0
        protected async override void OnStartup(StartupEventArgs e)
        {
            var adapterLoader = new AdapterLoader();
            var result        = await adapterLoader.FindAdaptersAsync("Adapters", Cts.Token);

            if (result.HasError)
            {
                await Log.ReportErrorAsync(result.Message, Cts.Token);
            }

            var adapterManager = new Processor.AdapterManager(result.Adapters, EntityContextConnection, new DatabaseFeedback(EntityContextConnection));

            var pluginLoader     = new PluginLoader();
            var pluginFindResult = await pluginLoader.FindPluginsAsync("plugins", Cts.Token);

            if (pluginFindResult.HasError)
            {
                await Log.ReportErrorAsync(pluginFindResult.Message, Cts.Token);
            }

            var pluginManager = new Processor.PluginManager(pluginFindResult.Plugins, EntityContextConnection, new DatabaseFeedback(EntityContextConnection), adapterManager);


            var triggerRunner       = new TriggerRunner(new DatabaseFeedback(EntityContextConnection), new CommandProcessor(adapterManager, EntityContextConnection, new DatabaseFeedback(EntityContextConnection)), EntityContextConnection);
            var scheduledTaskRunner = new ScheduledTaskRunner(new DatabaseFeedback(EntityContextConnection), new CommandProcessor(adapterManager, EntityContextConnection, new DatabaseFeedback(EntityContextConnection)), EntityContextConnection, new CurrentTimeProvider());

            ZvsEngine = new ZvsEngine(new DatabaseFeedback(EntityContextConnection), adapterManager, pluginManager, EntityContextConnection, triggerRunner, scheduledTaskRunner);

            var splashscreen = new SplashScreen();

            splashscreen.SetLoadingTextFormat("Starting {0}", Utils.ApplicationNameAndVersion);
            splashscreen.Show();
            await Task.Delay(10);

#if DEBUG
            var sw = new Stopwatch();
            sw.Start();
#endif

#if (RELEASE)
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
            using (var context = new ZvsContext(new ZvsEntityContextConnection()))
            {
                //Install Program Options
                var option =
                    await
                    context.ProgramOptions.FirstOrDefaultAsync(o => o.UniqueIdentifier == "LOGDIRECTION",
                                                               Cts.Token);

                if (option == null)
                {
                    var registerLogDirectionResult = await ProgramOption.TryAddOrEditAsync(context, new ProgramOption
                    {
                        UniqueIdentifier = "LOGDIRECTION",
                        Value            = "Descending"
                    }, Cts.Token);

                    if (registerLogDirectionResult.HasError)
                    {
                        await Log.ReportErrorAsync(registerLogDirectionResult.Message, Cts.Token);
                    }
                }
            }
            //using (var context = new ZvsContext(new ZvsEntityContextConnection()))
            //{
            //    var adapter = CreateFakeAdapter();
            //    context.Devices.Add(new Device
            //    {
            //        Name = "Light Switch",
            //        Location = "Living Room",
            //        Type = new DeviceType
            //        {
            //            Name = "Switch Device Type",
            //            UniqueIdentifier = "Switch",
            //            Adapter = adapter
            //        }
            //    });

            //    context.Devices.Add(new Device
            //    {
            //        Name = "Main Controller",
            //        Location = "Utility",
            //        Type = new DeviceType
            //        {
            //            Name = "Controller Type",
            //            UniqueIdentifier = "Controller",
            //            Adapter = adapter
            //        }
            //    });

            //    context.Devices.Add(new Device
            //    {
            //        Name = "Can Lights",
            //        Location = "Kitchen",
            //        Type = new DeviceType
            //        {
            //            Name = "Dimmer Type",
            //            UniqueIdentifier = "Dimmer",
            //            Adapter = adapter
            //        }
            //    });

            //    context.Devices.Add(new Device
            //    {
            //        Name = "Thermostat",
            //        Location = "Kitchen",
            //        Type = new DeviceType
            //        {
            //            Name = "Thermostat Type",
            //            UniqueIdentifier = "Thermostat",
            //            Adapter = adapter
            //        }
            //    });

            //    context.Devices.Add(new Device
            //    {
            //        Name = "Front Door",
            //        Location = "Entry",
            //        Type = new DeviceType
            //        {
            //            Name = "Doorlock Type",
            //            UniqueIdentifier = "Doorlock",
            //            Adapter = adapter
            //        }
            //    });
            //    var sensorDt = new DeviceType
            //    {
            //        Name = "Sensor Type",
            //        UniqueIdentifier = "Sensor",
            //        Adapter = adapter
            //    };
            //    var device = new Device
            //    {
            //        Name = "Motion Sensor",
            //        Location = "Entry",
            //        Type = sensorDt,
            //    };
            //    var value = new DeviceValue
            //    {
            //        Name = "Level",
            //        ValueType = DataType.BYTE,
            //        Value = "255"
            //    };
            //    device.Values.Add(value);
            //    context.Devices.Add(device);

            //     //context.SaveChanges();
            //}

            #region Create Logger

            await Log.ReportInfoFormatAsync(Cts.Token, "Init Complete ({0})", (Utils.DebugMode ? "Debug Mode" : "Release Mode"));

#if DEBUG
            await Log.ReportInfoAsync("--------------DUMPING ENVIRONMENT--------------", Cts.Token);

            await Log.ReportInfoFormatAsync(Cts.Token, "AppDataPath:{0}", Utils.AppDataPath);

            await Log.ReportInfoFormatAsync(Cts.Token, "AppPath:{0}", Utils.AppPath);

            await Log.ReportInfoFormatAsync(Cts.Token, "ApplicationNameAndVersion:{0}", Utils.ApplicationNameAndVersion);

            await Log.ReportInfoFormatAsync(Cts.Token, "ApplicationVersionLong:{0}", Utils.ApplicationVersionLong);

            await Log.ReportInfoFormatAsync(Cts.Token, "HasDotNet45:{0}", Utils.HasDotNet45());

            await Log.ReportInfoFormatAsync(Cts.Token, "HasSQLCE4:{0}", Utils.HasSQLCE4());

            await Log.ReportInfoFormatAsync(Cts.Token, "CommandLine:{0}", Environment.CommandLine);

            await Log.ReportInfoFormatAsync(Cts.Token, "CurrentDirectory:{0}", Environment.CurrentDirectory);

            await Log.ReportInfoFormatAsync(Cts.Token, "Is64BitOperatingSystem:{0}", Environment.Is64BitOperatingSystem);

            await Log.ReportInfoFormatAsync(Cts.Token, "Is64BitProcess:{0}", Environment.Is64BitProcess);

            await Log.ReportInfoFormatAsync(Cts.Token, "MachineName:{0}", Environment.MachineName);

            await Log.ReportInfoFormatAsync(Cts.Token, "OSVersion:{0}", Environment.OSVersion);

            await Log.ReportInfoFormatAsync(Cts.Token, "ProcessorCount:{0}", Environment.ProcessorCount);

            await Log.ReportInfoFormatAsync(Cts.Token, "UserDomainName:{0}", Environment.UserDomainName);

            await Log.ReportInfoFormatAsync(Cts.Token, "UserInteractive:{0}", Environment.UserInteractive);

            await Log.ReportInfoFormatAsync(Cts.Token, "UserName:{0}", Environment.UserName);

            await Log.ReportInfoFormatAsync(Cts.Token, "Version:{0}", Environment.Version);

            await Log.ReportInfoFormatAsync(Cts.Token, "WorkingSet:{0}", Environment.WorkingSet);

            await Log.ReportInfoAsync("--------------/DUMPING ENVIRONMENT--------------", Cts.Token);
#endif
            AppDomain.CurrentDomain.SetData("DataDirectory", Utils.AppDataPath);
            #endregion

            #region Checking for other running instances
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Checking for other running instances");
            await Task.Delay(10);

            try
            {
                _zvsMutex = Mutex.OpenExisting("zVirtualScenesGUIMutex");
                ProgramHasToClosePrompt(Utils.ApplicationName + " can't start because it is already running");
            }
            catch
            {
                //the specified mutex doesn't exist, we should create it
                _zvsMutex = new Mutex(true, "zVirtualScenesGUIMutex"); //these names need to match.
            }
            #endregion

            #region Check for .Net Framework 4.5
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Checking for .Net framework 4.5");
            await Task.Delay(10);

            if (!Utils.HasDotNet45())
            {
                ProgramHasToClosePrompt(
                    $"Microsoft .NET Framework 4.5 Full/Extended is required to run {Utils.ApplicationName}. \r\n\r\nPlease install Microsoft .NET Framework 4.5 and re-launch the application.");
            }
            #endregion

            #region Checking for Microsoft® SQL Server® Compact 4.0 SP1
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Checking for Microsoft® SQL Server® Compact 4.0 SP1");
            await Task.Delay(10);

            if (!Utils.HasSQLCE4())
            {
                ProgramHasToClosePrompt(
                    $"Microsoft® SQL Server® Compact 4.0 SP1 is required to run {Utils.ApplicationName}. \r\n\r\nPlease install Microsoft® SQL Server® Compact 4.0 SP1 and re-launch the application.");
            }
            #endregion

            #region Initializing and upgrading local database
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Initializing and migrating database");
            await Task.Delay(10);

            await Task.Run(() =>
            {
                using (var context = new ZvsContext())
                {
                    var configuration = new Configuration();
                    var migrator      = new DbMigrator(configuration);

                    migrator.Update();
                    context.Database.Initialize(true);
                }
            });

            #endregion

            //TODO: Check for VCRedist

            #region Start zvsEngine Services
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Starting zvsEngine services");
            await Task.Delay(10);

            //Initialize the zvsEngine

            try
            {
                await Task.Run(() => ZvsEngine.StartAsync(Cts.Token));
            }
            catch (Exception ex)
            {
                ProgramHasToClosePrompt(ex.Message);
            }

            #endregion

            //Create taskbar Icon
            TaskbarIcon = new ZVSTaskbarIcon();
            TaskbarIcon.ShowBalloonTip(Utils.ApplicationName, Utils.ApplicationNameAndVersion + " started", 3000, ToolTipIcon.Info);

            //close Splash Screen
            splashscreen.Close();

#if DEBUG
            sw.Stop();
            Debug.WriteLine("App Startup initialized in {0}", sw.Elapsed.ToString() as object);
#endif

            base.OnStartup(e);
        }
        private void ServiceHelper_ServiceStarted(object sender, EventArgs e)
        {
            m_serviceHelper.AddScheduledProcess(ServiceHeartbeatHandler, "ServiceHeartbeat", "* * * * *");
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("ReloadConfig", "Reloads configuration from configuration file", ReloadConfigRequestHandler));
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("ForceEvent", "Forces an event to be processed by the file watcher", ForceEventRequestHandler));
            m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("MsgServiceMonitors", "Sends a message to all service monitors", MsgServiceMonitorsRequestHandler));

            m_serviceMonitors = new AdapterLoader<IServiceMonitor>();
            m_serviceMonitors.AdapterCreated += ServiceMonitors_AdapterCreated;
            m_serviceMonitors.AdapterLoaded += ServiceMonitors_AdapterLoaded;
            m_serviceMonitors.AdapterUnloaded += ServiceMonitors_AdapterUnloaded;
            m_serviceMonitors.Initialize();

            m_configFile = Path.Combine(Application.StartupPath, "Filewatcher.config");
            m_fileWatcher = new XDAFileWatcher();
            m_fileWatcher.ReadConfigFile(m_configFile);
            m_fileWatcher.StartWatching();
        }