Esempio n. 1
0
        public MyDbContext()
            : base("name=MyDbContext")
        {
            // 下面这句为 拦截的处理.
#if DEBUG
            DbInterception.Add(new EFIntercepterLogging());
#endif
        }
Esempio n. 2
0
 protected void Application_Start()
 {
     //ModelBinderProviders.BinderProviders.Clear();
     //ModelBinderProviders.BinderProviders.Insert(0, new DecipfilterModelBinderProvider());
     GlobalConfiguration.Configure(WebApiConfig.Register);
     log4net.Config.XmlConfigurator.Configure();
     DbInterception.Add(new CustomEFInterceptor());
 }
Esempio n. 3
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     DbInterception.Add(new SchoolInterceptorTransientErrors()); DbInterception.Add(new SchoolInterceptorLogging());
 }
 public CarsContext(DbConnection connection)
     : base(connection, false)
 {
     _dbInterceptor     = new DbCommandInterceptor();
     _dbTreeInterceptor = new DbCommandTreeInterceptor();
     DbInterception.Add(_dbInterceptor);
     DbInterception.Add(_dbTreeInterceptor);
 }
        /// <summary>
        /// Adds an instance of <see cref="SentryCommandInterceptor"/> to <see cref="DbInterception"/>
        /// This is a static setup call, so make sure you only call it once for each <see cref="IQueryLogger"/> instance you want to register globally
        /// </summary>
        /// <param name="logger"></param>
        public static SentryCommandInterceptor UseBreadcrumbs(IQueryLogger logger = null)
        {
            logger = logger ?? new SentryQueryLogger();
            var interceptor = new SentryCommandInterceptor(logger);

            DbInterception.Add(interceptor);
            return(interceptor);
        }
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     DbInterception.Add(new DatabaseInterceptingLogging());
 }
Esempio n. 7
0
 private static void AttacheInterception()
 {
     if (_CountDbInterception == 0)
     {
         DbInterception.Add(ftsExtension);
     }
     _CountDbInterception++;
 }
Esempio n. 8
0
        /// <summary>
        /// 初始化一个<see cref="DbContextBase{TDbContext}"/>类型的新实例
        /// </summary>
        protected DbContextBase()
            : base(GetConnectionStringName())
        {
            //监听数据库sql 语句
#if DEBUG
            DbInterception.Add(new EFIntercepterLogging());
#endif
        }
Esempio n. 9
0
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

            //IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
            //Database.SetInitializer<MaoDbContext>(null);
            DbInterception.Add(new EFIntercepterLogging());
        }
 public MyDataDAO()
 {
     if (!isDbInterceptionInitialised)
     {
         DbInterception.Add(new InsertUpdateInterceptor());
         isDbInterceptionInitialised = true;
     }
 }
Esempio n. 11
0
 private void ConfigureLog()
 {
     if (LogConfig.DbLogger.IsActive)
     {
         DatabaseLogger.StartLogging();
         DbInterception.Add(DatabaseLogger);
     }
 }
Esempio n. 12
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);


            DbInterception.Add(new SchoolInterceptorTransientErrors());
            DbInterception.Add(new SchoolInterceptorLogging());
        }
        public FbProviderServices()
        {
#if EF6
            AddDependencyResolver(new SingletonDependencyResolver <IDbConnectionFactory>(new FbConnectionFactory()));
            AddDependencyResolver(new SingletonDependencyResolver <Func <MigrationSqlGenerator> >(() => new FbMigrationSqlGenerator(), ProviderInvariantName));
            DbInterception.Add(new FbMigrationsTransactionsInterceptor());
#endif
        }
Esempio n. 14
0
 /// <summary>
 /// Starts logging all EF SQL Calls to the Debug Output Window as T-SQL Blocks
 /// </summary>
 /// <param name="dbContext">The database context.</param>
 public static void SQLLoggingStart(System.Data.Entity.DbContext dbContext)
 {
     _callCounts  = 0;
     _callMSTotal = 0.00;
     SQLLoggingStop();
     _debugLoggingDbCommandInterceptor.DbContextList.Add(dbContext);
     DbInterception.Add(_debugLoggingDbCommandInterceptor);
 }
Esempio n. 15
0
        /// <summary>
        /// Get Entity queryable
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public IQueryable <TEntity> GetQueryNoLock <TEntity>() where TEntity : class
        {
            EFDbContext dbContext = GetEFDbContext <TEntity>();

            NoLockInterceptor.ApplyNoLock = true;
            DbInterception.Add(new NoLockInterceptor());
            return(dbContext.Set <TEntity>());
        }
Esempio n. 16
0
        public ApplicationInstance()
        {
            Container = new UnityContainer();
            Container.AddNewExtension <ExampleContainerExtension>();

            //Adicionar interceptor UTC
            DbInterception.Add(new UtcDbCommandInterceptor());
        }
        public CustomDbConfig()
        {
            //SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());

            //interception
            DbInterception.Add(new DbInterceptorLogging());
            SetDatabaseLogFormatter((context, writeAction) => new OneLineFormatter(context, writeAction));
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            DbInterception.Add(new LogFormatter());

            RunEntity();
            //RunAdoNet();
            Console.ReadLine();
        }
