Beispiel #1
0
        public static int Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug() //TODO: Should be configurable!
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.File("Logs/logs.txt")
                         .CreateLogger();

            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("hosting.json", optional: true)
                         .Build();

            try
            {
                Log.Information("Starting web host.");
                BuildWebHostInternal(args, config).Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly!");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        /// <summary>
        /// Gest AppSetting value.
        /// </summary>
        /// <typeparam name="T">Return type.</typeparam>
        /// <param name="key">AppSetting key.</param>
        /// <param name="defaultValue">Default value if AppSetting key couldnt find.</param>
        /// <returns></returns>
        public static T GetAppSetting <T>(string key, T defaultValue)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();
            if (string.IsNullOrEmpty(key))
            {
                return(defaultValue);
            }
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            var configuration = builder.Build();

            var value = configuration.GetSection(key).Value;

            try
            {
                if (value == null)
                {
                    return(default(T));
                }
                var theType = typeof(T);
                if (theType.IsEnum)
                {
                    return((T)Enum.Parse(theType, value, true));
                }

                return((T)Convert.ChangeType(value, theType));
            }
            catch (Exception)
            {
                // ignored
            }

            return(defaultValue);
        }
Beispiel #3
0
        public static int Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.File("Logs/logs.txt")
                         .CreateLogger();

            try
            {
                Log.Information("Starting web host.");
                BuildWebHostInternal(args).Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly!");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(System.IO.Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .UseSerilog()
                       .UseStartup <Startup>()
                       .Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService <WideWorldImportersContext>();
                    context.Database.EnsureCreated();
                }
                catch (Exception ex)
                {
                    Log.Fatal(ex, "An error occurred creating the DB.");
                }
            }

            host.Run();
        }
