protected void Application_Start()
        {
            LocalizeFactory.Create();

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var dbInitializer = new DbInitializer();
            dbInitializer.InitializeDatabase(new SvsDbContext());
        }
        //
        // GET: /Home/
        //[Authorize]
        public ActionResult Index()
        {
            //UserServiceFactory.Create().Insert(new User { Avatar = "Avatar", Confirm = true, Email = "*****@*****.**", FirstName = "Stas", Password = "******", SecondName = "Orlov", Comments = new List<Comment>(), Subscribes = new List<Subscribe>(), VideoPosts = new List<VideoPost>()});

            //var users = UserServiceFactory.Create().GetAll();

            //ViewRes.SharedStrings.Culture = new CultureInfo("RU");

            //var cookie = new HttpCookie("CultureInfo");
            //cookie.Expires = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1);
            //cookie["language"]

            var svsDbContext = new SvsDbContext();
            var res = svsDbContext.Contents.Select(content => content.Language == "language").FirstOrDefault();

            var initializer = new DbInitializer();
            initializer.InitializeDatabase(svsDbContext);

            return View();
        }
Exemplo n.º 3
0
        private void DependecyResolver()
        {
            builder = new ContainerBuilder();

            //controllers
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            //generic repositories
            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

            //dbcontext
            if (HttpContext.Current.Request.IsLocal)
            {
                var context = new ApplicationContext(ConfigurationManager.ConnectionStrings["ApplicationContext"].ConnectionString);
                var dbInitializer = new DbInitializer<ApplicationContext>();
                Database.SetInitializer<ApplicationContext>(dbInitializer);
                dbInitializer.InitializeDatabase(context);
                builder.Register<IDbContext>(c => context).SingleInstance();
            }
            else
            {
                Database.SetInitializer<ApplicationContext>(null);
                var context = new ApplicationContext("ApplicationContext");
                builder.Register<IDbContext>(c => context).SingleInstance();
            }

            //services
            builder.RegisterType<FinancialService>().As<IFinancialService>().InstancePerLifetimeScope();
            builder.RegisterType<InventoryService>().As<IInventoryService>().InstancePerLifetimeScope();
            builder.RegisterType<SalesService>().As<ISalesService>().InstancePerLifetimeScope();
            builder.RegisterType<PurchasingService>().As<IPurchasingService>().InstancePerLifetimeScope();
            builder.RegisterType<AdministrationService>().As<IAdministrationService>().InstancePerLifetimeScope();
            //builder.RegisterType<UserManager<ApplicationUser>>().As<UserStore<ApplicationUser>>().InstancePerLifetimeScope();
            //builder.RegisterType<RoleManager<ApplicationRole>>().As<RoleStore<ApplicationRole>>().InstancePerLifetimeScope();

            container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Exemplo n.º 4
0
 public static List <DevInfo> GetDevInfos()
 {
     return(DbInitializer.LoadExcelToList <DevInfo>(baseDir + "DevInfo.xls"));
 }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, A2spaContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (CurrentEnvironment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                // app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // Add a middleware used to validate access
            // tokens and protect the API endpoints.
            app.UseOAuthValidation();

            // Alternatively, you can also use the introspection middleware.
            // Using it is recommended if your resource server is in a
            // different application/separated from the authorization server.
            //
            // app.UseOAuthIntrospection(options =>
            // {
            //     options.AutomaticAuthenticate = true;
            //     options.AutomaticChallenge = true;
            //     options.Authority = "http://localhost:58795/";
            //     options.Audiences.Add("resource_server");
            //     options.ClientId = "resource_server";
            //     options.ClientSecret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd";
            // });

            app.UseOpenIddict();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(CurrentEnvironment.ContentRootPath, "node_modules")),
                RequestPath  = "/node_modules"
            });

            app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, new SwaggerUiOwinSettings()
            {
                OperationProcessors =
                {
                    new OperationSecurityScopeProcessor("apikey")
                },
                DocumentProcessors =
                {
                    new SecurityDefinitionAppender("apikey", new SwaggerSecurityScheme
                    {
                        Type = SwaggerSecuritySchemeType.ApiKey,
                        Name = "Authorization",
                        In   = SwaggerSecurityApiKeyLocation.Header
                    })
                },
                DefaultPropertyNameHandling = PropertyNameHandling.CamelCase
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                // in case multiple SPAs required.
                routes.MapSpaFallbackRoute("spa-fallback", new { controller = "home", action = "index" });
            });

            // if you want to use automated deployments, keep the following line remarked out
            // if (CurrentEnvironment.IsDevelopment())
            {
                DbInitializer.Initialize(context);
            }
        }
