Exemple #1
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation($"{Directory.GetCurrentDirectory()}");
            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 (!stoppingToken.IsCancellationRequested)
            {
                //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                bot.settings.RefreshSettings(_logger);
                await Task.Delay(1000, stoppingToken);
            }
        }
        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 Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            // initialise env vars for local development
            DotEnv.Config(false); // (do not throw if .env file doen't exist)
        }
        // 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);
        }
        /// <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 #6
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!");
        }
        public void ThrowsExceptionWithNonExistentEnvFileWhenThrowErrorIsTrue()
        {
            Action action = () => DotEnv.Config(true, "hello");

            action.ShouldThrowExactly <FileNotFoundException>()
            .WithMessage("An enviroment file with path \"hello\" does not exist.");
        }
Exemple #8
0
        public static void Main(string[] args)
        {
            DotEnv.Config();
            var manager = new CommunicationManager();

            manager.NewServerNeeded += ManagerOnNewServerNeeded;
        }
Exemple #9
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>();
        }
 public MasterCourseSectionsReport()
 {
     DotEnv.Config();
     _api = new Api(Environment.GetEnvironmentVariable("TEST_TOKEN")
                    ?? throw new ArgumentException(".env should contain TEST_TOKEN"),
                    "https://uview.instructure.com/api/v1/");
 }
Exemple #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options
                             .AddPolicy(name: "MotivationPolicy",
                                        builder => builder
                                        .WithOrigins("http://localhost:5500")
                                        .AllowAnyMethod()
                                        .AllowAnyHeader()
                                        .AllowCredentials())
                             );

            services.AddControllers();

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

            // use MSSQL
            services.AddDbContext <MotivationDbContext>(options =>
            {
                options.EnableDetailedErrors();
                options.UseSqlServer(connectionString);
            }
                                                        );

            // register dependencies in the IOC container
            services.AddTransient <IMessageService, MessageService>();
            services.AddTransient <IMessageReader, MessageReader>();
        }
Exemple #12
0
        public ApiFixture()
        {
            DotEnv.Config();

            Api = new Api(Environment.GetEnvironmentVariable("TEST_TOKEN"),
                          "https://uview.instructure.com/api/v1/");
        }
 public ExportLoggedInUsers(ITestOutputHelper testOutputHelper)
 {
     _testOutputHelper = testOutputHelper;
     DotEnv.Config();
     _api = new Api(Environment.GetEnvironmentVariable("TEST_TOKEN"),
                    "https://uview.instructure.com/api/v1/");
 }
        public PrepareSession(NancyContext context)
        {
            string path = @"E:\esign-demo2\.env";

            DotEnv.Config(true, path);

            Post("/demoform2", async _ =>
            {
                /*if (!await validateCaptcha(this.Request.Headers.Authorization))
                 * {
                 *  return new Response
                 *  {
                 *      StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "Unauthorized"
                 *  };
                 * }*/

                return(this.Request.Files.

                       var token = await RetrieveAccessToken());

                String result = "";
                if (this.Request.Form.type == "send")
                {
                    result = await RetrieveSendingSession(token, this.Request, this.Response);
                }

                return(result);
            });
        }
        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);
        }
Exemple #16
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 #17
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);
            }
        }
Exemple #18
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 #19
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);
        }
Exemple #20
0
        public void InitEnvFile()
        {
            var testRootPath = AppDomain.CurrentDomain.BaseDirectory;
            var envPath      = testRootPath.Substring(0, testRootPath.IndexOf("bin"));

            DotEnv.Config(true, envPath + ".env");
        }
 public TestStartupBase()
 {
     if (File.Exists(".env"))
     {
         DotEnv.Config();
     }
 }
Exemple #22
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();
            });
        }
        static void Main()
        {
            DotEnv.Config();
            Console.WriteLine(Env.Var.ESEndpoint);

            Example().GetAwaiter().GetResult();
        }
Exemple #24
0
 public UserStorageQuotaReport(ITestOutputHelper testOutputHelper)
 {
     _testOutputHelper = testOutputHelper;
     DotEnv.Config();
     _api = new Api(Environment.GetEnvironmentVariable("TEST_TOKEN"),
                    "https://uview.instructure.com/api/v1/");
 }
        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).");
            }
        }
        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 #27
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 #28
0
        public static void Main(string[] args)
        {
#if DEBUG
            DotEnv.Config(); // injectar el .env globalmente
#endif
            CreateHostBuilder(args).Build().Run();
        }
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 void ShouldReturnValidValuesWhenValuesAreQuoted()
        {
            DotEnv.Config(true, QuotationsEnvFileName, Encoding.UTF8);

            Environment.GetEnvironmentVariable("SINGLE").Should().Be("single");
            Environment.GetEnvironmentVariable("DOUBLE").Should().Be("double");
        }