Exemple #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // 'services' is the IOC container
            services.AddCors(options => options
                             .AddPolicy(name: "GoodBooksPolicy",
                                        builder => builder
                                        .WithOrigins("http://localhost:8080")
                                        .AllowAnyMethod()
                                        .AllowAnyHeader()
                                        .AllowCredentials())
                             );

            services.AddControllers();

            // set up dotenv to grab the env vars
            DotEnv.Config(true, "../../.env");
            var envReader        = new EnvReader();
            var connectionString = envReader.GetStringValue("DEV_CONNECTION_STRING");

            // set up Postgres
            services.AddDbContext <GoodBooksDbContext>(options =>
            {
                options.EnableDetailedErrors();
                options.UseNpgsql(connectionString);
            });

            // register dependencies in the IOC container. When I ask for IBookService, please use the BookService implementation
            // AddTransient means we want a simple, short-lived instance of a BookService when its behaviour is requested
            services.AddTransient <IBookService, BookService>();
            services.AddTransient <IBookDataReader, BookDataReader>();
            services.AddTransient <IBookDataWriter, BookDataWriter>();
        }
Exemple #2
0
        public async void TestGet()
        {
            DotEnv.Config(true);
            var rc = new RestClient(
                Environment.GetEnvironmentVariable("RINGCENTRAL_CLIENT_ID"),
                Environment.GetEnvironmentVariable("RINGCENTRAL_CLIENT_SECRET"),
                Environment.GetEnvironmentVariable("RINGCENTRAL_SERVER_URL")
                );
            await rc.Authorize(
                Environment.GetEnvironmentVariable("RINGCENTRAL_USERNAME"),
                Environment.GetEnvironmentVariable("RINGCENTRAL_EXTENSION"),
                Environment.GetEnvironmentVariable("RINGCENTRAL_PASSWORD")
                );

            var engageVoice      = new EngageVoice(Environment.GetEnvironmentVariable("ENGAGE_VOICE_SERVER_URL"));
            var engageVoiceToken = await engageVoice.Authorize(rc.token.access_token);

            Assert.NotNull(engageVoiceToken);
            Assert.NotNull(engageVoiceToken.accessToken);

            var httpResponseMessage = await engageVoice.Get("/voice/api/v1/admin/accounts");

            var s = await httpResponseMessage.Content.ReadAsStringAsync();

            Assert.NotNull(s);
            Assert.NotEmpty(s);

            await rc.Revoke();
        }
Exemple #3
0
        public BaseRepository(IMongoDbSettings settings, string collection)
        {
            var client   = new MongoClient(DotEnv.Read()[Text.MongoDbUri]);
            var database = client.GetDatabase(DotEnv.Read()[Text.MongoDbDb]);

            _documents = database.GetCollection <T>(collection);
        }
Exemple #4
0
        public UserService(IMongoDbSettings settings)
        {
            var client   = new MongoClient(DotEnv.Read()["MONGODB_URI"]);
            var database = client.GetDatabase(DotEnv.Read()["MONGODB_DB"]);

            _users = database.GetCollection <User>("users"); //settings.CollectionName is not users
        }
Exemple #5
0
        public virtual void Configuration(IAppBuilder app)
        {
            DotEnv.Load();

            var corsPolicyTask = Task.FromResult(new CorsPolicy {
                AllowAnyHeader  = true,
                AllowAnyMethod  = true,
                AllowAnyOrigin  = true,
                PreflightMaxAge = 60 * 60 * 1000 // 1 hour, though Chrome would limit to 10 mins I believe
            });
            var corsOptions = new CorsOptions {
                PolicyProvider = new CorsPolicyProvider {
                    PolicyResolver = r => corsPolicyTask
                }
            };

            app.UseCors(corsOptions);

            var container          = CreateContainer();
            var mirrorSharpOptions = CreateMirrorSharpOptions(container);

            app.UseMirrorSharp(mirrorSharpOptions);

            app.Map("/status", a => a.Use((c, next) => {
                c.Response.ContentType = "text/plain";
                return(c.Response.WriteAsync("OK"));
            }));

            var monitor = container.Resolve <IMonitor>();

            monitor.Event("Application Startup", null);
            HostingEnvironment.RegisterObject(new ShutdownMonitor(monitor));

            app.UseAutofacLifetimeScopeInjector(container);
        }
        static void Main()
        {
            DotEnv.Config();
            Console.WriteLine(Env.Var.ESEndpoint);

            Example().GetAwaiter().GetResult();
        }