Esempio n. 19
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app)
 {
     //由于.Net Core默认只会从wwwroot目录加载静态文件,其他文件夹的静态文件无法正常访问。
     //而我们希望将图片上传到网站根目录的upload文件夹下,所以需要额外在Startup.cs类的Configure方法中
     //string resource = Path.Combine(Directory.GetCurrentDirectory(), "upload");
     //if (!FileHelper.IsExistDirectory(resource))
     //{
     //    FileHelper.CreateFolder(resource);
     //}
     //app.UseStaticFiles(new StaticFileOptions
     //{
     //    FileProvider = new PhysicalFileProvider(resource),
     //    RequestPath = "/upload",
     //    OnPrepareResponse = ctx =>
     //    {
     //        ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=36000");
     //    }
     //});
     //虚拟目录
     //如需使用,所有URL修改,例:"/Home/Index"改成'@Url.Content("~/Home/Index")',部署访问首页必须带虚拟目录;
     //if (!string.IsNullOrEmpty(GlobalContext.SystemConfig.VirtualDirectory))
     //{
     //    app.UsePathBase(new PathString(GlobalContext.SystemConfig.VirtualDirectory)); // 让 Pathbase 中间件成为第一个处理请求的中间件, 才能正确的模拟虚拟路径
     //}
     //实时通讯跨域
     app.UseCors("CorsPolicy");
     if (WebHostEnvironment.IsDevelopment())
     {
         //打印sql
         IDbCommandInterceptor interceptor = new DbCommandInterceptor();
         DbInterception.Add(interceptor);
         GlobalContext.SystemConfig.Debug = true;
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseExceptionHandler("/Home/Error?msg=404");
     }
     //文件地址Resource
     //静态资源wwwroot
     app.UseStaticFiles(new StaticFileOptions
     {
         ContentTypeProvider = new CustomerFileExtensionContentTypeProvider(),
         OnPrepareResponse   = GlobalContext.SetCacheControl
     });
     //session
     app.UseSession();
     //路径
     app.UseRouting();
     //MVC路由
     app.UseEndpoints(endpoints =>
     {
         endpoints.MapHub <MessageHub>("/chatHub");
         endpoints.MapControllerRoute("areas", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
         endpoints.MapControllerRoute("default", "{controller=Login}/{action=Index}/{id?}");
     });
     GlobalContext.ServiceProvider = app.ApplicationServices;
 }
    public Configuration2()
    {
        DbConfiguration.SetConfiguration(new DbConfigurationBase("SQLCE"));

        DbInterception.Add(new NLogCommandInterceptor());        // guardar logs

        AutomaticMigrationsEnabled        = true;
        AutomaticMigrationDataLossAllowed = true;
    }
Esempio n. 21
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.Configuration.LazyLoadingEnabled = true;

            this.ModelConfiguration(modelBuilder);
            // this.DetermineTables(modelBuilder);
            DbInterception.Add(new MZLogCommandInterceptor());
            base.OnModelCreating(modelBuilder);
        }
Esempio n. 22
0
        static DefaultContext()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <DefaultContext, Migrations.Default.Configuration>());
            //Database.SetInitializer<DefaultContext>(null);

#if DEBUG
            DbInterception.Add(new EFIntercepterLogging());
#endif
        }
Esempio n. 23
0
 protected void Application_Start()
 {
     // Database.SetInitializer(new SchoolInitializer());
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     DbInterception.Add(new SchoolInterceptorLogging());
 }
Esempio n. 24
0
        public static void Initialize(ICache cache, CachingPolicy cachingPolicy)
        {
            var transactionHandler = new CacheTransactionHandler(cache);

            DbConfiguration.Loaded +=
                (sender, args) => args.ReplaceService <DbProviderServices>(
                    (dbServices, _) => new CachingProviderServices(dbServices, transactionHandler, cachingPolicy));
            DbInterception.Add(transactionHandler);
        }