Exemplo n.º 6
0
 public AnabiDbContextBuilder WithAllDictionaries()
 {
     DbInitializer.InitializeFullDb(context);
     return(this);
 }
Exemplo n.º 7
0
 public AnabiDbContextBuilder WithRecoveryBeneficiaries()
 {
     DbInitializer.AddRecoveryBeneficiaries(context);
     return(this);
 }
Exemplo n.º 8
0
 public AnabiDbContextBuilder WithStages()
 {
     DbInitializer.AddStages(context);
     return(this);
 }
Exemplo n.º 9
0
 public AnabiDbContextBuilder WithUsers()
 {
     DbInitializer.AddUsers(context);
     return(this);
 }
Exemplo n.º 10
0
        public AnabiDbContextBuilder WithAssetCategories()
        {
            DbInitializer.AddCategories(context);

            return(this);
        }
Exemplo n.º 11
0
        //Use this for starting the server
        public static void StartServer(EmpireService service)
        {
            DbInitializer.Initialize(service);
            List <GruntTask> tsks = service.GetEmpire().gruntTasks;


            //arbitrary buffer size. This may need to change in the future
            byte[]     buffer        = new byte[10000000];
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2012);
            Socket     listener      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(localEndPoint);
            listener.Listen(100);

            while (true)
            {
                Console.WriteLine("Compiler ready");
                Socket socket   = listener.Accept();
                int    bytesRec = socket.Receive(buffer);
                //interpret the message
                var      data       = Encoding.ASCII.GetString(buffer, 0, bytesRec);
                string[] recMessage = data.Split(",");
                //Data is sent with the TaskName first and then
                var    bytesTaskName = Convert.FromBase64String(recMessage[0]);
                var    bytesYAML     = Convert.FromBase64String(recMessage[1]);
                string strTaskName   = Encoding.UTF8.GetString(bytesTaskName);
                string strYAML       = Encoding.UTF8.GetString(bytesYAML);
                // Initialize the task from the passed YAML
                DbInitializer.IngestTask(service, strYAML);
                tsks = service.GetEmpire().gruntTasks;

                try
                {
                    if (strTaskName != "close")
                    {
                        GruntTask tsk         = tsks.First(tk => tk.Name == strTaskName);
                        var       chars       = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                        var       stringChars = new char[5];
                        var       random      = new Random();
                        for (int i = 0; i < stringChars.Length; i++)
                        {
                            stringChars[i] = chars[random.Next(chars.Length)];
                        }
                        var randNew = new String(stringChars);
                        tsk.Name = tsk.Name + "_" + randNew;
                        tsk.Compile();
                        string message  = "FileName:" + tsk.Name;
                        var    msgBytes = Encoding.ASCII.GetBytes(message);
                        socket.Send(msgBytes);
                    }
                    else
                    {
                        socket.Close();
                        break;
                    }
                }
                catch (Exception e)
                {
                    string message  = "Compile failed";
                    var    msgBytes = Encoding.ASCII.GetBytes(message);
                    socket.Send(msgBytes);
                    Console.WriteLine(e.ToString());
                }
            }
        }
Exemplo n.º 12
0
 public static List <DevType> GetDevTypes()
 {
     return(DbInitializer.LoadExcelToList <DevType>(baseDir + "DevType.xls"));
 }