Exemple #7
0
        private static async Task MainAsync()
        {
            DotEnv.AutoConfig();
            using (var services = ConfigureServices())
            {
                var envCheckerService      = services.GetRequiredService <EnvCheckerService>();
                var checkEnvironmentValues = envCheckerService.CheckEnvironmentValues();
                if (checkEnvironmentValues == false)
                {
                    Console.WriteLine("Error: CheckEnvironmentValues ");
                    return;
                }

                var valorantApiService = services.GetRequiredService <ValorantApiService>();

                await using (var db = new DatabaseDbContext())
                {
                    await db.Database.MigrateAsync();
                }

                var discord = services.GetRequiredService <BotService>();
                await discord.StartAsync();


                services.GetRequiredService <PlayerRankChecker>().Start();


                await Task.Delay(-1);
            }
        }
        static void Main(string[] args)
        {
            DotEnv.Config(false);

            var importDir  = Environment.GetEnvironmentVariable("IMPORT_DIR");
            var importGlob = Environment.GetEnvironmentVariable("IMPORT_GLOB");

            var hostName     = Environment.GetEnvironmentVariable("DATABASE_HOST");
            var databaseName = Environment.GetEnvironmentVariable("DATABASE_NAME");
            var userName     = Environment.GetEnvironmentVariable("DATABASE_USERNAME");
            var password     = Environment.GetEnvironmentVariable("DATABASE_PASSWORD");
            var port         = Environment.GetEnvironmentVariable("DATABASE_PORT");

            _connectionString = $"Server={hostName},{port};Database={databaseName};User Id={userName};Password={password}";

            var path    = Path.Combine(Environment.CurrentDirectory, importDir);
            var watcher = new FileSystemWatcher(path, importGlob);

            watcher.Changed            += HandleFileChange;
            watcher.EnableRaisingEvents = true;

            Console.WriteLine($"Watching directory {path} for '{importGlob}'...");
            Console.CancelKeyPress += OnExit;
            _closing.WaitOne();
        }
Exemple #9
0
        public static void Main(string[] args)
        {
#if DEBUG
            DotEnv.Config(); // injectar el .env globalmente
#endif
            CreateHostBuilder(args).Build().Run();
        }
Exemple #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (File.Exists("/var/data/Hexastore.env"))
            {
                DotEnv.Config(false, "/var/data/Hexastore.env");
            }
            else if (File.Exists("Hexastore.env"))
            {
                DotEnv.Config(false, "Hexastore.env");
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors("AllowAnyOrigin");

            app.UseMiddleware <PerfHeaderMiddleware>();

            // app.UseHttpsRedirection();
            // app.UseAuthorization();
            app.UseRouting();

            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
        }
Exemple #11
0
 public UserStorageQuotaReport(ITestOutputHelper testOutputHelper)
 {
     _testOutputHelper = testOutputHelper;
     DotEnv.Config();
     _api = new Api(Environment.GetEnvironmentVariable("TEST_TOKEN"),
                    "https://uview.instructure.com/api/v1/");
 }
Exemple #12
0
        public void InitEnvFile()
        {
            var testRootPath = AppDomain.CurrentDomain.BaseDirectory;
            var envPath      = testRootPath.Substring(0, testRootPath.IndexOf("bin"));

            DotEnv.Config(true, envPath + ".env");
        }
Exemple #13
0
    public async Task Start()
    {
        DotEnv.Config();
        if (!File.Exists("config.toml"))
        {
            Console.WriteLine("config.toml doesnt exist, please create it.");
            return;
        }

        Client   = new DiscordSocketClient();
        Commands = new CommandService();

        ServiceCollection ServiceCollection = new ServiceCollection();

        ServiceCollection.AddSingleton(Client);
        ServiceCollection.AddSingleton(Commands);
        ServiceCollection.AddSingleton(this);
        ServiceCollection.AddSingleton(DatabaseService.Instance);
        ServiceCollection.AddSingleton(ConfigService.Instance);
        Services = ServiceCollection.BuildServiceProvider();

        Client.MessageReceived += HandleCommandAsync;
        await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), Services);

        await Client.LoginAsync(
            Discord.TokenType.Bot,
            Environment.GetEnvironmentVariable("TOKEN"));

        await Client.StartAsync();

        await Client.SetStatusAsync(Discord.UserStatus.Online);

        await Task.Delay(-1);
    }
