Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            //services.AddDbContext<FrendsMapContext>(options =>
            //        options.UseSqlServer(Configuration.GetConnectionString("FrendsMapContext")));

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <FrendsMapContext>(options =>
                                                     options.UseSqlServer(Configuration.GetConnectionString("FrendsMapContext"), optionsBuilder => optionsBuilder.MigrationsAssembly(migrationsAssembly)));

            services.Configure <AzureStorageConfig>(Configuration.GetSection("AzureStorageConfig"));
            //services.AddSingleton(x => new String(Configuration.GetValue<string>("AzureBlobStorageConnectionString")));
            // services.AddSingleton<IBlobService, BlobService>();

            services.AddTransient <IPlaceService, PlaceService>();
            services.AddTransient <ITypeOfPlaceService, TypeOfPlaceService>();
            services.AddTransient <IPersonService, PersonService>();
            services.AddTransient <IRankingService, RankingService>();
            services.AddTransient <ICommentService, CommentService>();
            services.AddTransient <IPhotoService, PhotoService>();
            services.AddTransient <IRankingOfFriendService, RankingOfFriendService>();

            services.AddTransient <IUnitOfWork, UnitOfWork>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            //
            services.AddMvc(mvcOptions => { mvcOptions.EnableEndpointRouting = false; });
            EntityFrameworkProfiler.Initialize();
        }
        static async Task Main(string[] args)
        {
            try
            {
                EntityFrameworkProfiler.Initialize();

                var config = Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;
                config.CodeFirstOptions.UseNonUnicodeStrings = true;
                config.CodeFirstOptions.UseNonLobStrings     = true;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();
                EntityContext.ConnectionString = ComposeConnectionString(configuration);

                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var context = new EntityContext())
                    {
                        context.Database.EnsureDeleted();
                        context.Database.ExecuteSqlCommand(@"
CREATE TABLE RIDER
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    MOUNT       VARCHAR2 (100 CHAR)
)");

                        var rider = new Rider(EquineBeast.Mule);
                        context.Add(rider);
                        await context.SaveChangesAsync();
                    }

                    scope.Complete();
                }

                using (var context = new EntityContext())
                {
                    // The following code generates an invalid query: ORA-01722: invalid number
                    var rider = context.Set <Rider>()
                                .FirstOrDefault(_ => _.Mount.HasValue &&
                                                _.Mount.Value == EquineBeast.Mule);
                }

                Console.WriteLine("Finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
Ejemplo n.º 3
0
        public void ConfigureDevelopmentServices(IServiceCollection services)
        {
            // use in-memory database
            //ConfigureInMemoryDatabases(services);

            EntityFrameworkProfiler.Initialize();
            // use real database
            ConfigureProductionServices(services);
        }
Ejemplo n.º 4
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            //var constraintsResolver = new DefaultInlineConstraintResolver();
            //constraintsResolver.ConstraintMap.Add("apiVersionConstraint", typeof(ApiVersionConstraint));
            //config.MapHttpAttributeRoutes(constraintsResolver);

            // Remove the XML formatter
            //config.Formatters.Remove(config.Formatters.XmlFormatter);

            // Add JSON return type by default, even when text/html is specified
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            //config.Formatters.JsonFormatter.MaxDepth = 1;

            // Ignore null values - don't emit properties with Json Nulls
            //config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            /*
             * config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
             * = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
             *
             *
             * config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling
             *   = Newtonsoft.Json.PreserveReferencesHandling.Objects;
             *
             */

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            /*
             * config.Services.Replace(typeof(ITraceWriter),
             * new SimpleTraceWriter(WebContainerManager.Get<ILogManager>()));
             *
             * config.Services.Add(typeof(IExceptionLogger),
             *  new SimpleExceptionLogger(WebContainerManager.Get<ILogManager>()));
             *
             * config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
             */

            EntityFrameworkProfiler.Initialize();

            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            GlobalConfiguration.Configuration.MessageHandlers.Add(new BasicAuthenticationMessageHandler());
        }
Ejemplo n.º 5
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            EntityFrameworkProfiler.Initialize();
        }
 private static void Main()
 {
     EntityFrameworkProfiler.Initialize();
     Database.DefaultConnectionFactory = new SqlConnectionFactory("System.Data.SqlServer");
     Database.SetInitializer(new MigrateDatabaseToLatestVersion <MyContext, MyContextConfiguration>());
     using (var context = new MyContext())
     {
         var element = context.Dummies.FirstOrDefault();
     }
 }
 static void Main(string[] args)
 {
     EntityFrameworkProfiler.Initialize();
     using (var ctx = new NorthwndContext())
     {
         var customersV1 = ctx.Customers.Where(x => x.CompanyName.StartsWith("A")).ToList();
         var customersV2 = ctx.Customers.Where(x => EF.Functions.Like(x.CompanyName, "A%")).ToList();
         Console.WriteLine($"Version 1 returned {customersV1.Count} And 2 {customersV2.Count}");
     }
 }