Exemplo n.º 13
0
 public static List <Archor> GetArchors()
 {
     return(DbInitializer.LoadExcelToList <Archor>(baseDir + "Archor.xls"));
 }
Exemplo n.º 14
0
 public static List <DevModel> GetDevModels()
 {
     return(DbInitializer.LoadExcelToList <DevModel>(baseDir + "DevModel.xls"));
 }
Exemplo n.º 15
0
 public static List <ArchorSetting> GetArchorSettings()
 {
     return(DbInitializer.LoadExcelToList <ArchorSetting>(baseDir + "ArchorSetting.xls"));
 }
        public static void Main()
        {
            using var db = new BookShopContext();
            DbInitializer.ResetDatabase(db);

            // 2.Age Restriction
            //var input = Console.ReadLine();
            //var result = GetBooksByAgeRestriction(db, input);
            //Console.WriteLine(result);

            // 3. Golden Books
            //var goldenBooks = GetGoldenBooks(db);
            //Console.WriteLine(goldenBooks);

            //4. Books by Price
            //var booksByPrice = GetBooksByPrice(db);
            //Console.WriteLine(booksByPrice);

            //5. Not Released In
            //var year = int.Parse(Console.ReadLine());
            //var booksReleasedIn = GetBooksNotReleasedIn(db, year);
            //Console.WriteLine(booksReleasedIn);

            //6. Book Titles by Category
            //var input = Console.ReadLine();
            //var result = GetBooksByCategory(db, input);
            //Console.WriteLine(result);

            //7. Released Before Date
            //var date = Console.ReadLine();
            //var result = GetBooksReleasedBefore(db, date);
            //Console.WriteLine(result);

            //8. Author Search
            //var input = Console.ReadLine();
            //var result = GetAuthorNamesEndingIn(db, input);
            //Console.WriteLine(result);

            //9. Book Search
            //var input = Console.ReadLine();
            //var result = GetBookTitlesContaining(db, input);
            //Console.WriteLine(result);

            //10. Book Search by Author
            //var input = Console.ReadLine();
            //var result = GetBooksByAuthor(db, input);
            //Console.WriteLine(result);

            //11. Count Books
            //var length = int.Parse(Console.ReadLine());
            //var countBooks = CountBooks(db, length);
            //Console.WriteLine(countBooks);

            //12. Total Book Copies
            //var result = CountCopiesByAuthor(db);
            //Console.WriteLine(result);

            //13. Profit by Category
            var result = GetTotalProfitByCategory(db);

            Console.WriteLine(result);

            //14. Most Recent Books
            //var result = GetMostRecentBooks(db);
            //Console.WriteLine(result);

            //15. Increase Prices
            //IncreasePrices(db);

            //16. Remove Books
            //var removedBooks = RemoveBooks(db);
            //Console.WriteLine(removedBooks);
        }
Exemplo n.º 17
0
 protected void Application_Start()
 {
     GlobalConfiguration.Configure(WebApiConfig.Register);
     DbInitializer.Initialize();
 }
Exemplo n.º 18
0
        public Task Invoke(HttpContext httpContext, ApplicationContext dbContext)
        {
            DbInitializer.Initialize(dbContext);

            return(_next(httpContext));
        }