Exemple #14
0
        public void ShouldThrowExceptionWhenFileNameEmptyOrNull()
        {
            Action action = () => DotEnv.Config(true, null);

            action.ShouldThrowExactly <ArgumentException>()
            .WithMessage($"The file path cannot be null, empty or whitespace.{Environment.NewLine}Parameter name: filePath");
        }
Exemple #15
0
    public static async Task <int> RunSolver(string[] args, IServiceCollection services)
    {
        DotEnv.Fluent()
        .WithoutExceptions()
        .WithEnvFiles()
        .WithTrimValues()
        .WithDefaultEncoding()
        .WithOverwriteExistingVars()
        .WithProbeForEnv(6)
        .Load();

        SetWorkingDirectory();

        ConfigureServices(services);
        ServiceProvider serviceProvider = BuildServiceProvider(services);
        var             solver          = serviceProvider.GetRequiredService <Solver>();

        var all = false;

        switch (args.Length)
        {
        // dotnet run
        case 0:
            await solver.SolveLast().ConfigureAwait(false);

            break;

        // dotnet run all | dotnet run --all
        case 1 when args[0].Contains("all", StringComparison.CurrentCultureIgnoreCase):
        static void Main(string[] args)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory());

            path = Path.GetFullPath(path) + "/.env";
            DotEnv.Config(true, path);
            DotEnv.Config(true, path, Encoding.Unicode, false);
            EnvReader envReader = new EnvReader();

            BlockIo blockIo = new BlockIo(envReader.GetStringValue("API_KEY"), envReader.GetStringValue("PIN"));

            var balance = blockIo.GetBalance().Data.available_balance;

            Console.WriteLine("Balance: " + balance);

            while (true)
            {
                var    res         = blockIo.Withdraw(new { to_address = envReader.GetStringValue("TO_ADDRESS"), amount = balance.ToString() });
                double maxWithdraw = res.Data.max_withdrawal_available;

                Console.WriteLine("Max Withdraw Available: " + maxWithdraw.ToString());

                if (maxWithdraw == 0)
                {
                    break;
                }
                blockIo.Withdraw(new { to_address = envReader.GetStringValue("TO_ADDRESS"), amount = maxWithdraw.ToString() });
            }

            balance = blockIo.GetBalance().Data.available_balance;

            Console.WriteLine("Final Balance: " + balance);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Parse env vars from local .env file.
            DotEnv.Config();

            //Console.WriteLine(System.Environment.GetEnvironmentVariable("TEST_VAR"));

            string env = System.Environment.GetEnvironmentVariable("DEV_ENVIRONMENT");

            // Use Azure DB if env is production. Use in-memory db if env is dev or not set.

            if (env != null && env.Equals("PROD"))
            {
                // Azure SQL Database
                string connectionString = @Environment.GetEnvironmentVariable("DB_DONNECTION_STRING");
                Console.WriteLine(connectionString);
                services.AddDbContext <MessageContext>(opt => opt.UseSqlServer(connectionString));
            }
            else
            {
                // In Memory DB
                services.AddDbContext <MessageContext>(opt => opt.UseInMemoryDatabase("Announcments"));
            }

            //services.AddDbContext<MessageContext>(opt => opt.UseInMemoryDatabase("Announcments"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Exemple #18
0
        public void VerifyText(string CustomerPhoneNumber)
        {
            DotEnv.Config();
            string accountSID   = System.Environment.GetEnvironmentVariable("TWILIO_SID");
            string authToken    = System.Environment.GetEnvironmentVariable("TWILIO_AUTHTOKEN");
            string TwilioNumber = System.Environment.GetEnvironmentVariable("TWILIO_PHONE");

            try
            {
                TwilioClient.Init(accountSID, authToken);


                var message = MessageResource.Create(
                    body: "Would you like to recieve SMS notifications? Reply Yes or No, Reply STOP at any time "
                    + "to disable text notifications",
                    from: new Twilio.Types.PhoneNumber(TwilioNumber),
                    to: new Twilio.Types.PhoneNumber(CustomerPhoneNumber)
                    );
                //Use Account Sid for testing to make sure the message was sent
                Console.WriteLine(message.Sid);
                Console.WriteLine(message.AccountSid);
            }
            catch (Exception exp)
            {
                Console.Error.WriteLine("Error:" + exp.Message + Environment.NewLine + " " + exp.StackTrace);
            }
        }
        /// <summary>
        /// Main
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        static async Task Main(string[] args)
        {
            // Create service collection
            var serviceCollection = new ServiceCollection();

            DotEnv.Config(false);
            ConfigureServices(serviceCollection);
            // Create service provider
            _serviceProvider = serviceCollection.BuildServiceProvider();
            var config = _serviceProvider.GetService <IConfigurationRoot>();
            var logger = _serviceProvider.GetService <ILogger <StorageBackupWorker> >();

            _timer          = new System.Timers.Timer(int.Parse(config.GetSection("AppSettings")["TimerElapsedInMS"]));
            _timer.Elapsed += OnTimerElapsed;
            _timer.Start();
            logger.LogInformation("Listener started!!!");
            await Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    logger.LogInformation("looping @ {0}", DateTime.Now.ToString());
                    Thread.Sleep(10000);
                }
            });

            Console.CancelKeyPress += new ConsoleCancelEventHandler(OnExit);
            _closing.WaitOne();
        }
