protected HistoryOperation CreateInsertOperation( string contextKey, string migrationId, XDocument model, string productVersion = null) { using (var connection = ProviderFactory.CreateConnection()) { connection.ConnectionString = ConnectionString; using (var historyContext = new HistoryContext(connection, "dbo")) { historyContext.History.Add( new HistoryRow { MigrationId = migrationId, ContextKey = contextKey, Model = CompressModel(model), ProductVersion = productVersion ?? typeof(DbContext).Assembly() .GetCustomAttributes <AssemblyInformationalVersionAttribute>() .Single() .InformationalVersion, }); var cancellingLogger = new CommandTreeCancellingLogger(historyContext); DbInterception.Add(cancellingLogger); try { historyContext.SaveChanges(); return(new HistoryOperation( cancellingLogger.Log.OfType <DbModificationCommandTree>().ToList())); } finally { DbInterception.Remove(cancellingLogger); } } } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); //WebApiConfig.Register(GlobalConfiguration.Configuration); GlobalConfiguration.Configure(WebApiConfig.Register); //https://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/ ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder()); ModelBinders.Binders.Add(typeof(int), new IntegerModelBinder()); //https://stackoverflow.com/questions/793459/how-to-set-decimal-separators-in-asp-net-mvc-controllers //ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); //ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder()); //https://blog.murilogomes.com/2015/03/24/globalizing-datetime-and-decimal-in-asp-net-mvc-using-modelbinder/ //System.Web.Mvc.ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); //ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); //ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder()); DependenciesConfig.RegisterDependencies(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DbConfiguration.SetConfiguration(new ProductQuoteApp.Persistence.ProductQuoteAppConfiguration()); //Para los mensaje de error se muestren en el idioma correcto dependiendo de Culture. ClientDataTypeModelValidatorProvider.ResourceClassKey = "Messages"; DefaultModelBinder.ResourceClassKey = "Messages"; DbInterception.Add(new ProductQuoteAppInterceptorLogging()); }
public static void Config() { // disable response header for protection attak MvcHandler.DisableMvcResponseHeader = true; // change captcha provider for using cookie CaptchaUtils.CaptchaManager.StorageProvider = new CookieStorageProvider(); //Set current Controller factory as StructureMapControllerFactory ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()); //set current Filter factory as StructureMapFitlerProvider var filterProider = FilterProviders.Providers.Single(p => p is FilterAttributeFilterProvider); FilterProviders.Providers.Remove(filterProider); FilterProviders.Providers.Add(ProjectObjectFactory.Container.GetInstance <StructureMapFilterProvider>()); Database.SetInitializer <ApplicationDbContext>(null); // Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>()); // ProjectObjectFactory.Container.GetInstance<IUnitOfWork>().ForceDatabaseInitialize(); var defaultJsonFactory = ValueProviderFactories.Factories .OfType <JsonValueProviderFactory>().FirstOrDefault(); var index = ValueProviderFactories.Factories.IndexOf(defaultJsonFactory); ValueProviderFactories.Factories.Remove(defaultJsonFactory); ValueProviderFactories.Factories.Insert(index, new JsonNetValueProviderFactory()); //ad interception for logg EF errors DbInterception.Add(new ElmahEfInterceptor()); foreach (var task in ProjectObjectFactory.Container.GetAllInstances <IRunAtInit>()) { task.Execute(); } Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver = ProjectObjectFactory.Container.GetInstance <Microsoft.AspNet.SignalR.IDependencyResolver>(); }
public void Async_commands_that_result_in_exceptions_are_still_intercepted() { var logger = new CommandLogger(); DbInterception.Add(logger); try { using (var context = new BlogContextNoInit()) { var query = context.Blogs.SqlQuery("select * from No.Chance").ToListAsync(); Assert.Throws <AggregateException>(() => query.Wait()); Assert.True(query.IsFaulted); } } finally { DbInterception.Remove(logger); } Assert.Equal(2, logger.Log.Count); var executingLog = logger.Log[0]; Assert.Equal(CommandMethod.ReaderExecuting, executingLog.Method); Assert.True(executingLog.IsAsync); Assert.Null(executingLog.Result); Assert.Null(executingLog.Exception); var executedLog = logger.Log[1]; Assert.Equal(CommandMethod.ReaderExecuted, executedLog.Method); Assert.True(executedLog.IsAsync); Assert.Null(executedLog.Result); Assert.IsType <SqlException>(executedLog.Exception); Assert.True(executedLog.TaskStatus.HasFlag(TaskStatus.Faulted)); }
// This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(IAppBuilder appBuilder) { var isDatabaseLoggingEnabled = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["EnableDatabaseLogging"]) && Convert.ToBoolean(ConfigurationManager.AppSettings["EnableDatabaseLogging"]); if (isDatabaseLoggingEnabled) { DbInterception.Add(new SchoolInterceptorLogging()); } // Configure Web API for self-host. var config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.DependencyResolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer()); appBuilder.UseWebApi(config); }
public void Static_method_dispatches_to_interceptors() { var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); var model = EdmModel.CreateStoreModel( new DbProviderInfo("System.Data.FakeSqlClient", "2008"), new SqlProviderManifest("2008")); var storeItemCollectionMock = new Mock <StoreItemCollection>(model) { CallBase = true }; var metadataWorkspaceMock = new Mock <MetadataWorkspace>(); metadataWorkspaceMock.Setup(m => m.GetItemCollection(DataSpace.SSpace)).Returns(storeItemCollectionMock.Object); var connectionMock = new Mock <DbConnection>(); var entityConnection = new EntityConnection( workspace: null, connection: connectionMock.Object, skipInitialization: true, entityConnectionOwnsStoreConnection: false); DbInterception.Add(dbConnectionInterceptorMock.Object); try { DbProviderServices.GetExecutionStrategy(entityConnection, metadataWorkspaceMock.Object); } finally { DbInterception.Remove(dbConnectionInterceptorMock.Object); } dbConnectionInterceptorMock.Verify( m => m.DataSourceGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.DataSourceGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); }
public void ExecuteSql_dispatches_commands_to_interceptors() { var mockCommand = new Mock <DbCommand>(); mockCommand.Setup(m => m.ExecuteNonQuery()).Returns(2013); var mockConnection = new Mock <DbConnection>(); mockConnection.Protected().Setup <DbCommand>("CreateDbCommand").Returns(mockCommand.Object); var mockTransaction = new Mock <DbTransaction>(); mockTransaction.Protected().Setup <DbConnection>("DbConnection").Returns(mockConnection.Object); var migrator = new DbMigrator(); var statement = new MigrationStatement { Sql = "Some Sql" }; var mockInterceptor = new Mock <DbCommandInterceptor> { CallBase = true }; DbInterception.Add(mockInterceptor.Object); try { migrator.ExecuteSql(mockTransaction.Object, statement, new DbInterceptionContext()); } finally { DbInterception.Remove(mockInterceptor.Object); } mockInterceptor.Verify(m => m.NonQueryExecuting(mockCommand.Object, It.IsAny <DbCommandInterceptionContext <int> >())); mockInterceptor.Verify(m => m.NonQueryExecuted(mockCommand.Object, It.IsAny <DbCommandInterceptionContext <int> >())); }
public void ConnectionKey_uses_interception() { using (var internalConnection = new LazyInternalConnection("NameNotInAppConfig")) { var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); DbInterception.Add(dbConnectionInterceptorMock.Object); try { Assert.False(String.IsNullOrWhiteSpace(internalConnection.ConnectionKey)); } finally { DbInterception.Remove(dbConnectionInterceptorMock.Object); } dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); XmlConfigurator.Configure(); Logger.Info("Starting WCB Web..."); //Database.SetInitializer<Repository>(null); Database.SetInitializer <Repository>(new RepositoryInitializer()); using (var db = new Repository()) { db.Database.Initialize(true); } DbInterception.Add(new CustomEFInterceptor()); ServicePointManager.UseNagleAlgorithm = false; ServicePointManager.DefaultConnectionLimit = 1000000; ServicePointManager.ServerCertificateValidationCallback += ServerCertificateValidationCallback;// += (sender, certificate, chain, errors) => errors == SslPolicyErrors.None && validCerts.Contains(certificate); }
public void DbDatabaseExists_dispatches_commands_to_interceptors_for_connections_with_initial_catalog() { var interceptor = new TestScalarInterceptor(); DbInterception.Add(interceptor); try { using (var connection = new SqlConnection(ModelHelpers.SimpleAttachConnectionString("I.Do.Not.Exist"))) { SqlProviderServices.Instance.DatabaseExists(connection, null, new StoreItemCollection()); } } finally { DbInterception.Remove(interceptor); } Assert.Equal(2, interceptor.Commands.Count); Assert.True( interceptor.Commands.Select(c => c.CommandText).All( t => t == "SELECT Count(*) FROM sys.databases WHERE [name]=N'I.Do.Not.Exist'")); }
public void Does_not_throw_ArgumentNullException_on_null_transaction() { DropDatabase(); using (var context = CreateContext <ShopContext_v1>()) { context.Database.Create(); } var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); dbConnectionInterceptorMock.Setup( m => m.BeginningTransaction(It.IsAny <DbConnection>(), It.IsAny <BeginTransactionInterceptionContext>())) .Callback <DbConnection, BeginTransactionInterceptionContext>( (c, b) => { b.Exception = new TimeoutException(); }); DbInterception.Add(dbConnectionInterceptorMock.Object); try { var migrator = CreateMigrator <ShopContext_v1>(); Assert.Throws <TimeoutException>(() => migrator.ExecuteStatements(Enumerable.Empty <MigrationStatement>())); dbConnectionInterceptorMock.Verify( m => m.BeginningTransaction(It.IsAny <DbConnection>(), It.IsAny <BeginTransactionInterceptionContext>()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.BeganTransaction(It.IsAny <DbConnection>(), It.IsAny <BeginTransactionInterceptionContext>()), Times.Once()); } finally { DbInterception.Remove(dbConnectionInterceptorMock.Object); } }
public void AnyModelTableExists_dispatches_to_interceptors() { var connectionMock = new Mock <DbConnection> { CallBase = true }; var internalContextMock = new Mock <InternalContext>(); var dbCommandMock = new Mock <DbCommand>(); var mockOperations = new Mock <DatabaseOperations>(); mockOperations.Setup(m => m.Exists(It.IsAny <ObjectContext>())).Returns(true); internalContextMock.Setup(m => m.DatabaseOperations).Returns(mockOperations.Object); SetupMocksForTableChecking(dbCommandMock, connectionMock, internalContextMock); var interceptorMock = new Mock <DbCommandInterceptor> { CallBase = true }; DbInterception.Add(interceptorMock.Object); try { new DatabaseTableChecker().AnyModelTableExists(internalContextMock.Object); } finally { DbInterception.Remove(interceptorMock.Object); } interceptorMock.Verify( m => m.ScalarExecuting( dbCommandMock.Object, It.Is <DbCommandInterceptionContext <object> >(c => c.ObjectContexts.Contains(internalContextMock.Object.ObjectContext)))); }
protected void Application_Start() { string newdb = ConfigurationManager.AppSettings["CreateDatabaseIfNotExists"].ToLower(); if (newdb == "true") { Database.SetInitializer <DbContextManager>(new InitializeDataForCreateDatabaseIfNotExists()); } else { Database.SetInitializer <DbContextManager>(null); } //initialize engine context EngineContext.Initialize(false); //NopEngine ne = new NopEngine(); //ne.Initialize(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AutoMapperConfig.RegisterObjects(); //RegisterCache("Heartbeat"); currentDate = DateTime.Now.Date; //JobQueue.Add(new UARCJob() { Frequency = JobFrequency.EveryDay }); //JobQueue.Add(new UARCUserJob { Frequency = JobFrequency.Immediately }); //DbInterception.Add(new Log4NetInterceptor()); //MiniProfilerEF6.Initialize(); Log4Helper.Initialize(Server.MapPath("log4net.config")); //注册数据库操作拦截器类 DbInterception.Add(new LogEFMonitor()); }
public void QueryForModelHash_uses_interception() { var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); DbInterception.Add(dbConnectionInterceptorMock.Object); try { var mockContext = CreateMockContext("Hash"); var repository = new EdmMetadataRepository(Mock.Of <InternalContextForMock>(), "Database=Foo", SqlClientFactory.Instance); repository.QueryForModelHash(c => mockContext.Object); } finally { DbInterception.Remove(dbConnectionInterceptorMock.Object); } dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); }
public void Uses_interception() { var transactionMock = new Mock <DbTransaction>(); var transaction = new EntityTransaction(new EntityConnection(), transactionMock.Object); var transactionInterceptorMock = new Mock <IDbTransactionInterceptor>(); DbInterception.Add(transactionInterceptorMock.Object); try { transaction.Dispose(); } finally { DbInterception.Remove(transactionInterceptorMock.Object); } transactionInterceptorMock.Verify( m => m.Disposing(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext>()), Times.Once()); transactionInterceptorMock.Verify( m => m.Disposed(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext>()), Times.Once()); transactionMock.Protected().Verify("Dispose", Times.Once(), ItExpr.IsAny <bool>()); }
//protected override void Dispose(bool disposing) //{ // _writer?.Close(); // _writer?.Dispose(); // _fileStream?.Close(); // _fileStream?.Dispose(); // base.Dispose(disposing); //} protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Types().Configure(c => c.Ignore("IsDirty")); modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); //modelBuilder.Configurations.AddFromAssembly(typeof(DataContext).Assembly); DbInterception.Add(new FilterInterceptor()); modelBuilder.Entity <Product>().Property(p => p.Description).HasMaxLength(4000); modelBuilder.Properties <Guid>().Where(p => p.Name == "Key").Configure(c => c.IsKey()); modelBuilder.Entity <Customer>() .Property(c => c.CustomerName) .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("Idx_History.Customers.Customer_Name", 2))); modelBuilder.Conventions.AddFromAssembly(typeof(ModelConventionsContext).Assembly); modelBuilder.HasDefaultSchema("AnythingsBut_dbo"); base.OnModelCreating(modelBuilder); }
public void TestTasks() { DbInterception.Add(new HintInterceptor()); using (var userContext = new UserContext()) { userContext.Database.Initialize(true); } using (var test = new TaskContext()) { test.Database.Initialize(true); } using (var db = new GenericContext()) { using (var qh = new HintScope("HASH JOIN")) { var tasks = db.Set <Task>().Include(t => t.User).Where(t => db.Set <User>(). Where(UserExpressions.UserByGroups(1)).Any(u => u.Id == t.UserId)); var testarr = tasks.ToArray(); Assert.AreEqual(4, testarr.Length); } } }
/// <summary> /// 1.Add HttpOutDiagnosticListenerNetframework, EntityFramework and Sql tracing handler for tracing Http outgping request and Sql query. /// 2.Register XRay for AWS services /// </summary> internal static void Initialize(XRayAutoInstrumentationOptions options) { if (options.TraceHttpRequests) { DiagnosticListenerBase[] subscriptions = { new HttpOutDiagnosticListenerNetframework() }; DiagnosticListener.AllListeners.Subscribe(new DiagnosticListenerObserver(subscriptions)); } if (options.TraceSqlRequests) { _ = new SqlEventListener(); } if (options.TraceEFRequests) { DbInterception.Add(new EntityFrameworkHandler()); } if (options.TraceAWSRequests) { AWSSDKRequestRegister.Register(); } }
public void Uses_interception() { var transactionMock = new Mock <DbTransaction>(); var transaction = new EntityTransaction(new EntityConnection(), transactionMock.Object); var transactionInterceptorMock = new Mock <IDbTransactionInterceptor>(); DbInterception.Add(transactionInterceptorMock.Object); try { Assert.Equal((IsolationLevel)0, transaction.IsolationLevel); } finally { DbInterception.Remove(transactionInterceptorMock.Object); } transactionInterceptorMock.Verify( m => m.IsolationLevelGetting(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext <IsolationLevel> >()), Times.Once()); transactionInterceptorMock.Verify( m => m.IsolationLevelGot(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext <IsolationLevel> >()), Times.Once()); transactionMock.Verify(m => m.IsolationLevel, Times.Once()); }
public void DbDatabaseExists_dispatches_to_interceptors() { var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); DbInterception.Add(dbConnectionInterceptorMock.Object); try { using (var connection = new SqlCeConnection(ModelHelpers.SimpleCeConnectionString("I.Do.Not.Exist"))) { Assert.False(SqlCeProviderServices.Instance.DatabaseExists(connection, null, new Lazy <StoreItemCollection>())); } } finally { DbInterception.Remove(dbConnectionInterceptorMock.Object); } dbConnectionInterceptorMock.Verify( m => m.DataSourceGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.DataSourceGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); }
public void Commands_that_result_in_exceptions_are_still_intercepted() { var logger = new CommandLogger(); DbInterception.Add(logger); Exception exception; try { using (var context = new BlogContextNoInit()) { exception = Assert.Throws <SqlException>(() => context.Blogs.SqlQuery("select * from No.Chance").ToList()); } } finally { DbInterception.Remove(logger); } Assert.Equal(2, logger.Log.Count); var executingLog = logger.Log[0]; Assert.Equal(CommandMethod.ReaderExecuting, executingLog.Method); Assert.False(executingLog.IsAsync); Assert.Null(executingLog.Result); Assert.Null(executingLog.Exception); var executedLog = logger.Log[1]; Assert.Equal(CommandMethod.ReaderExecuted, executedLog.Method); Assert.False(executedLog.IsAsync); Assert.Null(executedLog.Result); Assert.Same(exception, executedLog.Exception); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Below being used for Unity DI Bootstrapper.Initialise(); // Used to create Blob container if one does not already exist FileRepository fileRepository = new FileRepository(new UnitOfWork(), new Logger()); fileRepository.CreateAndConfigureAsync(); /* * The 2 lines below cause the interceptor code to be run when EF sends queries to the DB and they * can be independently enabled and disabled since separate interceptor classes for transient error simulation and * logging were created * DbInterception.Add method can be anywhere in the code, not just Application_Start. It can be placed * in the DbConfiguration class used to configure the execution policy. */ //DbInterception.Add(new BlogInterceptorTransientErrors()); DbInterception.Add(new BlogInterceptorLogging()); }
protected void Application_Start() { try { System.Web.Mvc.ModelBinders.Binders.Add(typeof(decimal?), new DecimalBinder()); System.Web.Mvc.ModelBinders.Binders.Add(typeof(DateTime), new PersianDateModelBinder()); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AutoMapperConfig.Config(); //Database.SetInitializer<ApplicationDbContext>(null); Database.SetInitializer(new MigrateDatabaseToLatestVersion <ApplicationDbContext, DataLayer.Migrations.Configuration>()); DbInterception.Add(new YeKeInterceptor()); ScheduledTasksRegistry.Init(); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); MvcHandler.DisableMvcResponseHeader = true; } catch { HttpRuntime.UnloadAppDomain(); // سبب ری استارت برنامه و آغاز مجدد آن با درخواست بعدی میشود throw; } }
public XXXEntities(bool isLog) : base("name=XXXEntities") { DbInterception.Add(new EFIntercepterLogging()); }
public override void Dispose() { DbInterception.Remove(_dbInterceptor); DbInterception.Remove(_dbTreeInterceptor); }
public void DbDatabaseExists_dispatches_commands_to_interceptors_for_connections_with_initial_catalog() { var interceptor = new TestScalarInterceptor(); DbInterception.Add(interceptor); var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); DbInterception.Add(dbConnectionInterceptorMock.Object); try { using (var connection = new SqlConnection(ModelHelpers.SimpleAttachConnectionString("I.Do.Not.Exist"))) { SqlProviderServices.Instance.DatabaseExists(connection, null, new StoreItemCollection()); } } finally { DbInterception.Remove(interceptor); DbInterception.Remove(dbConnectionInterceptorMock.Object); } Assert.Equal(2, interceptor.Commands.Count); Assert.True( interceptor.Commands.Select(c => c.CommandText).All( t => t == "IF db_id(N'I.Do.Not.Exist') IS NOT NULL SELECT 1 ELSE SELECT Count(*) FROM sys.databases WHERE [name]=N'I.Do.Not.Exist'")); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(11)); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(11)); dbConnectionInterceptorMock.Verify( m => m.StateGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()), Times.Exactly(8)); dbConnectionInterceptorMock.Verify( m => m.StateGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()), Times.Exactly(8)); dbConnectionInterceptorMock.Verify( m => m.DataSourceGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.DataSourceGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.ServerVersionGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(0)); dbConnectionInterceptorMock.Verify( m => m.ServerVersionGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(0)); dbConnectionInterceptorMock.Verify( m => m.Opening(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.Opened(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.Closing(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(2)); dbConnectionInterceptorMock.Verify( m => m.Closed(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(2)); }
static WorldwideContext() { DbInterception.Add(new FtsInterceptor()); }
public void DbDeleteDatabase_dispatches_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(); var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); // 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); DbInterception.Add(dbConnectionInterceptorMock.Object); try { SqlProviderServices.Instance.DeleteDatabase(connection, null, storeItemCollection); } finally { DbInterception.Remove(nonQueryInterceptor); DbInterception.Remove(readerInterceptor); DbInterception.Remove(dbConnectionInterceptorMock.Object); } } 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 ")); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(13)); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(13)); dbConnectionInterceptorMock.Verify( m => m.StateGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()), Times.Exactly(9)); dbConnectionInterceptorMock.Verify( m => m.StateGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()), Times.Exactly(9)); dbConnectionInterceptorMock.Verify( m => m.DataSourceGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.DataSourceGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.ServerVersionGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.ServerVersionGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.Opening(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.Opened(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.Closing(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.Closed(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(3)); } }
public void DbDeleteDatabase_dispatches_to_interceptors_for_connections_with_initial_catalog() { using (var context = new DdlDatabaseContext()) { context.Database.CreateIfNotExists(); } var interceptor = new TestNonQueryInterceptor(); DbInterception.Add(interceptor); var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); DbInterception.Add(dbConnectionInterceptorMock.Object); try { using (var connection = new SqlConnection(SimpleAttachConnectionString <DdlDatabaseContext>())) { SqlProviderServices.Instance.DeleteDatabase(connection, null, new StoreItemCollection()); } } finally { DbInterception.Remove(interceptor); DbInterception.Remove(dbConnectionInterceptorMock.Object); } Assert.Equal(1, interceptor.Commands.Count); Assert.Equal( "drop database [System.Data.Entity.SqlServer.SqlProviderServicesTests+DdlDatabaseContext]", interceptor.Commands.Select(c => c.CommandText).Single()); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(5)); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(5)); dbConnectionInterceptorMock.Verify( m => m.StateGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.StateGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()), Times.Exactly(3)); dbConnectionInterceptorMock.Verify( m => m.DataSourceGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.DataSourceGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.Opening(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.Opened(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.Closing(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.Closed(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Once()); }
public void DbDatabaseExists_dispatches_commands_to_interceptors_for_connections_with_no_initial_catalog() { // See CodePlex 1554 - Handle User Instance flakiness MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(new ExecutionStrategyResolver <IDbExecutionStrategy>( SqlProviderServices.ProviderInvariantName, null, () => new SqlAzureExecutionStrategy())); var interceptor = new TestScalarInterceptor(); DbInterception.Add(interceptor); var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>(); DbInterception.Add(dbConnectionInterceptorMock.Object); try { using (var connection = new SqlConnection(ModelHelpers.SimpleAttachConnectionString("I.Do.Not.Exist", useInitialCatalog: false))) { SqlProviderServices.Instance.DatabaseExists(connection, null, new StoreItemCollection()); } } finally { MutableResolver.ClearResolvers(); DbInterception.Remove(interceptor); DbInterception.Remove(dbConnectionInterceptorMock.Object); } Assert.Equal(1, interceptor.Commands.Count); Assert.True( interceptor.Commands.Select(c => c.CommandText) .Single() .StartsWith("SELECT Count(*) FROM sys.master_files WHERE [physical_name]=N'")); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(7)); dbConnectionInterceptorMock.Verify( m => m.ConnectionStringGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(7)); dbConnectionInterceptorMock.Verify( m => m.StateGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()), Times.Exactly(5)); dbConnectionInterceptorMock.Verify( m => m.StateGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()), Times.Exactly(5)); dbConnectionInterceptorMock.Verify( m => m.DataSourceGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(2)); dbConnectionInterceptorMock.Verify( m => m.DataSourceGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Exactly(2)); dbConnectionInterceptorMock.Verify( m => m.ServerVersionGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.ServerVersionGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.Opening(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(2)); dbConnectionInterceptorMock.Verify( m => m.Opened(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Exactly(2)); dbConnectionInterceptorMock.Verify( m => m.Closing(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Once()); dbConnectionInterceptorMock.Verify( m => m.Closed(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()), Times.Once()); }