private bool RunValidationQueries(NightWatchmanSettings settings, CommonExtractionContext context)
        {
            foreach (var query in settings.Queries)
            {
                if (!string.IsNullOrEmpty(query.ValidationQuery))
                {
                    var validationParameters = new[]
                    {
                        new SqlParameter("@startdate", SqlDbType.DateTime)
                        {
                            Value = context.StartDate
                        },
                        new SqlParameter("@enddate", SqlDbType.DateTime)
                        {
                            Value = context.EndtDate
                        }
                    };

                    var validationData = queryExecutor.ExecuteQuery(
                        query.ValidationQuery, "Validate_" + query.Name, validationParameters);
                    if (!ValidateQueryResult(query, validationData))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
示例#2
0
        public override void ExtractData(string outputDirectory, CommonExtractionContext context, Dictionary <string, object> pluginSettings)
        {
            var collectorQueries = new CollectorQueries();
            SqlQueryResultSerializer resultSerializer = new SqlQueryResultSerializer(queryExecutor, context.SccmConnection, outputDirectory);

            foreach (var query in collectorQueries.Queries)
            {
                resultSerializer.SerializeQueryResult(query.SelectionQuery, query.Name, null, (msg) => NotifyProgress(
                                                          new ExtractionEventArgs()
                {
                    Status  = ExtractionStatus.Succeeded,
                    Message = msg
                }));
            }

            if (collectorQueries.Queries.Count > 0)
            {
                NotifyProgress(
                    new ExtractionEventArgs()
                {
                    Status  = ExtractionStatus.Succeeded,
                    Message = "All query results collected successfully."
                });
            }
        }
        public void HappyPath_NightWatchmanAnalysis_BuildMachineData()
        {
            const int    DesktopCount          = 50123;
            const int    LaptopCount           = 50321;
            const string companyName           = "Nightwatchman Company, Ltd";
            long         totalMachine          = 5000;
            long         machinesOnForWeekdays = 3000;
            long         machinesOnForWeekend  = 2000;
            long         noOfDays = 15;

            var       machineData = BuildMachineData(DesktopCount, LaptopCount);
            DataTable machineActivityData;
            DataTable machineActivityValidationData;

            BuildMachineActivityData(totalMachine, machinesOnForWeekdays, machinesOnForWeekend, noOfDays, out machineActivityData, out machineActivityValidationData);

            Dictionary <string, DataTable> mockValues = new Dictionary <string, DataTable>()
            {
                { "MachineData", machineData },
                { "MachineActivityData", machineActivityData },
                { "Validate_MachineActivityData", machineActivityValidationData }
            };

            var mockQueryExecutor = new Moq.Mock <IQueryExecutor>();

            mockQueryExecutor.Setup(
                m =>
                m.ExecuteQuery(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <SqlParameter[]>()))
            .Returns(
                (string a, string b, string tableName, SqlParameter[] p)
                => mockValues[tableName]);

            string assemblyPath;

            assemblyPath = Directory.GetCurrentDirectory();
            Console.WriteLine("Working directory: " + assemblyPath);
            var context = new CommonExtractionContext()
            {
                CompanyName       = companyName,
                BaseWorkDirectory = assemblyPath,
                PluginsDirectory  = assemblyPath
            };

            var factory      = new DataExtractorFactory(context.PluginsDirectory);
            var nwmExtractor = factory.GetExtractor <NightWatchmanDataExtractor>();

            Assert.NotNull(nwmExtractor, "DataExtractorFactory failed to load NightWatchmanDataExtractor");


            var extractor = new DataExtractor(factory, mockQueryExecutor.Object);
            var zipFile   = extractor.BuildPackage(context);

            Assert.IsTrue(File.Exists(zipFile), "Failed to create Zip file");
            Assert.IsTrue((string.Compare(Path.GetFileNameWithoutExtension(zipFile), context.CompanyName) == 0), "Zip file is not correctly named");

            // Need to add more code to test zip file paths
        }
示例#4
0
        public static void Main(string[] args)
        {
            ExitCodes exitCode = ExitCodes.Success;

            try
            {
                CommandLine.DisplayBanner();
                var commandLine = new CommandLine(new Arguments(args));
                if (commandLine.Valid())
                {
                    // Create common configuration context
                    string connectionString = BuildConnectionString(commandLine);
                    Console.WriteLine("Using database connection string " + connectionString);
                    string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    var    context      = new CommonExtractionContext
                    {
                        CompanyName       = commandLine.CompanyName,
                        SccmConnection    = connectionString,
                        StartDate         = commandLine.StartDate,
                        EndtDate          = commandLine.EndDate,
                        BaseWorkDirectory = assemblyPath,
                        PluginsDirectory  = Path.Combine(assemblyPath, "Plugins")
                    };

                    // Create DataExtractor Plugin Factory
                    var factory = new DataExtractorFactory(context.PluginsDirectory);

                    int commandExecutionTimeout = SqlCommandExecutionTimeout();
                    var queryExecutor           = new SqlQueryExecutor(context.SccmConnection, commandExecutionTimeout);

                    // Create Data Extractor and build package
                    var    extractor = new DataExtractor(factory, queryExecutor);
                    string zipPath   = extractor.BuildPackage(context);

                    if (extractor.Succeded())
                    {
                        string uploadurl = ConfigurationManager.AppSettings["fileUploadUrl"].Replace(
                            "[SERVERNAME]", commandLine.UploadServerName);

                        FileUploader.UploadFile(uploadurl, zipPath);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayError(ex);
                exitCode = ExitCodes.Error;
            }

            Environment.Exit((int)exitCode);
        }
        public override void ExtractData(string outputDirectory, CommonExtractionContext context, Dictionary <string, object> pluginSettings)
        {
            GlobalContext.Properties[Name] = Name + " Plugin";

            var settings = new NightWatchmanSettings(Path.Combine(context.PluginsDirectory, "SavingsAnalysis.Plugin.NightWatchman.xml"));

            if (!RunValidationQueries(settings, context))
            {
                return;
            }

            SqlQueryResultSerializer resultSerializer = new SqlQueryResultSerializer(queryExecutor, context.SccmConnection, outputDirectory);

            foreach (var query in settings.Queries)
            {
                var queryParameters = new[]
                {
                    new SqlParameter("@startdate", SqlDbType.DateTime)
                    {
                        Value = context.StartDate
                    },
                    new SqlParameter("@enddate", SqlDbType.DateTime)
                    {
                        Value = context.EndtDate
                    }
                };

                resultSerializer.SerializeQueryResult(query.SelectionQuery, query.Name, queryParameters, (msg) => NotifyProgress(
                                                          new ExtractionEventArgs()
                {
                    Status  = ExtractionStatus.Succeeded,
                    Message = msg
                }));

                Log.Info("Successfully extracted data for " + query.Name);
            }

            if (settings.Queries.Count > 0)
            {
                NotifyProgress(
                    new ExtractionEventArgs()
                {
                    Status = ExtractionStatus.Succeeded, Message = "All query results collected successfully."
                });
            }
        }
示例#6
0
        public string BuildPackage(CommonExtractionContext context)
        {
            // Loop through all the plugins and extract their data
            string extractedData             = Path.Combine(context.BaseWorkDirectory, "SavingsAnalysisData");
            List <IDataExtractor> extractors = this.extractorFactory.GetDataExtractors();

            if (Directory.Exists(extractedData))
            {
                Directory.Delete(extractedData, true);
            }

            Directory.CreateDirectory(extractedData);

            foreach (IDataExtractor extractor in extractors)
            {
                try
                {
                    extractor.Progess      += this.OnNotifyProgress;
                    extractor.QueryExecutor = this.queryExecutor;
                    extractor.ExtractData(extractedData, context, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());

                    Log.Fatal(ex);

                    // throw;
                }
            }

            string zipPath = string.Empty;

            if (this.Succeded())
            {
                zipPath = Path.Combine(context.BaseWorkDirectory, string.Format("{0}.zip", context.CompanyName));
                ZipPackage.PackageFiles(extractedData, zipPath, string.Empty);
            }

            Directory.Delete(extractedData, true);
            return(zipPath);
        }
示例#7
0
        public override void ExtractData(
            string outputDirectory, CommonExtractionContext context, Dictionary <string, object> pluginSettings)
        {
            var collectorQueries     = new CollectorQueries();
            var collectionStatistics = new Dictionary <string, long>();
            var resultSerializer     = new SqlQueryResultSerializer(
                this.queryExecutor, context.SccmConnection, outputDirectory);

            foreach (QuerySettings query in collectorQueries.Queries)
            {
                long numberOfRows = resultSerializer.SerializeQueryResult(
                    query.SelectionQuery, query.Name, null, (msg) => this.Notify(ExtractionStatus.Info, msg));
                collectionStatistics.Add(query.Name, numberOfRows);
            }

            if (collectorQueries.Queries.Count > 0)
            {
                this.Notify(ExtractionStatus.Succeeded, "All query results collected successfully.");
                foreach (var stats in collectionStatistics)
                {
                    this.Notify(ExtractionStatus.Info, string.Format("{0} {1} rows collected", stats.Key, stats.Value));
                }
            }
        }