Exemple #20
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            DotEnv.Load();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BlazorServer v1"));
            }

            app.UseCors("CorsPolicy");

            app.UseRouting();

            app.UseAuthorization();

            app.UseWhen(
                context => !context.Request.Path.StartsWithSegments("/auth"),
                appBuilder =>
            {
                appBuilder.UseMiddleware <JwtMiddleware>();
            }
                );

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemple #21
0
 public MailService(IOptions <MailSettings> mailSettings)
 {
     _mailSettings          = mailSettings.Value;
     _mailSettings.Mail     = DotEnv.Read()["MAIL"];
     _mailSettings.Password = DotEnv.Read()["MAIL_PASSWORD"];
     //TODO: check if we could load .env and not use Read anymore
 }
Exemple #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var envReader = new EnvReader();

            DotEnv.Config(true, "mySecrets");
            var channel  = envReader.GetStringValue("CHANNEL");
            var token    = envReader.GetStringValue("BOT_PASSWORD");
            var endpoint = envReader.GetStringValue("API_ENDPOINT");

#if DEBUG
            using (var context = new mashDbContext())
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }
#endif

            BotSettings settings = new(endpoint);
            var         bot      = new Bot(channel, token, settings);

            while (true)
            {
                bot.settings.RefreshSettings();
                System.Threading.Thread.Sleep(1000);
            }

            Console.WriteLine("We made it here without error!");
        }
        static void Main(string[] args)
        {
            DotEnv.Config();
            Console.WriteLine("Hello World!");

            var credentials       = new BasicAWSCredentials(Env.Var.AwsAccessKey, Env.Var.AwsSecretAccessKey);
            var region            = RegionEndpoint.GetBySystemName(Env.Var.AwsRegion);
            var s3                = new AmazonS3Client(credentials, region);
            var sqs               = new AmazonSQSClient(credentials, region);
            var sqsExtendedClient = new AmazonSQSExtendedClient(sqs,
                                                                new ExtendedClientConfiguration().WithLargePayloadSupportEnabled(s3, Env.Var.SqsPayloadBucket)
                                                                );

            string command = args.FirstOrDefault();

            if (command == "upsert-simple")
            {
                UpsertSimpleExample(sqsExtendedClient).GetAwaiter().GetResult();
            }
            else if (command == "delete-simple")
            {
                DeleteExample(sqsExtendedClient).GetAwaiter().GetResult();
            }
            else if (command == "upsert-pdf")
            {
                UpsertPdfExample(sqsExtendedClient).GetAwaiter().GetResult();
            }
            else
            {
                throw new Exception("Please specify command (see code / readme).");
            }
        }