Ejemplo n.º 8
0
        protected void Application_Start(object sender, EventArgs e)
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AutofacConfig.Configure(out _containerProvider);

            if (HttpContext.Current.IsDebuggingEnabled)
            {
                EntityFrameworkProfiler.Initialize();
            }
        }
        public static void PreStart()
        {
            // Initialize the profiler
            EntityFrameworkProfiler.Initialize();

            // You can also use the profiler in an offline manner.
            // This will generate a file with a snapshot of all the EntityFramework activity in the application,
            // which you can use for later analysis by loading the file into the profiler.
            // var filename = @"c:\profiler-log";
            // EntityFrameworkProfiler.InitializeOfflineProfiling(filename);
        }
Ejemplo n.º 10
0
 static void Main(string[] args)
 {
     EntityFrameworkProfiler.Initialize();
     using (var ctx = new NorthwndContext())
     {
         var query = ctx.Customers.Where(x => x.CompanyName.StartsWith("A")).ToList();
         foreach (var result in query)
         {
             Console.WriteLine($"Company: {result.CompanyName}");
         }
     }
 }
Ejemplo n.º 11
0
        private void Application_Start(object sender, EventArgs e)
        {
            EntityFrameworkProfiler.Initialize();
            UoW.UoWFactory = () => new EFUoW(new MyBlogConnection());

            UoW.SubscribeToDomainEvents = () =>
            {
                DomainEvents
                .When <UserCommentedOnPost>()
                .DelayUntill(CurrentTransaction.Committed)
                .Then(@event => { });
            };
        }
        public static void PreStart()
        {
            // Initialize the profiler
            EntityFrameworkProfiler.Initialize();

            // You can also use the profiler in an offline manner.
            // This will generate a file with a snapshot of all the EntityFramework activity in the application,
            // which you can use for later analysis by loading the file into the profiler.
            // var filename = @"c:\profiler-log";
            // EntityFrameworkProfiler.InitializeOfflineProfiling(filename);

            // You can use the following for production profiling.
            // EntityFrameworkProfiler.InitializeForProduction(11234, "A strong password like: ze38r/b2ulve2HLQB8NK5AYig");
        }
Ejemplo n.º 13
0
        public void OnStartUp()
        {
            EntityFrameworkProfiler.Initialize();

            var resolver = new TestEfDependencyResolver {
                Modules = new List <IDbContextModule> {
                    new EntityAuditModule()
                }
            };

            EfConfiguration.RegisterDependencyResolver <TestDbContext>(resolver);
            Database.SetInitializer(new DropCreateDatabaseAlways <TestDbContext>());
            resolver.Modules.Clear();
        }
Ejemplo n.º 14
0
        public static void Main(string[] args)
        {
            EntityFrameworkProfiler.Initialize();

            Database.SetInitializer(new NullDatabaseInitializer <AnimalStoveDbContext>());
            Database.SetInitializer(new NullDatabaseInitializer <PersonStoveDbContext>());

            IRootResolver resolver = IocBuilder.New
                                     .UseAutofacContainerBuilder()
                                     .UseStove <StoveDemoBootstrapper>(false)
                                     .UseStoveEntityFramework()
                                     .UseStoveDapper()
                                     .UseStoveMapster()
                                     .UseStoveEventBus()
                                     .UseStoveDbContextEfTransactionStrategy()
                                     .UseStoveTypedConnectionStringResolver()
                                     .UseStoveNLog()
                                     .UseStoveBackgroundJobs()
                                     .UseStoveRedisCaching()
                                     .UseStoveRabbitMQ(configuration =>
            {
                configuration.HostAddress = "rabbitmq://localhost/";
                configuration.Username    = "******";
                configuration.Password    = "******";
                configuration.QueueName   = "Default";
                return(configuration);
            })
                                     .UseStoveHangfire(configuration =>
            {
                configuration.GlobalConfiguration
                .UseSqlServerStorage("Default")
                .UseNLogLogProvider();
                return(configuration);
            })
                                     .RegisterServices(r => r.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly()))
                                     .CreateResolver();

            //var someDomainService = resolver.Resolve<SomeDomainService>();
            //someDomainService.DoSomeStuff();

            var productDomainService = resolver.Resolve <ProductDomainService>();

            productDomainService.DoSomeStuff();

            resolver.Dispose();

            EntityFrameworkProfiler.Shutdown();

            Console.ReadKey();
        }