Beispiel #5
0
        public static void Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();
            string caminhoLog = Path.Combine(Directory.GetCurrentDirectory(), "Logs.txt");

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
                         .Enrich.FromLogContext()
                         .WriteTo.File(caminhoLog)
                         .CreateLogger();

            try
            {
                Log.Information("--- SERVIDOR INICIANDO ---");
                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "--- SERVIDOR TERMINOU INESPERADAMENTE ---");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
 public static void Main(string[] args)
 {
     CurrentDirectoryHelpers.SetCurrentDirectory();
     Log.Logger = new LoggerConfiguration()
                  .MinimumLevel.Information()                                                                      // Set the minimun log level
                  .WriteTo.File("Logs\\log-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) // this is for logging into file system
                  .CreateLogger();
Beispiel #7
0
 public static void Main(string[] args)
 {
     Task.Run(() => {
         CurrentDirectoryHelpers.SetCurrentDirectory();
     });
     BuildWebHost(args).Run();
 }
Beispiel #8
0
        public static void Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            var host = CreateWebHostBuilder(args).Build();

            #if !(DEBUG)
            Thread.Sleep(10000); // wait for start of postgres container (cannot understand how to add wait for it script)
            #endif

            using (var scope = host.Services.CreateScope())
            {
                try
                {
                    var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                    context.Database.Migrate();
                    CoursesInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while migrating or initializing the database.");
                }
            }

            host.Run();
        }
Beispiel #9
0
        public static int Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            Log.Logger = new LoggerConfiguration()
#if DEBUG
                         .MinimumLevel.Debug()
#else
                         .MinimumLevel.Information()
#endif
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.Async(c => c.File("Logs/logs.txt"))
                         .CreateLogger();

            try
            {
                Log.Information("Starting AbpPermissionCacheTest.IdentityServer.");
                BuildWebHostInternal(args).Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "AbpPermissionCacheTest.IdentityServer terminated unexpectedly!");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        public static void Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .Enrich.WithProperty("App Name", "SecretSanta.Api")
                         .CreateLogger();
            try
            {
                var host = CreateWebHostBuilder(args).Build();

                using (var serviceScope = host.Services.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    using (var context = serviceScope.ServiceProvider.GetService <ApplicationDbContext>())
                    {
                        context.Database.Migrate();
                    }
                }

                host.Run();
            }
            catch (Exception e)
            {
                Log.Fatal(e, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        public static void Main(string[] args)
        {
            //Importante

            CurrentDirectoryHelpers.SetCurrentDirectory();

            CreateWebHostBuilder(args).Build().Run();
        }
    public static void Main(string[] args)
    {
        CurrentDirectoryHelpers.SetCurrentDirectory();

        Log.Logger = new LoggerConfiguration()
                     .Enrich.FromLogContext()
                     .ReadFrom.Configuration(Configuration)
                     .WriteTo.Console()
                     .CreateLogger();
Beispiel #13
0
        public static void Main(string[] args)
        {
            /*
             *  https://github.com/aspnet/AspNetCore/issues/4206#issuecomment-445612167
             *  CurrentDirectoryHelpers exists in: \framework\src\Volo.Abp.AspNetCore.Mvc\Microsoft\AspNetCore\InProcess\CurrentDirectoryHelpers.cs
             *  Will remove CurrentDirectoryHelpers.cs when upgrade to ASP.NET Core 3.0.
             */
            CurrentDirectoryHelpers.SetCurrentDirectory();

            BuildWebHostInternal(args).Run();
        }
Beispiel #14
0
        public static void Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            var host = CreateWebHostBuilder(args).Build();

            using (var serviceScope = host.Services.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                using (var context = serviceScope.ServiceProvider.GetService <ApplicationDbContext>())
                {
                    context.Database.EnsureCreated();
                }
            }

            host.Run();
        }
Beispiel #15
0
 public static int Main(string[] args)
 {
     CurrentDirectoryHelpers.SetCurrentDirectory();
     try
     {
         Log.Information("Starting web host.");
         BuildWebHostInternal(args).Run();
         return(0);
     }
     catch (Exception ex)
     {
         Log.Fatal(ex, "Host terminated unexpectedly!");
         return(1);
     }
     finally
     {
         Log.CloseAndFlush();
     }
 }
Beispiel #16
0
        public static int Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            //TODO: Temporary: it's not good to read appsettings.json here just to configure logging
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json")
                                .AddEnvironmentVariables()
                                .Build();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.WithProperty("Application", "BackendAdminApp")
                         .Enrich.FromLogContext()
                         .WriteTo.File("Logs/logs.txt")
                         .WriteTo.Elasticsearch(
                new ElasticsearchSinkOptions(new Uri(configuration["ElasticSearch:Url"]))
            {
                AutoRegisterTemplate        = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
                IndexFormat = "msdemo-log-{0:yyyy.MM}"
            })
                         .CreateLogger();

            try
            {
                Log.Information("Starting BackendAdminApp.Host.");
                BuildWebHostInternal(args).Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "BackendAdminApp.Host terminated unexpectedly!");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Beispiel #17
0
        public static int Main(string[] args)
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            Log.Logger = new LoggerConfiguration()
#if DEBUG
                         .MinimumLevel.Debug()
#else
                         .MinimumLevel.Information()
#endif
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Debug)
                         .Enrich.WithProperty("Application", "Notes")
                         .Enrich.FromLogContext()
                         .WriteTo.File("Logs/logs.txt")
                         .WriteTo.Elasticsearch(
                new ElasticsearchSinkOptions(new Uri("http://117.48.227.241:9200/"))
            {
                AutoRegisterTemplate        = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
                IndexFormat = "msdemo-log-{0:yyyy.MM}"
            })
                         .CreateLogger();


            try
            {
                Log.Information("Starting web host.");
                BuildWebHostInternal(args).Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly!");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        private bool UploadPicture(IFormFile file, ref string path)
        {
            //Check if file is selected
            if (file == null || file.Length == 0)
            {
                return(false); //Content("File not selected");
            }
            //Check for correct filetype
            string extension = Path.GetExtension(file.FileName);

            if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif")
            {
                //Check for filesize > 4mb
                if (file.Length > 400000)
                {
                    return(false); // Content("Too large file");
                }
                //Add timestamp to filename
                var timeStamp = DateTime.Now.ToShortTimeString();
                var fileName  = timeStamp.Replace(':', '.') + file.FileName;

                CurrentDirectoryHelpers.SetCurrentDirectory();

                //Combine filepath
                var imgUrl = Path.Combine(
                    Directory.GetCurrentDirectory(), "wwwroot/PostPictures", fileName);

                //Write code to file
                using (var stream = new FileStream(imgUrl, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
                path = "/PostPictures/" + fileName;

                return(true);
            }
            return(false);    //Content("Incorrect filetype");
        }
Beispiel #19
0
 public static void Main(string[] args)
 {
     CurrentDirectoryHelpers.SetCurrentDirectory(); // call it here
     CreateHostBuilder(args).Build().Run();
 }
Beispiel #20
0
 public Startup(IConfiguration configuration)
 {
     CurrentDirectoryHelpers.SetCurrentDirectory();
     Configuration = configuration;
 }
Beispiel #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //****************************************************
            //Important: ApiLaunchers must be added to the service
            //collection before any dependent services are added
            //(e.g., if you are launching IdentityServer with
            //ApiLauncher, it must be launched before calls
            //to AddAuthentication("Bearer") -- where the
            //address of IdentityServer must be known)
            //****************************************************

            if (HostingEnvironment.EnvironmentName == EnvironmentName.Development &&
                (string.IsNullOrEmpty(Configuration["Apis:IdentityServer:BaseAddress"]))
                )
            {
                services
                .AddLauncher <A.Startup>(Configuration, Logger)
                //.AddLauncher<B.Startup>()
                //... etc.
                .AwaitApis();
                //note: you must call AwaitApis() after adding all launchers
                //AwaitApis() blocks the main thread until the Apis are ready
            }

            var securityOptions = new SecurityOptions();

            Configuration.GetSection("Security").Bind(securityOptions);


            services.AddClientAuthenticationAndAuthorizationWithDefaultPolicies(securityOptions);

            services.AddMvc(options => {
                options.Conventions.Add(new AddDefaultAuthorizationPolicyConvention(HostingEnvironment, Configuration));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .ExcludeReferencedProjectControllers <A.Startup>();


            //add an AuthorizationPolicyProvider which generates default
            //policies upon first access to any controller action
            services.AddSingleton <IAuthorizationPolicyProvider>(new DefaultPoliciesAuthorizationPolicyProvider(
                                                                     Configuration, securityOptions.ScopePatternOptions, Logger));



            Task.Run(() => {
                CurrentDirectoryHelpers.SetCurrentDirectory();
            });

            services.AddScoped <ScopeProperties>();

            services.AddDbContext <AppDbContext>(options =>
                                                 options.UseSqlite($"Data Source={HostingEnvironment.ContentRootPath}/hr.db")
                                                 );



            if (HostingEnvironment.EnvironmentName == EnvironmentName.Development)
            {
                services.AddSwaggerGen(c => {
                    c.SwaggerDoc("v1", new Info {
                        Title = "My API", Version = "v1"
                    });
                });
            }
        }