public static void Main(string[] args)
        {
            var options = new ArgumentOptions();

            Parser.Default.ParseArguments(args, options);

            var settings   = CostMonitoringSettings.CreateInstance();
            var dbContext  = new MonitoringDbContext();
            var auth       = new AzureAuthenticationHelperWrapper();
            var billing    = new AzureBillingApiClientHelper(settings);
            var httpClient = new HttpClientHelper();

            var service = new CostAggregationService(settings, dbContext, auth, billing, httpClient);

            Console.WriteLine("Azure Resources Usage Cost Aggregator");
            Console.WriteLine("-------------------------------------");
            Console.WriteLine();

            if (!options.RunEntirePeriod)
            {
                var result = ProcessAsync(service, options: options).Result;
            }
            else
            {
                var monthsBack = 0;
                var result     = 1;
                while (result > 0)
                {
                    result = ProcessAsync(service, monthsBack: monthsBack).Result;
                    monthsBack++;
                }
            }
        }
Ejemplo n.º 2
0
        private static void Run(ArgumentOptions opts)
        {
            using (var container = GetContainer(opts))
            {
                var calculationProducer = container.Resolve <CalculationProducer>();

                using (calculationProducer.Subscribe(container.Resolve <IObserver <StopsCalculationResult> >()))
                {
                    calculationProducer.Run();
                }
            }
            Console.WriteLine($"Press any key to Exit ...");
            Console.Read();
        }
        public void Constructor_WithEnoughArguments_MakesArgumentsAvailableThroughFields()
        {
            var expectedTransactionsLocation  = _fixture.Create <string>();
            var expectedCategoryRulesLocation = _fixture.Create <string>();
            var expectedWorkbookLocation      = _fixture.Create <string>();

            var result = new ArgumentOptions(new[] {
                expectedTransactionsLocation,
                expectedCategoryRulesLocation,
                expectedWorkbookLocation
            });

            result.TransactionsLocation.Value.Should().Be(expectedTransactionsLocation);
            result.CategoryRulesLocation.Value.Should().Be(expectedCategoryRulesLocation);
            result.WorkbookLocation.Value.Should().Be(expectedWorkbookLocation);
        }
        public static void Main(string[] args)
        {
            var options = new ArgumentOptions();

            Parser.Default.ParseArguments(args, options);

            var settings  = CostMonitoringSettings.CreateInstance();
            var dbContext = new MonitoringDbContext();

            var service = new CostReminderService(settings, dbContext);

            Console.WriteLine("Azure Resources Usage Reminder");
            Console.WriteLine("------------------------------");
            Console.WriteLine();

            var result = ProcessAsync(service, options).Result;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Gets the start date of the billing.
        /// </summary>
        /// <param name="options"><see cref="ArgumentOptions"/> instance.</param>
        /// <returns>Returns the start date based on options.</returns>
        public static DateTime GetStartDate(ArgumentOptions options)
        {
            if (options.RunEntirePeriod)
            {
                return(DateTime.MinValue.ToUniversalTime());
            }

            var dt = options.DateStart.IsNullOrWhiteSpace()
                         ? DateTime.Today.AddDays(options.Retro * (-1))
                         : DateTime.Parse(options.DateStart);

            DateTime.SpecifyKind(dt, DateTimeKind.Local);

            var dateStart = dt.ToUniversalTime();

            return(options.RunEntirePeriod ? DateTime.MinValue : dateStart);
        }
Ejemplo n.º 6
0
        public static ServerBase GetServer(ArgumentOptions options)
        {
            ServerBase server;

            if (options.PlayBack)
            {
                server = new PlayBackServer(options);
            }
            else if (options.RequestOnly)
            {
                server = new RequestOnlyServer(options);
            }
            else
            {
                server = new GameServer(options);
            }
            return(server);
        }
Ejemplo n.º 7
0
        private static void Main(string[] args)
        {
            var arguments = new ArgumentOptions();
            var result    = Parser.Default.ParseArguments <ArgumentOptions>(args);


            if (result.Tag != ParserResultType.Parsed)
            {
                var argumentErrors = ((NotParsed <ArgumentOptions>)result).Errors.Select(i => i.Tag.ToString());
                Console.WriteLine(string.Join(", ", argumentErrors));
            }

            else
            {
                Parser.Default.ParseArguments <ArgumentOptions>(args)
                .WithParsed(options => { arguments = options; });


                var builder = new ConfigurationBuilder();
                BuildConfig(builder);
                var host = Host.CreateDefaultBuilder()
                           .ConfigureServices((context, services) =>
                {
                    services.AddLogging(loggingBuilder =>
                    {
                        loggingBuilder.ClearProviders();
                        loggingBuilder.SetMinimumLevel(LogLevel.Trace);
                        loggingBuilder.AddNLog();
                    });

                    services.AddTransient <IFileService, FileService>();
                    services.AddTransient <IFilterByArgumentQueryHandler, FilterByArgumentQueryHandler>();
                    services.AddTransient <ILineParser, LineParser>();
                    services.AddTransient <IDelimitedFileReaderService, DelimetedFileReaderService>();
                    services.AddTransient <IDeserializeRowData <Procurement> >
                        (s => new DeserializeRowData <Procurement>());
                })
                           .UseNLog()
                           .Build();

                var svc = ActivatorUtilities.CreateInstance <ReaderService>(host.Services);
                svc.Run(arguments);
            }
        }
Ejemplo n.º 8
0
        static void RunOptionsAndReturnExitCode(ArgumentOptions opts)
        {
            LogOptions(opts);

            if (ImpossibleArgumentConfiguration(opts))
            {
                Console.WriteLine("Can't process both sitemap and input files");
                return;
            }

            if (ProcessingSitemap(opts))
            {
                ProcessSitemap(opts.SitemapUrl, opts.CsvName);
            }
            if (ProcessingFileList(opts))
            {
                ProcessFileList(opts.InputFiles, opts.CsvName);
            }
        }
Ejemplo n.º 9
0
        public void ProcessArgumentShortcut(FrameworkElement source, KeyEventArgs eventArgs)
        {
            if (eventArgs.Key == Key.Escape)
            {
                _temporaryResults = new ListWithCurrentSelection <AutoCompletionResult.CommandResult>();
                ((MainWindowView)Window.GetWindow(source)).Toggle();
                eventArgs.Handled = true;
                return;
            }

            if (eventArgs.Key == Key.Down || eventArgs.Key == Key.Up)
            {
                if (eventArgs.Key == Key.Down)
                {
                    Arguments = ArgumentOptions.Next();
                }
                else
                {
                    Arguments = ArgumentOptions.Previous();
                }

                eventArgs.Handled = true;
                return;
            }

            if (eventArgs.KeyboardDevice.Modifiers != ModifierKeys.Control)
            {
                return;
            }

            var str = new KeyConverter().ConvertToString(eventArgs.Key);
            int index;

            if (int.TryParse(str, out index))
            {
                index -= 1;
                if (index < ArgumentOptions.Count)
                {
                    Arguments         = ArgumentOptions.SetIndex(index);
                    eventArgs.Handled = true;
                }
            }
        }
Ejemplo n.º 10
0
        private static IContainer GetContainer(ArgumentOptions opts)
        {
            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", true, true)
                                    .Build();

            var builder = new ContainerBuilder();

            builder.RegisterInstance(config).As <IConfiguration>().SingleInstance();
            builder.RegisterType <LoggerFactory>().As <ILoggerFactory>().SingleInstance();
            builder.Register <ILogger>(c => c.Resolve <ILoggerFactory>().CreateLogger("Default"));
            builder.RegisterInstance(new RangeCalculationStrategyFactory()).As <IRangeCalculationStrategyFactory>().SingleInstance();
            builder.RegisterType <StopsCalculator>().As <IStopsCalculator>();
            builder.RegisterType <StarshipWebApiRepository>().As <IStarshipRepository>();
            builder.Register(c => new CalculationProducer(
                                 c.Resolve <IStarshipRepository>(), c.Resolve <IStopsCalculator>(), c.Resolve <ILogger>(), opts.TotalDistance));
            builder.Register(c => new CalculationConsoleConsumer(opts.Unknowns)).As <IObserver <StopsCalculationResult> >().SingleInstance();
            return(builder.Build());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Gets the end date of the billing.
        /// </summary>
        /// <param name="options"><see cref="ArgumentOptions"/> instance.</param>
        /// <returns>Returns the end date based on options.</returns>
        public static DateTime GetEndDate(ArgumentOptions options)
        {
            if (options.RunEntirePeriod)
            {
                return(DateTime.MaxValue.ToUniversalTime());
            }

            var dt = options.DateEnd.IsNullOrWhiteSpace()
                         ? (options.DateStart.IsNullOrWhiteSpace()
                                ? DateTime.Today.AddDays((options.Retro - options.Duration) * (-1))
                                : DateTime.Parse(options.DateStart).AddDays(options.Duration))
                         : DateTime.Parse(options.DateEnd);

            DateTime.SpecifyKind(dt, DateTimeKind.Local);

            var dateEnd = dt.ToUniversalTime();

            return(dateEnd);
        }
        private static async Task <int> ProcessAsync(ICostReminderService service, ArgumentOptions options)
        {
            var dateStart = BillingHelper.GetStartDate(options);
            var dateEnd   = BillingHelper.GetEndDate(options);

            Console.WriteLine(
                options.RunEntirePeriod
                                  ? $"Usage from the entire billing history:"
                                  : $"Usage from {dateStart.ToLocalTime():yyyy-MM-dd HH:mm:ss} to {dateEnd.AddDays(-1).ToLocalTime():yyyy-MM-dd HH:mm:ss}:");
            Console.WriteLine();

            var watch = Stopwatch.StartNew();

            var result = await service.ProcessAsync(dateStart, dateEnd, options.RunEntirePeriod, (decimal)options.Threshold).ConfigureAwait(false);

            watch.Stop();

            Console.WriteLine();
            Console.WriteLine($"Execution time: {watch.ElapsedMilliseconds} ms");

            return(result);
        }
Ejemplo n.º 13
0
 /// 
 ///<summary>
 ///	Initializes a new instance of the ArgumentAttribute class.
 ///</summary>
 ///<param name="argumentOptions">
 ///	The options for the argument.
 ///</param>
 public ArgumentAttribute( ArgumentOptions argumentOptions )
 {
     _argumentOptions = argumentOptions;
 }
Ejemplo n.º 14
0
 static bool ImpossibleArgumentConfiguration(ArgumentOptions opts)
 {
     return(ProcessingSitemap(opts) && ProcessingFileList(opts));
 }
        private static async Task <int> ProcessReminderAsync(ICostReminderService service, TraceWriter log, ArgumentOptions options)
        {
            var dateStart = BillingHelper.GetStartDate(options);
            var dateEnd   = BillingHelper.GetEndDate(options);

            log.Info(options.RunEntirePeriod
                         ? $"Usage from the entire billing history:"
                         : $"Usage from {dateStart.ToLocalTime():yyyy-MM-dd HH:mm:ss} to {dateEnd.AddDays(-1).ToLocalTime():yyyy-MM-dd HH:mm:ss}:");

            var result = await service.ProcessAsync(dateStart, dateEnd, options.RunEntirePeriod, (decimal)options.Threshold).ConfigureAwait(false);

            return(result);
        }
        private static async Task <int> ProcessAggregatorAsync(ICostAggregationService service, TraceWriter log, ArgumentOptions options = null, int?monthsBack = null)
        {
            var dateStart = options != null?BillingHelper.GetStartDate(options) : BillingHelper.GetStartDateOfMonth(monthsBack.Value);

            var dateEnd = options != null?BillingHelper.GetEndDate(options) : BillingHelper.GetEndDateOfMonth(monthsBack.Value);

            log.Info($"Usage from {dateStart.ToLocalTime():yyyy-MM-dd HH:mm:ss} to {dateEnd.ToLocalTime():yyyy-MM-dd HH:mm:ss}:");

            var result = await service.ProcessAsync(dateStart, dateEnd).ConfigureAwait(false);

            return(result);
        }
Ejemplo n.º 17
0
 static void LogOptions(ArgumentOptions opts)
 {
     Console.WriteLine($"csv:\t\t{opts.CsvName}\n" +
                       $"input files:\t{String.Join(",", opts.InputFiles)}\n" +
                       $"sitemap:\t{opts.SitemapUrl}\n\n");
 }
Ejemplo n.º 18
0
 public Argument(ArgumentOptions argumentOptions, string argumentName)
 {
     this.ArgumentOptions = argumentOptions;
     this.ArgumentName    = argumentName;
 }
        private static async Task <int> ProcessAsync(ICostAggregationService service, ArgumentOptions options = null, int?monthsBack = null)
        {
            var dateStart = options != null?BillingHelper.GetStartDate(options) : BillingHelper.GetStartDateOfMonth(monthsBack.Value);

            var dateEnd = options != null?BillingHelper.GetEndDate(options) : BillingHelper.GetEndDateOfMonth(monthsBack.Value);

            Console.WriteLine($"Usage from {dateStart.ToLocalTime():yyyy-MM-dd HH:mm:ss} to {dateEnd.ToLocalTime():yyyy-MM-dd HH:mm:ss}:");
            Console.WriteLine();

            var watch = Stopwatch.StartNew();

            var result = await service.ProcessAsync(dateStart, dateEnd).ConfigureAwait(false);

            watch.Stop();

            Console.WriteLine();
            Console.WriteLine($"Execution time: {watch.ElapsedMilliseconds} ms");

            return(result);
        }
Ejemplo n.º 20
0
 static bool ProcessingFileList(ArgumentOptions opts)
 {
     return(opts.InputFiles.Count() > 0);
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Entry point of the command-line utility.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
        public static async Task Main(string[] args)
        {
            using (var parser = new Parser(with =>
            {
                with.CaseSensitive = false;
                with.CaseInsensitiveEnumValues = true;
                with.EnableDashDash = true;
                with.HelpWriter = Console.Out;
            }))
            {
                ArgumentOptions options = null;

                parser.ParseArguments <ArgumentOptions>(args)
                .WithParsed(opts => options = opts)
                .WithNotParsed(errors => Environment.Exit(ErrorBadArguments));

                Uri            baseUri     = new Uri(options.ServiceUrl.Trim());
                VssCredentials credentials = new VssBasicCredential(string.Empty, options.Token);

                switch (options.AuthType)
                {
                case AuthType.Pat:
                    credentials = new VssBasicCredential(string.Empty, options.Token.Trim());
                    break;

                case AuthType.Basic:
                    credentials = new VssBasicCredential(options.Username.Trim(), options.Password.Trim());
                    break;

                case AuthType.Ntlm:
                    credentials = new VssCredentials();
                    break;

                case AuthType.Interactive:
                    credentials = new VssClientCredentials(
                        new WindowsCredential(false),
                        new VssFederatedCredential(false),
                        CredentialPromptType.PromptIfNeeded);
                    break;

                default:
                    break;
                }

                using (var connection = new VssConnection(baseUri, credentials))
                {
                    try
                    {
                        await connection.ConnectAsync();

                        var container = Container.Build(connection);
                        var factory   = container.Resolve <IModelFactory>();

                        var organization = await factory.Create(options.ConfigurationFilePath).ConfigureAwait(false);

                        // TODO: Expand patterns so we can use expressions, like [$teampProject]\Project Administrators
                        organization.Expand();

                        var deviations = await organization.CollectDeviations().ConfigureAwait(false);

                        // TODO: Decide what to do with the deviations (print to screen/file) or remediate them.
                        foreach (var deviation in deviations)
                        {
                            Console.WriteLine(deviation.ToString());
                        }
                    }
                    catch (Exception)
                    {
                        // TODO: handle Exception
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 22
0
        private static Block AddToCommandBlock(this Block block, string regexComparer, string description, string sectionName, string sampleInput, ArgumentOptions argumentOptions, string preSampleInputSeparator = " ")
        {
            const string separatorPattern = @"\W*";

            block.SampleInput += preSampleInputSeparator + sampleInput;
            block.RegexString += regexComparer + separatorPattern;
            block.Arguments.Add(new Argument(argumentOptions, sectionName));
            block.Description += description + " ";
            return(block);
        }
Ejemplo n.º 23
0
 static bool ProcessingSitemap(ArgumentOptions opts)
 {
     return(!String.IsNullOrEmpty(opts.SitemapUrl));
 }