Esempio n. 25
0
        private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
            Action <BlogContextCommit> runAndVerify)
        {
            var failingTransactionInterceptorMock = new Mock <FailingTransactionInterceptor> {
                CallBase = true
            };
            var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;

            DbInterception.Add(failingTransactionInterceptor);

            MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(
                key =>
                (Func <IDbExecutionStrategy>)
                    (() => new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));

            try
            {
                using (var context = new BlogContextCommit())
                {
                    failingTransactionInterceptor.ShouldFailTimes = 0;
                    context.Database.Delete();
                    Assert.Equal(1, context.Blogs.Count());

                    failingTransactionInterceptor.ShouldFailTimes = 2;
                    failingTransactionInterceptor.ShouldRollBack  = false;

                    context.Blogs.Add(new BlogContext.Blog());

                    runAndVerify(context);

                    failingTransactionInterceptorMock.Verify(
                        m => m.Committing(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext>()), Times.Exactly(3));
                }

                using (var context = new BlogContextCommit())
                {
                    Assert.Equal(2, context.Blogs.Count());

                    using (var transactionContext = new TransactionContext(context.Database.Connection))
                    {
                        using (var infoContext = GetInfoContext(transactionContext))
                        {
                            Assert.True(
                                !infoContext.TableExists("__Transactions") ||
                                !transactionContext.Transactions.Any());
                        }
                    }
                }
            }
            finally
            {
                DbInterception.Remove(failingTransactionInterceptorMock.Object);
                MutableResolver.ClearResolvers();
            }

            DbDispatchersHelpers.AssertNoInterceptors();
        }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Registers and configures it first.
        DbInterception.Add(new FilterInterceptor());
        var softDeleteFilter = FilterConvention.Create <BaseEntity>("SoftDelete",
                                                                    e => e.IsDeleted == false); // don't change it into e => !e.IsDeleted

        modelBuilder.Conventions.Add(softDeleteFilter);
    }
Esempio n. 27
0
        private void Init()
        {
            this.Configuration.LazyLoadingEnabled = true;
            Database
            .SetInitializer <ADAContext>
                (new MigrateDatabaseToLatestVersion <ADAContext, ADA.Data.Migrations.Configuration>(true));

            DbInterception.Add(new FtsInterceptor(_iFTSStringProvider));
        }
Esempio n. 28
0
            public void DbDeleteDatabase_dispatches_commands_to_interceptors_for_connections_without_initial_catalog()
            {
                StoreItemCollection storeItemCollection;

                using (var context = new DdlDatabaseContext())
                {
                    storeItemCollection =
                        (StoreItemCollection)
                        ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);
                }

                using (var connection = new SqlConnection(SimpleAttachConnectionString <DdlDatabaseContext>(useInitialCatalog: false)))
                {
                    var nonQueryInterceptor = new TestNonQueryInterceptor();
                    var readerInterceptor   = new TestReaderInterceptor();

                    // See CodePlex 1554 - Handle User Instance flakiness
                    MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(new ExecutionStrategyResolver <IDbExecutionStrategy>(
                                                                                   SqlProviderServices.ProviderInvariantName, null, () => new SqlAzureExecutionStrategy()));
                    try
                    {
                        if (!SqlProviderServices.Instance.DatabaseExists(connection, null, storeItemCollection))
                        {
                            SqlProviderServices.Instance.CreateDatabase(connection, null, storeItemCollection);
                        }

                        DbInterception.Add(nonQueryInterceptor);
                        DbInterception.Add(readerInterceptor);
                        try
                        {
                            SqlProviderServices.Instance.DeleteDatabase(connection, null, storeItemCollection);
                        }
                        finally
                        {
                            DbInterception.Remove(nonQueryInterceptor);
                            DbInterception.Remove(readerInterceptor);
                        }
                    }
                    finally
                    {
                        MutableResolver.ClearResolvers();
                    }

                    Assert.Equal(2, nonQueryInterceptor.Commands.Count);

                    var commandTexts = nonQueryInterceptor.Commands.Select(c => c.CommandText);
                    Assert.True(commandTexts.Any(t => t.StartsWith("drop database [SYSTEM_DATA_ENTITY_SQLSERVER")));
                    Assert.True(
                        commandTexts.Any(t => t.Contains("SYSTEM.DATA.ENTITY.SQLSERVER.SQLPROVIDERSERVICESTESTS+DDLDATABASECONTEXT.MDF")));

                    Assert.Equal(1, readerInterceptor.Commands.Count);

                    Assert.True(
                        readerInterceptor.Commands.Select(
                            c => c.CommandText).Single().StartsWith("SELECT [d].[name] FROM sys.databases "));
                }
            }
Esempio n. 29
0
        /// <summary>
        /// BlogConfiguration's default constructor, setting DB related configurations
        /// </summary>
        public BlogConfiguration()
        {
            // Setting up the SQL DB execution strategy (A.K.A. the retry policy)
            SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());

            // These were already added in the Global.asax file but can be added here also
            //DbInterception.Add(new BlogInterceptorTransientErrors());
            DbInterception.Add(new BlogInterceptorLogging());
        }
Esempio n. 30
0
        /// <summary>
        /// Carga los Mapper en el ModelBuilder
        /// </summary>
        /// <remarks>
        /// Añadir todos los Mapper del proyecto
        /// </remarks>
        /// <param name="modelBuilder">Modelo de BD</param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove <OneToManyCascadeDeleteConvention>();

            modelBuilder.Configurations.Add(new RuleMap());
            modelBuilder.Configurations.Add(new RuleTypeMap());

            DbInterception.Add(new FilterInterceptor());
        }