Exemple #24
0
        static void Main(string[] args)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory());

            path = Path.GetFullPath(path) + "/.env";
            DotEnv.Config(true, path);
            DotEnv.Config(true, path, Encoding.Unicode, false);
            EnvReader envReader = new EnvReader();

            BlockIo blockIo = new BlockIo(envReader.GetStringValue("API_KEY"));

            var res = blockIo.SweepFromAddress(new
            {
                to_address   = envReader.GetStringValue("TO_ADDRESS"),
                private_key  = envReader.GetStringValue("PRIVATE_KEY_FROM_ADDRESS"),
                from_address = envReader.GetStringValue("FROM_ADDRESS")
            });

            if (res.Status == "success")
            {
                Console.WriteLine("Sweep Res: " + res.Data);
                return;
            }

            Console.WriteLine("Error occurred: " + res.Data);
        }
        public static void Main(string[] args)
        {
            DotEnv.Config(false);
            var host = CreateHostBuilder(args).Build();

            // migrate the database.  Best practice = in Main, using service scope
            // using (var scope = host.Services.CreateScope())
            // {
            //     try
            //     {
            //         var context = scope.ServiceProvider.GetService<CourseLibraryContext>();
            //         // for demo purposes, delete the database & migrate on startup so
            //         // we can start with a clean slate
            //         context.Database.EnsureDeleted();
            //         context.Database.Migrate();
            //     }
            //     catch (Exception ex)
            //     {
            //         var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
            //         logger.LogError(ex, "An error occurred while migrating the database.");
            //     }
            // }

            // run the web app
            host.Run();
        }
        public void ThrowsExceptionWithNonExistentEnvFileWhenThrowErrorIsTrue()
        {
            Action action = () => DotEnv.Config(true, "hello");

            action.ShouldThrowExactly <FileNotFoundException>()
            .WithMessage("An enviroment file with path \"hello\" does not exist.");
        }
Exemple #27
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            // initialise env vars for local development
            DotEnv.Config(false); // (do not throw if .env file doen't exist)
        }
 public TestStartupBase()
 {
     if (File.Exists(".env"))
     {
         DotEnv.Config();
     }
 }
Exemple #29
0
        public Env(string filePath = ".env")
        {
            DotEnv.Config(filePath: filePath);

            this.HTTP_ROOT_URL          = GetVariable("HTTP_ROOT_URL");
            this.MAX_FILE_SIZE_IN_BYTES = long.Parse(GetVariable("MAX_FILE_SIZE_IN_BYTES"));

            this.FTP_HOST            = GetVariable("FTP_HOST");
            this.FTP_USERNAME        = GetVariable("FTP_USERNAME");
            this.FTP_PASSWORD        = GetVariable("FTP_PASSWORD");
            this.FTP_DATA_FOLDER     = GetVariable("FTP_DATA_FOLDER");
            this.FTP_WAF_FOLDER      = GetVariable("FTP_WAF_FOLDER");
            this.FTP_ROLLBACK_FOLDER = GetVariable("FTP_ROLLBACK_FOLDER");

            this.HUB_AWS_REGION           = GetVariable("HUB_AWS_REGION");
            this.HUB_AWS_ACCESSKEY        = GetVariable("HUB_AWS_ACCESSKEY");
            this.HUB_AWS_SECRETACCESSKEY  = GetVariable("HUB_AWS_SECRETACCESSKEY");
            this.HUB_ASSETS_BASE_URL      = GetVariable("HUB_ASSETS_BASE_URL");
            this.HUB_BASE_URL             = GetVariable("HUB_BASE_URL");
            this.HUB_DYNAMO_TABLE         = GetVariable("HUB_DYNAMO_TABLE");
            this.HUB_LAMBDA_FUNCTION      = GetVariable("HUB_LAMBDA_FUNCTION");
            this.HUB_LARGE_MESSAGE_BUCKET = GetVariable("HUB_LARGE_MESSAGE_BUCKET");

            this.SQS_ENDPOINT       = GetVariable("SQS_ENDPOINT");
            this.SQS_PAYLOAD_BUCKET = GetVariable("SQS_PAYLOAD_BUCKET");
            this.ES_INDEX           = GetVariable("ES_INDEX");
            this.ES_SITE            = GetVariable("ES_SITE");

            this.SMTP_NOTIFICATIONS_ON = bool.Parse(GetVariable("SMTP_NOTIFICATIONS_ON"));
            this.SMTP_HOST             = GetVariable("SMTP_HOST");
            this.SMTP_FROM             = GetVariable("SMTP_FROM");
            this.SMTP_TO = GetVariable("SMTP_TO");
        }
Exemple #30
0
        public static void Main(string[] args)
        {
            DotEnv.Config();
            var manager = new CommunicationManager();

            manager.NewServerNeeded += ManagerOnNewServerNeeded;
        }