Exemplo n.º 19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //Diagnostics

            //app.UseWelcomePage();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseStatusCodePages();
            }
            else
            {
                app.UseExceptionHandler("/AppException");
            }

            //gzip compression
            app.UseResponseCompression();

            app.UseStaticFiles();
            app.UseSession();
            app.UseIdentity();

            loggerFactory.AddConsole(LogLevel.Debug);
            loggerFactory.AddDebug(LogLevel.Debug);

            ////loggerFactory.AddDebug((c, l) => c.Contains("HomeController") && l > LogLevel.Trace);
            //loggerFactory
            //    .WithFilter(new FilterLoggerSettings
            //    {
            //        {"Microsoft", LogLevel.Warning},
            //        {"System", LogLevel.Warning},
            //        {"HomeController", LogLevel.Debug}
            //    }).AddDebug();

            //Serilog
            //Log.Logger = new LoggerConfiguration()
            //    .MinimumLevel.Debug()
            //    .WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "BethanysLogs-{Date}.txt"))
            //    .CreateLogger();

            //loggerFactory.AddSerilog();

            //app.UseMvcWithDefaultRoute();

            app.UseGoogleAuthentication(new GoogleOptions
            {
                ClientId     = "351865068992-9n45989ahb0ot26m10clusj206a7ub4n.apps.googleusercontent.com",
                ClientSecret = "ERD5Lvjf8TpGUUnuyTGv27vo"
            });

            app.UseRequestLocalization(app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >().Value);



            app.UseMvc(routes =>
            {
                //areas
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}");

                routes.MapRoute(
                    name: "categoryfilter",
                    template: "Pie/{action}/{category?}",
                    defaults: new { Controller = "Pie", action = "List" });

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            DbInitializer.Seed(app);
        }
Exemplo n.º 20
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ContextString context)
        {
            //初始化数据库
            DbInitializer.Initialize(context);
            Method._hostingEnvironment = env;
            //  Method._context = context;


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }


            app.UseWebSockets();
            app.UseMiddleware <ChatWebSocketMiddleware>();


            var staticfile = new StaticFileOptions();

            staticfile.ServeUnknownFileTypes = true;
            staticfile.DefaultContentType    = "application/x-msdownload"; //设置默认  MIME
            var provider = new FileExtensionContentTypeProvider();

            provider.Mappings.Add(".log", "text/plain");//手动设置对应MIME
            staticfile.ContentTypeProvider = provider;
            app.UseStaticFiles(staticfile);


            //启用Session
            // app.UseSession();

            //启用跨域访问配置
            app.UseCors("CorsSample");



            Method._hostingEnvironment = env;
            Method._context            = context;

            Method.ServerMac = Method.GetServerMac();


            app.UseHttpsRedirection();
            app.UseCookiePolicy();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");


                routes.MapRoute(
                    name: "MS",
                    template: "{MallSite=MallSite}/{API=API}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "API",
                    template: "{API=API}/{controller=Home}/{action=Index}/{id?}");


                routes.MapRoute(
                    name: "area",
                    template: "{MallSite=MallSite}/{controller=Home}/{action=Index}/{id?}");
            });

            //注册客户唯一代码
            Method.CusID = Method.GetCusID(context, Configuration.GetConnectionString("RegKey"));
            ServerIOTHelper.CreateServerToIOT();



            Method.PullDataFromCloud();
            string IsStartHF = Configuration.GetConnectionString("HangfireStart");

            if (IsStartHF == "true")
            {
                //添加Hangfire应用
                app.UseHangfireServer();
                app.UseHangfireDashboard("/api/jobs", new DashboardOptions()
                {
                    Authorization = new[] { new CustomAuthorizeFilter() }
                });



                //更新服务器状态
                RecurringJob.AddOrUpdate(
                    () => Method.UpdateDevState(),
                    Cron.Minutely);
                RecurringJob.AddOrUpdate(
                    () => Method.PullDataFromCloud(),
                    Cron.Daily());
                ServerIOTHelper.ServerSubIOT();
                // var _thisjobId = BackgroundJob.Enqueue(() => ServerIOTHelper.ServerSubIOT());

                //                RecurringJob.AddOrUpdate(
                //() => ServerIOTHelper.ServerPublishIOT(subReturn.mqttClient,subReturn.serveriot),
                //Cron.Minutely);
            }
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Need a Guild Member file that type is csv.");
                Console.Read();
                return;
            }

            // Validate a Guild Member file
            var guildMemberFilePath = args[0];
            var guildMemberFileInfo = new FileInfo(guildMemberFilePath);

            if (!guildMemberFileInfo.Exists || !guildMemberFileInfo.Extension.Equals(".csv", StringComparison.CurrentCultureIgnoreCase))
            {
                Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] Invalid a Guild Member file");
                Console.Read();
                return;
            }

            // Initialize a DB
            var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            var options          = SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder <RankContext>(), connectionString).Options;

            using (var context = new RankContext(options))
            {
                DbInitializer.Initialize(context);
                var guildName = guildMemberFileInfo.Name.Replace(guildMemberFileInfo.Extension, "");
                var guild     = CreateGuild(context, guildName);

#if UPDATE_WEEKLY_RANKING
                UpdateWeeklyRanking(context, guild, new DateTime(2018, 8, 10));
#else
                // Read a Guild Member file
                using (var sr = guildMemberFileInfo.OpenText())
                {
                    var membersInfo = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var memberInfo in membersInfo)
                    {
                        var splitedMemberInfo = memberInfo.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (splitedMemberInfo.Length != 2)
                        {
                            Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] Invalid a Member Info");
                            continue;
                        }

                        // Gets or Create the Guild and Member to Database
                        var guildPosition = splitedMemberInfo[0];
                        var characterName = splitedMemberInfo[1];
                        var member        = CreateCharacter(context, characterName, guild, guildPosition);

                        // Get a Ranking of Character vis web parsing
                        var ranking = GetCharacterRanking(member.Name, UsedEncoding);
                        if (String.IsNullOrWhiteSpace(ranking))
                        {
                            Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] Cannot found a ranking of Member '{member.Name}'");
                            continue;
                        }

                        var rankingDate = GetRankingUpdatedDate();

                        // Update
                        UpdateRanking(context, member, ranking, rankingDate);
                    }
                }

                // Add Weekly Ranking
                AddWeeklyRanking(context, guild);
#endif
            }

            Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}] Finish a getting the ranking of memeber!");
            Console.ReadLine();
        }
Exemplo n.º 22
0
 public DepartmentTest()
 {
     _db = new PurchaseReqContext();
     DbInitializer.ClearData(_db);
     DbInitializer.SeedData(_db);
 }
Exemplo n.º 23
0
 public AnabiDbContextBuilder WithCrimeTypes()
 {
     DbInitializer.AddCrimeTypes(context);
     return(this);
 }
Exemplo n.º 24
0
 public void Dispose()
 {
     DbInitializer.ClearData(_db);
     _db.Dispose();
 }
Exemplo n.º 25
0
 public AnabiDbContextBuilder WithDecisions()
 {
     DbInitializer.AddDecisions(context);
     return(this);
 }
Exemplo n.º 26
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DbInitializer seeder, IAntiforgery antiforgery, IKotraNewsService kotra, IMemoryCache memoryCache, ExodusKoreaContext ekcontext)
        {
            // load kotra news in background and store in cache
            //foreach (var c in ekcontext.News)
            //{
            //    var cache = memoryCache.Get<List<KotraNewsVM>>(c.Topic);
            //    if (cache == null)
            //        kotra.GetKotraNewsByCountry(c.Topic);
            //}

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

            app.UseStaticFiles();

            app.UseCors(builder =>
            {
                if (_appSettingsEnv.Equals("Live"))
                {
                    builder.WithOrigins("https://talchoseon.com");
                }
                else if (_appSettingsEnv.Equals("Development"))
                {
                    builder.WithOrigins("http://localhost:4200");
                }
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowCredentials();
            });

            app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        //context.Response.AddApplicationError(error.Error.Message);
                        await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
                    }
                });
            });

            app.Use(next => context =>
            {
                if (context.Request.Path.Value.IndexOf("/", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions()
                    {
                        HttpOnly = false
                    });
                }

                return(next(context));
            });

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute("DefaultApi", "api/{controller}/{id?}");
            });

            app.UseWelcomePage();

            //seeder.InitializeData().Wait();
        }
Exemplo n.º 27
0
 public AnabiDbContextBuilder WithCounties()
 {
     DbInitializer.AddCounties(context);
     return(this);
 }
Exemplo n.º 28
0
 public bool InitDB()
 {
     DbInitializer.Initialize(_context);
     return(true);
 }
Exemplo n.º 29
0
 public AnabiDbContextBuilder WithIdentifiers()
 {
     DbInitializer.AddIdentifiers(context);
     return(this);
 }
        public IRepository_Tests()
        {
            var _context = DbInitializer.CreateFakeDatabase();

            _repository = new RepositoryBase(_context);
        }
Exemplo n.º 31
0
        static void Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name        = "Ejercicio1.Tools.DataBaseInitialization",
                Description = "Herramienta para inicializar y/o actualizar la base de datos de un proyecto nuevo con la plantilla del ITI.Core"
            };


            var modeOption = app.Option("-m|--mode",
                                        "Test/Produccion -> Por defecto Produccion",
                                        CommandOptionType.SingleValue);

            var connectionStringOption = app.Option("-cs|--connectionString",
                                                    "Cadena de conexion de la base de datos",
                                                    CommandOptionType.SingleValue);

            app.HelpOption("-? | -h | --help");

            app.OnExecute(() =>
            {
                Console.WriteLine("Ejecutando Ejercicio1.Tools.DataBaseInitialization ...");


                if (!connectionStringOption.HasValue())
                {
                    Console.WriteLine("Es obligatorio especificar la cadena de conexión de la base de datos. Use el parametro -connectionString");

                    app.ShowHelp();

                    app.ShowHint();

                    return(-1);
                }

                connectionString = connectionStringOption.Value();


                if (modeOption.HasValue())
                {
                    mode = modeOption.Value().ToLower();
                }

                IServiceCollection services = new ServiceCollection();

                services.AddTransient <IPrincipalAccessor, NullPrincipalAccessor>();
                services.AddTransient <IUserSession, UserSession>();

                services.AddDbContext <ITICoreTemplateDbContext>(options =>
                                                                 options.UseSqlServer(connectionString));

                BootStrapper bootStrapper = new BootStrapper(services)
                                            .UseEntityFrameworkCore <ITICoreTemplateDbContext>();


                bootStrapper.Compose();

                var serviceProvider = services.BuildServiceProvider();

                try
                {
                    var context = serviceProvider.GetRequiredService <ITICoreTemplateDbContext>();

                    switch (mode)
                    {
                    case "test":
                        Console.WriteLine("Inicializando en modo Test:");

                        Console.WriteLine("Eliminando la base de datos.");

                        context.Database.EnsureDeleted();

                        Console.WriteLine("Creando la base de datos y cargando los datos de prueba.");
                        Console.WriteLine("Esta operación puede tardar unos segundos");

                        context.Database.Migrate();

                        DbInitializer.Initialize(context);
                        break;

                    case "prod":
                    default:
                        Console.WriteLine("Inicializando en modo Producción:");


                        Console.WriteLine("Aplicando las migrations.");
                        Console.WriteLine("Esta operación puede tardar unos segundos");

                        context.Database.Migrate();

                        break;
                    }
                }
                catch (Exception ex)
                {
                    Console.BackgroundColor = ConsoleColor.Red;

                    Console.WriteLine("Ha ocurrido el siguiente error al ejecutar la herramienta");
                    Console.WriteLine(ex.Message);

                    if (ex.InnerException != null)
                    {
                        Console.WriteLine(ex.InnerException.Message);
                    }

                    var logger = serviceProvider.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");

                    Console.ResetColor();

                    CountDown();

                    return(-1);
                }

                Console.WriteLine("Fin del proceso");


                CountDown();

                return(0);
            });

            app.Execute(args);
        }
Exemplo n.º 32
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, BUAContext dbcontext, IApplicationLifetime appLifetime)
        {
            //同一日志中间件需要最先引入,方法全程记录全局日志
            #region 记录日志默认方法
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            #endregion

            #region Serilog日志插件配置

            loggerFactory.AddDebug((className, logLevel) =>
            {
                if (className.StartsWith("ET.BUA."))
                {
                    return(true);
                }
                return(false);
            });

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .MinimumLevel.Override("ET.BUA", Serilog.Events.LogEventLevel.Debug)
                         .Enrich.FromLogContext()
                         .WriteTo.LiterateConsole()
                         .WriteTo.Seq("http://172.28.10.82:5341")
                         .CreateLogger();

            loggerFactory.AddSerilog();
            appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);
            #endregion

            #region 跨域请求配置
            //1.域 AllowAnyOrigin()  WithOrigins()
            //2.方法 AllowAnyMethod() WithMethods()
            //3.请求头AllowAnyHeader() WithHeaders()
            //4.设置暴露的响应头 WithExposedHeaders()
            #region 1.设置允许的域
            //允许一个或多个请求的域
            app.UseCors(builder =>
            {
                builder.WithOrigins("http://desktop.dongjiangoa.com", "http://document.dongjiangoa.com")
                .AllowAnyHeader().AllowAnyMethod();
            });
            //允许所有的域
            app.UseCors(builder =>
            {
                builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
            });
            #endregion

            #region 2.设置允许的HTTP方法
            app.UseCors(builder =>
            {
                builder.AllowAnyOrigin().AllowAnyHeader().WithMethods("POST", "GET", "HEAD");
            });
            #endregion

            #region 3.设置允许请求头
            app.UseCors(builder =>
            {
                builder.AllowAnyOrigin().WithHeaders("accept", "content-type", "origin", "x-custom-header").AllowAnyMethod();
            });
            #endregion

            #region 4.设置暴露的响应头

            /*默认情况下,浏览器并不暴露所有的响应头,默认可用的响应头如下所示:
             * Cache - Control
             * Content - Language
             * Content - Type
             * Expires
             * Last - Modified
             * Pragma*/
            app.UseCors(builder =>
            {
                builder.AllowAnyOrigin().WithExposedHeaders("x-custom-header");
            });
            #endregion

            #endregion

            #region 开发-生产环境设置切换
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            #endregion

            #region StaticFiles 中间件
            app.UseStaticFiles();
            #endregion

            #region MVC路由设置

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=App}/{action=AppAdd}/{id?}");
            });

            #endregion

            #region 数据初始化
            DbInitializer.Initialize(dbcontext);
            #endregion

            #region 配置默认请求响应
            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
            #endregion

            appLifetime.ApplicationStopped.Register(() => this.Container.Dispose());
        }
Exemplo n.º 33
0
        public ActionResult Upload()
        {
            DbInitializer<ApplicationContext> initializer = new DbInitializer<ApplicationContext>();
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = System.IO.Path.GetFileName(file.FileName);
                    var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                    file.SaveAs(path);

                    DbInitializerHelper.LoadChartOfAccountsFromFile(fileName, 100);
                }
            }
            return RedirectToAction("Index");
        }
Exemplo n.º 34
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SpaDbContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseStaticFiles();

            DbInitializer.Initialize(context);

            app.UseCors((builder) =>
            {
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowAnyOrigin();
                builder.AllowCredentials();
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
                    HotModuleReplacement = true
                });

                app.UseSwagger();

                // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                });

                app.MapWhen(x => !x.Request.Path.Value.StartsWith("/swagger"), builder =>
                {
                    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
                    {
                        Authority            = "http://localhost:5000",
                        RequireHttpsMetadata = false,

                        ApiName = "api1"
                    });

                    builder.UseMvc(routes =>
                    {
                        routes.MapSpaFallbackRoute(
                            name: "spa-fallback",
                            defaults: new { controller = "Home", action = "Index" });
                    });
                });
            }
            else
            {
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");

                    routes.MapRoute(
                        "Sitemap",
                        "sitemap.xml",
                        new { controller = "Home", action = "SitemapXml" });

                    routes.MapSpaFallbackRoute(
                        name: "spa-fallback",
                        defaults: new { controller = "Home", action = "Index" });
                });
                app.UseExceptionHandler("/Home/Error");
            }
        }