Ejemplo n.º 15
0
        public static void Main(string[] args)
        {
            EntityFrameworkProfiler.Initialize();

            Database.SetInitializer(new NullDatabaseInitializer <PersonDbContext>());
            Database.SetInitializer(new NullDatabaseInitializer <AnimalDbContext>());

            AbpBootstrapper bootstrapper = AbpBootstrapper.Create <SampleApplicationModule>();

            bootstrapper.Initialize();

            var someDomainService = bootstrapper.IocManager.Resolve <SomeDomainService>();

            someDomainService.DoSomeStuff();
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            EntityFrameworkProfiler.Initialize();

            using (var db = new AppDbContext())
            {
                foreach (var item in
                         db.StudentCourses
                         .Include("Student")
                         .Include("Course").ToList())
                {
                    Console.WriteLine(String.Format("", item.Student.Name, item.Course.Title));
                }
            }

            Console.WriteLine();
        }
Ejemplo n.º 17
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);
            if (this.IsDebugEnabled)
            {
                EntityFrameworkProfiler.Initialize();
            }

            builder
            .Register(x => new LocalDbContext())
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <LocalizationManagerImpl>()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            EntityFrameworkProfiler.Initialize();
            AutoMapperConfiguration.Configure();
            InjectByConfig();

            var userService = Container.Resolve <IUserService>();
            //var roleService = Container.Resolve<IRoleService>();
            var userDto = new UserDto()
            {
                Id = 8, Name = "lisi123123 "
            };
            //var userDto = userService.Get(7);
            //var role = roleService.Get(19);
            //var roleDto = new RoleDto() { Id=23};
            //userDto.Roles.Add(roleDto);
            //userService.Add(userDto);
            var array = new int[] { 23 };

            userService.Update(userDto, array);
            //var roleRepository = manager.Repository<Role>();
            //var userRepository = manager.Repository<User>();
            //var role = new Role()
            //{
            //    Id = 19,
            //    Name = "admin1",
            //    Code = "admin1"
            //};
            //var user = new User()
            //{
            //    Name = "zhangsan5",
            //};
            //user.Roles.Add(role);
            //userRepository.Add(user);

            //manager.Commit();
            Console.ReadKey();
        }
Ejemplo n.º 19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            EntityFrameworkProfiler.Initialize();
            services.AddDbContext <NorthwindDbContext>(ConfigureDbContextOptionsBuilder);

            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddTagHelpersAsServices()
            .AddControllersAsServices()
            .AddRazorRuntimeCompilation()
            .AddFluentValidation()
            .AddFeatureFolders(x =>
            {
                x.ClearDefaultViewLocationFormats     = false;
                x.ClearDefaultPageViewLocationFormats = false;
            })
            .AddAreaFeatureFolders(x =>
            {
                x.ClearDefaultAreaViewLocationFormats     = false;
                x.ClearDefaultAreaPageViewLocationFormats = false;
            });

            services.AddRouting(x =>
            {
                x.LowercaseQueryStrings = true;
                x.LowercaseUrls         = true;
            });

            services.AddMediatR(GetType().Assembly);
            services.AddAutoMapper(GetType().Assembly);
            services.AddDefaultGenericSearch(GetType().Assembly);
            services.ConfigureOptions <ConfigureGenericSearchOptions>();

            ConfigureOptions(services);
        }
        public void Configuration(IAppBuilder app)
        {
            EntityFrameworkProfiler.Initialize();

            // Create DI container
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

            // Create WebAPI config
            var config = new HttpConfiguration();

            // Set up DI container
            container.RegisterWebApiControllers(config);

            // Set up ODataQueryMapper
            ODataQueryMapper.Initialize(
                x =>
            {
                x.CreateMap <DomainAlbum, Album>("album")
                .ForMember(y => y.Id, y => y.AlbumId);
                x.Configure <Album>("album2", y => y.HasKey(z => z.AlbumId).Count().Filter().OrderBy(), true);

                x.AddProfile <TestProfile>();
            });

            // Set up Automapper
            Mapper.Initialize(
                x =>
            {
                x.ConstructServicesUsing(config.DependencyResolver.GetService);
                x.CreateMap <Album, DomainAlbum>()
                .ForMember(m => m.Id, y => y.MapFrom(z => z.AlbumId))
                .ForMember(m => m.Artist, y => y.MapFrom(z => new Resource <long>()
                {
                    Value = z.Artist.ArtistId, Title = z.Artist.Name, Link = $"/api/artist/{z.Artist.ArtistId}"
                }));
                x.CreateMap <Artist, DomainArtist>()
                .ForMember(m => m.Id, y => y.MapFrom(z => z.ArtistId))
                .ForMember(m => m.DisplayName, y => y.MapFrom(z => z.Name))
                .ForMember(m => m.Albums, y => y.Ignore());
                x.CreateMap <Track, DomainTrack>()
                .ForMember(m => m.Wbs, y => y.MapFrom(z => z.TrackId))
                .ForMember(m => m.Title, y => y.MapFrom(z => z.Name))
                .ForMember(m => m.Album, y => y.MapFrom(z => new Resource <long>()
                {
                    Value = z.Album.AlbumId, Title = z.Album.Title, Link = $"/api/album/{z.Album.AlbumId}"
                }));
            });

            container.RegisterWebApiRequest(() => ODataQueryMapper.Engine);
            container.RegisterWebApiRequest(() => Mapper.Instance);
            container.RegisterWebApiRequest <IAlbumRepository, AlbumRepository>();
            container.RegisterWebApiRequest <IArtistRepository, ArtistRepository>();
            container.RegisterWebApiRequest <ITrackRepository, TrackRepository>();
            container.RegisterWebApiRequest <IArtistFunctions, ArtistFunctions>();
            container.RegisterWebApiRequest <IAlbumFunctions, AlbumFunctions>();
            container.RegisterWebApiRequest <ITrackFunctions, TrackFunctions>();

            container.Verify();

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{id}",
                new { id = RouteParameter.Optional });
            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
            config.MapODataServiceRoute(
                "DefaultOData",
                "odata",
                ODataQueryMapper.Engine.GetModel());

            // Register the dependency resolver.
            config.DependencyResolver       = new SimpleInjectorWebApiDependencyResolver(container);
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            config.EnsureInitialized();

            // Start WebAPI
            app.UseWebApi(config);
        }
Ejemplo n.º 21
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddEFSecondLevelCache();

            // Add an in-memory cache service provider
            services.AddSingleton(typeof(ICacheManager <>), typeof(BaseCacheManager <>));
            services.AddSingleton(typeof(ICacheManagerConfiguration),
                                  new CacheManager.Core.ConfigurationBuilder()
                                  .WithJsonSerializer(JsonExtensions.JsonNetSetting, JsonExtensions.JsonNetSetting)
                                  .WithMicrosoftMemoryCacheHandle(instanceName: "MemoryCache1")
                                  .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10))
                                  .DisablePerformanceCounters()
                                  .DisableStatistics()
                                  .Build());

            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            if (connectionString.Contains("{{CFG}}", StringComparison.CurrentCulture))
            {
                // D:\\RSDB\\RSDB.mdf
                var config = Assembly.GetEntryAssembly().ReadConfiguration();
                if (config == null)
                {
                    return;
                }

                connectionString = connectionString.Replace("{{CFG}}", config.DbPath, StringComparison.CurrentCulture);
            }
            //            Console.WriteLine(connectionString);
            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseLazyLoadingProxies();

                options.UseSqlServer(connectionString,
                                     optionsBuilder =>
                {
                    optionsBuilder.MigrationsAssembly($"{nameof(RealEstate)}.{nameof(RealEstate.Web)}");
                    optionsBuilder.UseNetTopologySuite();
                    optionsBuilder.EnableRetryOnFailure();
                    optionsBuilder.CommandTimeout((int)TimeSpan.FromMinutes(3).TotalSeconds);
                    optionsBuilder.UseRowNumberForPaging();
                });
                options.ConfigureWarnings(config =>
                {
                    config.Log(CoreEventId.IncludeIgnoredWarning);
                    config.Log(CoreEventId.NavigationIncluded);
                    config.Log(CoreEventId.LazyLoadOnDisposedContextWarning);
                    //                    config.Throw(RelationalEventId.QueryClientEvaluationWarning);
                    //                    config.Throw(CoreEventId.LazyLoadOnDisposedContextWarning);
                    //                    config.Throw(CoreEventId.NavigationLazyLoading);
                });
                options.EnableSensitiveDataLogging();
            });

            services.AddCors();

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = AuthenticationScheme.Scheme;
                options.DefaultSignInScheme       = AuthenticationScheme.Scheme;
                options.DefaultChallengeScheme    = AuthenticationScheme.Scheme;
            })
            .AddCookie(AuthenticationScheme.Scheme,
                       options =>
            {
                options.SlidingExpiration   = false;
                options.LoginPath           = "/Index";
                options.LogoutPath          = $"/{nameof(RealEstate.Web.Pages.Manage)}/Logout";
                options.AccessDeniedPath    = "/Forbidden";
                options.ExpireTimeSpan      = TimeSpan.FromDays(30);
                options.EventsType          = typeof(AuthenticationTracker);
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.Cookie.SameSite     = SameSiteMode.Lax;
            });

            services.AddMvcCore(options => options.RespectBrowserAcceptHeader = true);

            services.AddElmah(options =>
            {
                options.ConnectionString = connectionString;
            });
            services.AddSingleton <LocalizationService>();
            services.AddLocalization(options => options.ResourcesPath = "");

            services
            .AddMvc(options =>
            {
                options.ModelBinderProviders.Insert(0, new StringModelBinderProvider());
            })
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder($"/{nameof(RealEstate.Web.Pages.Manage)}");
                options.Conventions.AddPageRoute("/manage/owners/edit", "manage/owners/edit/{id}");
                options.AllowMappingHeadRequestsToGetHandler = true;
            })
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create(nameof(SharedResource), assemblyName.Name));
                };
            })
            .AddJsonOptions(
                options =>
            {
                var settings = JsonExtensions.JsonNetSetting;
                options.SerializerSettings.Error = settings.Error;
                options.SerializerSettings.DefaultValueHandling       = settings.DefaultValueHandling;
                options.SerializerSettings.ReferenceLoopHandling      = settings.ReferenceLoopHandling;
                options.SerializerSettings.ObjectCreationHandling     = settings.ObjectCreationHandling;
                options.SerializerSettings.ContractResolver           = settings.ContractResolver;
                options.SerializerSettings.Formatting                 = settings.Formatting;
                options.SerializerSettings.PreserveReferencesHandling = settings.PreserveReferencesHandling;
            }
                );

            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = true;
            });

            EntityFrameworkProfiler.Initialize();
            services.AddHealthChecks()
            .AddCheck("sql-server", () =>
            {
                using (var connection = new SqlConnection(connectionString))
                {
                    try
                    {
                        connection.Open();
                    }
                    catch (SqlException)
                    {
                        return(HealthCheckResult.Unhealthy());
                    }
                }
                return(HealthCheckResult.Healthy());
            });

            services.Configure <FormOptions>(options => options.MultipartBodyLengthLimit = 838860800);
            services.AddWebMarkupMin(
                options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment  = true;
                options.DisablePoweredByHttpHeaders = true;
            })
            .AddHtmlMinification(
                options =>
            {
                options.MinificationSettings.RemoveRedundantAttributes         = true;
                options.MinificationSettings.RemoveHttpProtocolFromAttributes  = true;
                options.MinificationSettings.RemoveHttpsProtocolFromAttributes = true;
                options.MinificationSettings.MinifyEmbeddedJsCode = true;
                options.GenerateStatistics = true;
                options.MinificationSettings.RemoveHtmlComments         = true;
                options.MinificationSettings.MinifyInlineCssCode        = true;
                options.MinificationSettings.WhitespaceMinificationMode = WhitespaceMinificationMode.Aggressive;
                options.MinificationSettings.RemoveJsTypeAttributes     = true;
            });
            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
            });
            services
            .AddResponseCaching()
            .AddResponseCompression(options =>
            {
                options.Providers.Add <BrotliCompressionProvider>();
                options.Providers.Add <GzipCompressionProvider>();
                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "image/svg+xml" });
            });
            services.Configure <BrotliCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);
            services.Configure <GzipCompressionProviderOptions>(options => options.Level   = CompressionLevel.Optimal);

            services.AddScoped <AuthenticationTracker>();
            services.AddScoped <IUnitOfWork, ApplicationDbContext>();
            services.AddDistributedMemoryCache();
            services.AddTransient <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IActionContextAccessor, ActionContextAccessor>();

            services.AddRequiredServices();

            services.AddMiniProfiler(options =>
            {
                options.RouteBasePath            = "/profiler";
                options.SqlFormatter             = new StackExchange.Profiling.SqlFormatters.SqlServerFormatter();
                options.ResultsAuthorize         = request => !Program.DisableProfilingResults;
                options.TrackConnectionOpenClose = false;
            }).AddEntityFramework();
        }
        static async Task Main(string[] args)
        {
            try
            {
                EntityFrameworkProfiler.Initialize();

                var config = Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;
                config.CodeFirstOptions.UseNonUnicodeStrings = true;
                config.CodeFirstOptions.UseNonLobStrings     = true;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();
                EntityContext.ConnectionString = ComposeConnectionString(configuration);

                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var context = new EntityContext())
                    {
                        context.Database.EnsureDeleted();

                        context.Database.ExecuteSqlRaw(@"
CREATE TABLE CAR
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    COLOR       VARCHAR2 (50 CHAR) NOT NULL,
    OWNER_ID    NUMBER (19, 0)
)");
                        context.Database.ExecuteSqlRaw(@"
CREATE TABLE OWNER
(
    ID              NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    NAME            VARCHAR2 (50 CHAR) NOT NULL
)");

                        await context.SaveChangesAsync();
                    }

                    scope.Complete();
                }

                await using (var context = new EntityContext())
                {
                    // Create 3000 owners
                    var owners = Enumerable.Range(1, 3000).Select(_ => new Owner($"Owner {_}")).ToList();
                    context.AddRange(owners);
                    context.SaveChanges();

                    // Create the first car
                    var car1 = new Car("red", owners[0]);
                    context.Add(car1);

                    // Create the second car
                    var car2 = new Car("red", owners[600]);
                    context.Add(car2);

                    // Create the third car
                    var car3 = new Car("blue", owners[1000]);
                    context.Add(car3);

                    // Create the fourth car
                    var car4 = new Car("blue", owners[2000]);
                    context.Add(car4);

                    context.SaveChanges();

                    // This doesn't work, should return the first and second car
                    var carsOfSpecificOwnerWithRedColor = await context.Set <Car>()
                                                          .Where(_ => owners.Contains(_.Owner))
                                                          .Where(_ => _.Color == "red")
                                                          .ToArrayAsync();

                    foreach (var car in carsOfSpecificOwnerWithRedColor)
                    {
                        Console.WriteLine($"Found {car.Id}.");
                    }
                }

                Console.WriteLine("Finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
Ejemplo n.º 23
0
        static async Task Main(string[] args)
        {
            try
            {
                EntityFrameworkProfiler.Initialize();

                var config = Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;
                config.CodeFirstOptions.UseNonUnicodeStrings = true;
                config.CodeFirstOptions.UseNonLobStrings     = true;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();
                EntityContext.ConnectionString = ComposeConnectionString(configuration);

                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var context = new EntityContext())
                    {
                        context.Database.EnsureDeleted();

                        context.Database.ExecuteSqlRaw(@"
CREATE TABLE BEAST_RIDER
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    RIDER_NAME        VARCHAR2 (50 CHAR) NOT NULL,
    BEAST_NAME        VARCHAR2 (50 CHAR)
)");
                        context.Database.ExecuteSqlRaw(@"INSERT INTO BEAST_RIDER (RIDER_NAME) VALUES ('Khal Drogo')");

                        await context.SaveChangesAsync();
                    }

                    scope.Complete();
                }

                await using (var context = new EntityContext())
                {
                    // This works
                    var khalDrogo = await context.Set <BeastRider>()
                                    .FirstOrDefaultAsync(_ => _.Beast != null && _.Beast.Name == "Khal drogo");

                    // This fails with 'System.InvalidOperationException: Null TypeMapping in Sql Tree'
                    var khals = await context.Set <BeastRider>()
                                .Where(_ => _.Beast != null && _.Beast.Name.StartsWith("Khal"))
                                .ToArrayAsync();

                    Console.WriteLine($"Found {khals.Length} khals.");
                }

                Console.WriteLine("Finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
        static async Task Main(string[] args)
        {
            try
            {
                EntityFrameworkProfiler.Initialize();

                var config = Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;
                config.CodeFirstOptions.UseNonUnicodeStrings = true;
                config.CodeFirstOptions.UseNonLobStrings     = true;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();
                EntityContext.ConnectionString = ComposeConnectionString(configuration);

                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var context = new EntityContext())
                    {
                        context.Database.EnsureDeleted();

                        context.Database.ExecuteSqlCommand(@"
CREATE TABLE OTHER_RIDER
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    BEAST_NAME VARCHAR2 (50 CHAR) NOT NULL,
    BEAST_TYPE VARCHAR2 (50 CHAR) NOT NULL
)");

                        var otherBeast = new Beast("Viscerion", EquineBeast.Donkey);
                        var otherRider = new OtherBeastRider(otherBeast);
                        context.Add(otherRider);

                        await context.SaveChangesAsync();
                    }

                    scope.Complete();
                }

                using (var context = new EntityContext())
                {
                    var otherRider = context
                                     .Set <OtherBeastRider>()
                                     .FirstOrDefault(_ =>
                                                     _.Beast.Name == "Viscerion" ||          // Correctly translated to SQL
                                                     _.Beast.Name.StartsWith("Viscerion") || // ERROR ORA-00904: "_.Beast"."BEAST_NAME": invalid identifier
                                                     _.Beast.Name.Contains("Viscerion") ||   // ERROR ORA-00904: "_.Beast"."BEAST_NAME": invalid identifier
                                                     _.Beast.Name.EndsWith("Viscerion")      // ERROR ORA-00904: "_.Beast"."BEAST_NAME": invalid identifier
                                                     );
                }

                Console.WriteLine("Finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
Ejemplo n.º 25
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     EntityFrameworkProfiler.Initialize();
     services.AddMvc();
 }
        static async Task Main(string[] args)
        {
            try
            {
                EntityFrameworkProfiler.Initialize();

                var config = Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;
                config.CodeFirstOptions.UseNonUnicodeStrings = true;
                config.CodeFirstOptions.UseNonLobStrings     = true;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();
                EntityContext.ConnectionString = ComposeConnectionString(configuration);

                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var context = new EntityContext())
                    {
                        context.Database.EnsureDeleted();

                        context.Database.ExecuteSqlRaw(@"
CREATE TABLE BEAST_RIDER
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    NAME        VARCHAR2 (50 CHAR) NOT NULL,
    DISCRIMINATOR VARCHAR2 (50 CHAR) NOT NULL
)");

                        await context.SaveChangesAsync();
                    }

                    scope.Complete();
                }

                using (var context = new EntityContext())
                {
                    // Both methods of querying derived entities generate
                    // ... WHERE "b".DISCRIMINATOR = TO_NCLOB('BirdRider')
                    // resulting in 'ORA-00932: inconsistent datatypes: expected - got NCLOB'
                    var birdRider = context
                                    .Set <BirdRider>()
                                    .FirstOrDefault();

                    var beastRider = context
                                     .Set <BeastRider>()
                                     .FirstOrDefault(_ => _ is BirdRider);
                }

                Console.WriteLine("Finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
Ejemplo n.º 27
0
        public static void Main(string[] args)
        {
            EntityFrameworkProfiler.Initialize();

            IIocBuilder builder = IocBuilder.New
                                  .UseAutofacContainerBuilder()
                                  .UseStoveWithNullables(typeof(StoveMigratorBootstrapper))
                                  .UseStoveNLog()
                                  .UseStoveEntityFramework()
                                  .UseStoveMigrationParticipant()
                                  .UseStoveMigrator()
                                  .UseStoveMigratorDefaults();

            var options = new MigrationOptions();

            Parser.Default.ParseArguments(args, options);
            if (Parser.Default.ParseArguments(args, options))
            {
                if (options.Is(MigrationType.DbUp))
                {
                    Console.WriteLine("Selected Migration is only DbUp...");

                    builder.UseStoveDbUpMigrationStrategy();
                }
                else if (options.Is(MigrationType.DbContext))
                {
                    Console.WriteLine("Selected Migration is only DbContext...");

                    builder.UseStoveDbContextMigrationStrategy();
                }
                else if (options.Is(MigrationType.DbContextSeed))
                {
                    Console.WriteLine("Selected Migration is only DbContextSeed...");

                    builder.UseStoveDbContextSeedMigrationStrategy(configuration =>
                    {
                        configuration.Schema             = options.Schema;
                        configuration.Table              = options.Table;
                        configuration.TransactionTimeout = options.TransactionTimeout;
                        configuration.Enviroment         = options.Enviroment;
                        return(configuration);
                    });
                }
                else
                {
                    Console.WriteLine("Selected Migration is DbContext, DbUp and DbContextSeed...");

                    builder.UseStoveAllMigrationStrategies(configuration =>
                    {
                        configuration.Schema             = options.Schema;
                        configuration.Table              = options.Table;
                        configuration.TransactionTimeout = options.TransactionTimeout;
                        configuration.Enviroment         = options.Enviroment;
                        return(configuration);
                    });
                }
            }

            builder.RegisterServices(r => r.OnDisposing += (sender, eventArgs) => { Console.WriteLine("Stove.Migrator.Executer successfully executed and disposed."); });

            IRootResolver rootResolver = builder.CreateResolver();

            using (rootResolver)
            {
                var migrator = rootResolver.Resolve <MigrateExecuter>();
                migrator.Run();
            }

            Console.WriteLine("Press ENTER to exit...");

            Console.ReadLine();
        }
Ejemplo n.º 28
0
        static async Task Main(string[] args)
        {
            try
            {
                EntityFrameworkProfiler.Initialize();

                var config = Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;
                config.CodeFirstOptions.UseNonUnicodeStrings = true;
                config.CodeFirstOptions.UseNonLobStrings     = true;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();
                EntityContext.ConnectionString = ComposeConnectionString(configuration);

                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var context = new EntityContext())
                    {
                        context.Database.EnsureDeleted();
                        context.Database.ExecuteSqlCommand(@"
CREATE TABLE RIDER
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    BEAST_NAME VARCHAR2 (50 CHAR) NOT NULL,
    BEAST_TYPE VARCHAR2 (50 CHAR) NOT NULL,
    DISCRIMINATOR VARCHAR2 (50 CHAR) NOT NULL
)");

                        context.Database.ExecuteSqlCommand(@"
CREATE TABLE OTHER_RIDER
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    BEAST_NAME VARCHAR2 (50 CHAR) NOT NULL,
    BEAST_TYPE VARCHAR2 (50 CHAR) NOT NULL
)");

                        var beast = new Beast("Drogo", EquineBeast.Horse);
                        var rider = new BeastRider(beast);
                        context.Add(rider);

                        var otherBeast = new Beast("Viscerion", EquineBeast.Donkey);
                        var otherRider = new OtherBeastRider(otherBeast);
                        context.Add(otherRider);

                        await context.SaveChangesAsync();
                    }

                    scope.Complete();
                }

                using (var context = new EntityContext())
                {
                    // Works as expected, clean SQL
                    var otherRider = context.Set <OtherBeastRider>()
                                     .FirstOrDefault();

                    // Works, but generates unnecessary left join in SQL
                    var rider = context.Set <BeastRider>()
                                .FirstOrDefault();
                }

                Console.WriteLine("Finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
Ejemplo n.º 29
0
        static async Task Main(string[] args)
        {
            try
            {
                EntityFrameworkProfiler.Initialize();

                var config = Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;
                config.CodeFirstOptions.UseNonUnicodeStrings = true;
                config.CodeFirstOptions.UseNonLobStrings     = true;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();
                EntityContext.ConnectionString = ComposeConnectionString(configuration);

                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var context = new EntityContext())
                    {
                        context.Database.EnsureDeleted();
                        context.Database.ExecuteSqlCommand(@"
CREATE TABLE CLASSROOM
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    NAME        VARCHAR2(50 CHAR)
)");

                        context.Database.ExecuteSqlCommand(@"
CREATE TABLE PUZZLE_GROUP
(
    ID            NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    NAME        VARCHAR2(50 CHAR),
    CLASSROOM_ID  NUMBER (19, 0) NOT NULL
)");

                        context.Database.ExecuteSqlCommand(@"
CREATE TABLE PUZZLE
(
    ID              NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    PUZZLE_GROUP_ID NUMBER (19, 0) NOT NULL,
    COMPLETED       NUMBER (1, 0) NOT NULL
)");

                        var classroom    = new Classroom("test");
                        var puzzleGroup1 = new PuzzleGroup(classroom, "group1");
                        var puzzleGroup2 = new PuzzleGroup(classroom, "group2");

                        var puzzle1 = new Puzzle(puzzleGroup1, true);
                        var puzzle2 = new Puzzle(puzzleGroup1, true);
                        var puzzle3 = new Puzzle(puzzleGroup2, true);
                        var puzzle4 = new Puzzle(puzzleGroup2, false);

                        context.Add(classroom);
                        context.Add(puzzleGroup1);
                        context.Add(puzzleGroup2);
                        context.Add(puzzle1);
                        context.Add(puzzle2);
                        context.Add(puzzle3);
                        context.Add(puzzle4);
                        await context.SaveChangesAsync();
                    }

                    scope.Complete();
                }

                using (var context = new EntityContext())
                {
                    // This works
                    var classroomResult1 = context
                                           .Set <Classroom>()
                                           .FirstOrDefault(_ => _.PuzzleGroups.All(gr => gr.Puzzles.Any(p => !p.Completed)));

                    // This doesn't - throws ORA-00936: missing expression
                    var classroomResult2 = context
                                           .Set <Classroom>()
                                           .FirstOrDefault(_ => _.PuzzleGroups.All(gr => !gr.Puzzles.All(p => p.Completed)));
                }

                Console.WriteLine("Finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
Ejemplo n.º 30
0
        static async Task Main(string[] args)
        {
            try
            {
                EntityFrameworkProfiler.Initialize();

                var config = Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;
                config.CodeFirstOptions.UseNonUnicodeStrings = true;
                config.CodeFirstOptions.UseNonLobStrings     = true;

                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true);
                var configuration = builder.Build();
                EntityContext.ConnectionString = ComposeConnectionString(configuration);

                using (var scope = new TransactionScope(
                           TransactionScopeOption.Required,
                           new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var context = new EntityContext())
                    {
                        context.Database.EnsureDeleted();

                        context.Database.ExecuteSqlRaw(@"
CREATE TABLE BEAST_RIDER
(
    ID          NUMBER (19, 0) GENERATED ALWAYS AS IDENTITY NOT NULL,
    RIDER_NAME        VARCHAR2 (50 CHAR) NOT NULL,
    BEAST_TYPE        VARCHAR2 (50 CHAR) NOT NULL
)");
                        context.Database.ExecuteSqlRaw(@"INSERT INTO BEAST_RIDER (RIDER_NAME, BEAST_TYPE) VALUES ('Khal Drogo', 'Unicorn')");

                        await context.SaveChangesAsync();
                    }

                    scope.Complete();
                }

                await using (var context = new EntityContext())
                {
                    // Throws System.InvalidOperationException:
                    // No coercion operator is defined between types 'System.String' and 'devart_efcore_3_value_conversion_bug.EquineBeast'.
                    var unicornRiders = await context.Set <BeastRider>()
                                        .Where(_ => _.Beast == EquineBeast.Unicorn)
                                        .ToArrayAsync();

                    Console.WriteLine($"Found {unicornRiders.Length} unicorn riders.");
                }

                Console.WriteLine("Finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }