public static void ConfigureSlimApi(HttpConfiguration config, EntityApp app) { var actionSelector = new SlimApiActionSelector(app.ApiConfiguration); config.Services.Replace(typeof(System.Web.Http.Controllers.IHttpActionSelector), actionSelector); var prov = new SlimApiDirectRouteProvider(); config.MapHttpAttributeRoutes(prov); // config.ParameterBindingRules.Add(typeof(DateTime), p => new DateTimeParameterBinding(p)); }
public EntityApp Build(DbFirstConfig config) { _config = config; _app = new EntityApp(); var log = new ActivationLog(_app.ActivationLogPath); _dbSettings = new DbSettings(_config.Driver, config.Driver.GetDefaultOptions(), _config.ConnectionString); // create loader and setup filter var modelLoader = _config.Driver.CreateDbModelLoader(_dbSettings, log); modelLoader.SetSchemasSubset(_config.Schemas); //actually load model _dbModel = modelLoader.LoadModel(); Util.Check(_dbModel.Tables.Count() > 0, "No tables found in the database. Code generation aborted."); // Prepare type generator _tempNamespace = "_dummy_" + _callCount++; // artificial unique namespace for dummy interface types // Construct model setup and model GenerateModulesAndAreas(); _entityModel = new EntityModel(_app); // EntityModelBuilder.SetModel(_app, _entityModel); //generate entities and members GenerateEntities(); SetupPrimaryKeys(); GenerateReferenceMembers(); CreateIndexes(); SetupKeyMembers(); return(_app); }
// constructors public Database(EntityApp app, DbSettings settings) { _app = app; Settings = settings; _driver = Settings.ModelConfig.Driver; _entityModel = app.Model; _timeService = _app.TimeService; //Set list of all schemas var allSchemas = app.Areas.Select(a => settings.ModelConfig.GetSchema(a)); settings.SetSchemas(allSchemas); //Check if model is shared var modelConfig = Settings.ModelConfig; bool modelIsShared = modelConfig.Options.IsSet(DbOptions.ShareDbModel); lock (modelConfig) { //we need lock to prevent collision on shared model if (modelIsShared) { DbModel = modelConfig.SharedDbModel; } if (DbModel == null) { var dbmBuilder = new DbModelBuilder(app.Model, modelConfig); DbModel = dbmBuilder.Build(); if (modelIsShared) { modelConfig.SharedDbModel = DbModel; } } }//lock //Save }
public void RunTestIdentityWithSelfRefEntities() { _app = new IdentityTestsEntityApp(); Startup.ActivateApp(_app); //if(Startup.ServerType == Data.Driver.DbServerType.SQLite) DeleteAllData(); var session = _app.OpenSession(); // Create 3-level tree and save it var node1 = session.NewNode("N1"); // level 2 var node11 = session.NewNode("N11", node1); var node12 = session.NewNode("N12", node1); var node13 = session.NewNode("N13", node1); // level 3 var node111 = session.NewNode("N1111", node11); var node112 = session.NewNode("N1112", node11); var node121 = session.NewNode("N1121", node12); var node122 = session.NewNode("N1122", node12); var node131 = session.NewNode("N1131", node13); var node132 = session.NewNode("N1132", node13); DataUtility.RandomizeRecordOrder(session); session.SaveChanges(); // test passed if it executed without exceptions Assert.IsTrue(true, "never happens"); }
public WebCallInfo(EntityApp app, WebCallContextHandlerSettings settings, HttpRequestMessage request, CancellationToken cancellationToken) { Request = request; WebContext = new WebCallContext(request, app.TimeService.UtcNow, app.TimeService.ElapsedMilliseconds, GetIncomingCookies, GetIncomingHeaderValues); WebContext.OperationContext = new OperationContext(app, UserInfo.Anonymous, WebContext, settings.ConnectionReuseMode); WebContext.OperationContext.SetExternalCancellationToken(cancellationToken); Request.Properties[WebCallContext.WebCallContextKey] = WebContext; WebContext.RequestUrl = request.RequestUri.ToString(); WebContext.HttpMethod = request.Method.ToString().ToUpperInvariant(); WebContext.RequestSize = request.Content.GetLength(); //Check if it is one of the sensitive URLs var path = request.RequestUri.LocalPath; // The only way to get IPaddress it seems is thru use of HttpContext (from ASP.NET host). // NOTE: it is available only under ASP.NET/IIS host, not in self-hosting scenario var ctxWrapper = WebHelper.GetHttpContextWrapper(request); if (ctxWrapper != null) { //IIS hosting WebContext.Referrer = ctxWrapper.Request.UrlReferrer + string.Empty; WebContext.IPAddress = ctxWrapper.Request.UserHostAddress; } else { //Self hosting // webCallContext.IPAddress = "(unknown)"; } //Set log level for this call WebContext.OperationContext.LogLevel = settings.LogLevel; }
public void TestIdentityColumns() { _app = new IdentityTestsEntityApp(); SetupHelper.DropSchemaObjects("ident"); SetupHelper.ActivateApp(_app); var session = _app.OpenSession(); var john = session.NewEntity<IPerson>(); john.Name = "John S"; var car1 = session.NewEntity<ICar>(); car1.Model = "Beatle"; car1.Owner = john; var car2 = session.NewEntity<ICar>(); car2.Model = "Explorer"; car2.Owner = john; Assert.IsTrue(car1.Id < 0, "Car ID is expected to be <0 before saving."); session.SaveChanges(); //Check that Identity values immediately changed to actual positive values loaded from database Assert.IsTrue(john.Id > 0, "Invalid person ID - expected positive value."); Assert.IsTrue(car1.Id > 0, "Invalid car1 ID - expected positive value."); Assert.IsTrue(car2.Id > 0, "Invalid car2 ID - expected positive value."); //Start new session, load all and check that IDs and relationships are correct session = _app.OpenSession(); var persons = session.GetEntities<IPerson>().ToList(); john = persons[0]; var cars = session.GetEntities<ICar>().ToList(); car1 = cars[0]; car2 = cars[1]; Assert.IsTrue(john.Id > 0 && car1.Id > 0 && car2.Id > 0, "IDs expected to become > 0 after saving."); Assert.IsTrue(car1.Owner == john, "Owner expected to be John"); Assert.IsTrue(car2.Owner == john, "Owner expected to be John"); }
public void Init(EntityApp app) { _emailService = _app.GetService<IEmailSendService>(); Util.Check(_emailService != null, "EmailNotificationProvider: failed to retrieve {0} instance.", typeof(IEmailSendService)); _templateService = _app.GetService<ITemplateTransformService>(); Util.Check(_templateService != null, "EmailNotificationProvider: failed to retrieve {0} instance, add Template module to your app.", typeof(ITemplateTransformService)); }
public void Init(EntityApp app) { _errorLog = app.GetService <IErrorLogService>(); _timeService = TimeService.Instance; _timer = new Timer(Timer_Elapsed, null, 100, 100); app.AppEvents.Initializing += Events_Initializing; }
public DbUpgradeManager(Database database, ILog log) { _database = database; _log = log; _app = _database.DbModel.EntityApp; _dbInfoService = (IDbInfoService)_app.GetService(typeof(IDbInfoService)); }
public static INotificationService Create(EntityApp app) { var instance = new NotificationService(app); instance.Init(app); return(instance); }
public EntityApp Build(DbFirstConfig config) { _config = config; _app = new EntityApp(); var log = _app.ActivationLog; _dbSettings = new DbSettings(_config.Driver, DbOptions.Default, _config.ConnectionString); _dbSettings.SetSchemas(_config.Schemas); var modelLoader = _config.Driver.CreateDbModelLoader(_dbSettings, log); _dbModel = modelLoader.LoadModel(); Util.Check(_dbModel.Tables.Count() > 0, "No tables found in the database. Code generation aborted."); // Prepare type generator _tempNamespace = "_dummy_" + _callCount++; // artificial unique namespace for dummy interface types // Construct model setup and model GenerateModulesAndAreas(); _entityModel = new EntityModel(_app); EntityModelBuilder.SetModel(_app, _entityModel); _entityModel.ClassesAssembly = new EntityClassesAssembly(); //generate entities and members GenerateEntities(); SetupPrimaryKeys(); GenerateReferenceMembers(); CreateIndexes(); SetupKeyMembers(); return _app; }
public static void CreateBasicTestData(EntityApp app) { var session = app.OpenSystemSession(); session.EnableCache(false); Vita.Modules.Login.LoginModule.ImportDefaultSecretQuestions(session); session.SaveChanges(); //Create users var stan = session.CreateUser("Stan", UserType.Customer); var linda = session.CreateUser("Linda", UserType.BookEditor); var jessy = session.CreateUser("Jessy", UserType.CustomerSupport); var charlie = session.CreateUser("Charlie", UserType.StoreAdmin); var kevin = session.CreateUser("Kevin", UserType.StoreAdmin); //customers var dora = session.CreateUser("Dora", UserType.Customer, email: "*****@*****.**"); var diego = session.CreateUser("Diego", UserType.Customer); var duffy = session.CreateUser("Duffy", UserType.Customer); var ferb = session.CreateUser("Ferb", UserType.Customer); var cartman = session.CreateUser("Cartman", UserType.Customer, email: "*****@*****.**"); session.SaveChanges(); // Setup secret questions for dora var doraLogin = session.EntitySet <ILogin>().First(lg => lg.UserName == "dora"); //logins are lower-case, important for Postgres SetupSampleSecretQuestions(doraLogin); session.SaveChanges(); }
public SmtpService(EntityApp app, SmtpSettings settings) { _app = app; _settings = settings; _app.RegisterService <ISmtpService>(this); _app.RegisterConfig(settings); }
public static void ConfigureWebApi(HttpConfiguration httpConfiguration, EntityApp app, LogLevel logLevel = LogLevel.Basic, WebHandlerOptions webHandlerOptions = WebHandlerOptions.DefaultDebug) { // Logging message handler var webHandlerStt = new WebCallContextHandlerSettings(logLevel, webHandlerOptions); var webContextHandler = new WebCallContextHandler(app, webHandlerStt); httpConfiguration.MessageHandlers.Add(webContextHandler); // Exception handling filter - to handle/save exceptions httpConfiguration.Filters.Add(new ExceptionHandlingFilter()); // Formatters - add formatters with spies, to catch/log deserialization failures httpConfiguration.Formatters.Clear(); httpConfiguration.Formatters.Add(new StreamMediaTypeFormatter("image/jpeg", "image/webp")); //webp is for Chrome var xmlFmter = new XmlMediaTypeFormatter(); httpConfiguration.Formatters.Add(xmlFmter); var jsonFmter = new JsonMediaTypeFormatter(); // add converter that will serialize all enums as strings, not integers jsonFmter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); var resolver = jsonFmter.SerializerSettings.ContractResolver = new JsonContractResolver(jsonFmter); httpConfiguration.Formatters.Add(jsonFmter); //Api configuration if (app.ApiConfiguration.ControllerInfos.Count > 0) ConfigureSlimApi(httpConfiguration, app); }
public static void CreateBasicTestData(EntityApp app) { var session = app.OpenSystemSession(); session.EnableCache(false); CreateTextTemplates(session); Vita.Modules.Login.LoginModule.ImportDefaultSecretQuestions(session); session.SaveChanges(); //Create users var stan = session.CreateUser("Stan", UserType.Customer); var linda = session.CreateUser("Linda", UserType.BookEditor); var jessy = session.CreateUser("Jessy", UserType.CustomerSupport); var charlie = session.CreateUser("Charlie", UserType.StoreAdmin); var kevin = session.CreateUser("Kevin", UserType.StoreAdmin); //customers var dora = session.CreateUser("Dora", UserType.Customer, email: "*****@*****.**"); var diego = session.CreateUser("Diego", UserType.Customer); var duffy = session.CreateUser("Duffy", UserType.Customer); var ferb = session.CreateUser("Ferb", UserType.Customer); var cartman = session.CreateUser("Cartman", UserType.Customer, email: "*****@*****.**"); session.SaveChanges(); // Setup secret questions for dora var doraLogin = session.EntitySet<ILogin>().First(lg => lg.UserName == "dora"); //logins are lower-case, important for Postgres SetupSampleSecretQuestions(doraLogin); session.SaveChanges(); }
public void TestIdentityColumns() { _app = new IdentityTestsEntityApp(); Startup.DropSchemaObjects("ident"); Startup.ActivateApp(_app); var session = _app.OpenSession(); var john = session.NewEntity <IPerson>(); john.Name = "John S"; var car1 = session.NewEntity <ICar>(); car1.Model = "Beatle"; car1.Owner = john; var car2 = session.NewEntity <ICar>(); car2.Model = "Explorer"; car2.Owner = john; Assert.IsTrue(car1.Id < 0, "Car ID is expected to be <0 before saving."); session.SaveChanges(); //Check that Identity values immediately changed to actual positive values loaded from database Assert.IsTrue(john.Id > 0, "Invalid person ID - expected positive value."); Assert.IsTrue(car1.Id > 0, "Invalid car1 ID - expected positive value."); Assert.IsTrue(car2.Id > 0, "Invalid car2 ID - expected positive value."); //Start new session, load all and check that IDs and relationships are correct session = _app.OpenSession(); john = session.EntitySet <IPerson>().Where(p => p.Name == "John S").Single(); var cars = session.GetEntities <ICar>().ToList(); car1 = cars[0]; car2 = cars[1]; Assert.IsTrue(john.Id > 0 && car1.Id > 0 && car2.Id > 0, "IDs expected to become > 0 after saving."); Assert.IsTrue(car1.Owner == john, "Owner expected to be John"); Assert.IsTrue(car2.Owner == john, "Owner expected to be John"); }//method
public DefaultOperationLogService(EntityApp app, LogLevel logLevel = Services.LogLevel.Details) { LogLevel = logLevel; _timerService = app.GetService<ITimerService>(); _timerService.Elapsed1Second += TimerService_Elapsed1Second; app.AppEvents.FlushRequested += Events_FlushRequested; }
public static EntityApp ActivateApp(EntityApp app, bool updateSchema = true, bool dropUnknownTables = false) { DeleteLocalLogFiles(); app.LogPath = LogFilePath; app.SystemLogPath = SystemLogFilePath; //If driver is not set, it means we are running from Test Explorer in VS. Use ServerTypeForTestExplorer if (Driver == null) { SetupForTestExplorerMode(); } try { app.Init(); var upgradeMode = updateSchema ? DbUpgradeMode.Always : DbUpgradeMode.Never; var upgradeOptions = DbUpgradeOptions.Default; if (dropUnknownTables) { upgradeOptions |= DbUpgradeOptions.DropUnknownObjects; } var dbSettings = new DbSettings(Driver, DbOptions, ConnectionString, upgradeMode: upgradeMode, upgradeOptions: upgradeOptions); app.ConnectTo(dbSettings); return(app); } catch (StartupFailureException sx) { //Unit test framework shows only ex message, not details; let's write specifics into debug output - it will be shown in test failure report Debug.WriteLine("EntityApp init exception: "); Debug.WriteLine(sx.Log); throw; } }
public DbUpgradeManager(Database database, IActivationLog log) { _database = database; _log = log; _app = _database.DbModel.EntityApp; _dbInfoService = _app.GetService <IDbInfoService>(throwIfNotFound: false); }
public VitaJwtTokenHandler(EntityApp entityApp, IServiceCollection services, string jwtSecret) { _entityApp = entityApp; _entityApp.RegisterService <IAuthenticationTokenHandler>(this); var secretBytes = Encoding.ASCII.GetBytes(jwtSecret); _jwtKey = new SymmetricSecurityKey(secretBytes); // some cryptic code copied from samples somewhere services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.Events = new JwtBearerEvents { OnTokenValidated = OnJwtTokenValidated }; x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = _jwtKey, ValidateIssuer = false, ValidateAudience = false }; }); }
// constructors public Database(EntityApp app, DbSettings settings) { _app = app; Settings = settings; _driver = Settings.ModelConfig.Driver; _entityModel = app.Model; _timeService = _app.TimeService; //Set list of all schemas var allSchemas = app.Areas.Select(a => settings.ModelConfig.GetSchema(a)); settings.SetSchemas(allSchemas); //Check if model is shared bool modelIsShared = Settings.ModelConfig.Options.IsSet(DbOptions.ShareDbModel); lock (_lock) { //we need lock to prevent collision on shared model if (modelIsShared) DbModel = Settings.ModelConfig.SharedDbModel; if (DbModel == null) { var dbmBuilder = new DbModelBuilder(app.Model, settings.ModelConfig, app.ActivationLog); DbModel = dbmBuilder.Build(); if (modelIsShared) Settings.ModelConfig.SharedDbModel = DbModel; } }//lock //Save }
public void TestInit() { Startup.InitApp(); _app = Startup.BooksApp; _timersControl = _app.GetService <ITimerServiceControl>(); _jobDiagService = _app.GetService <IJobDiagnosticsService>(); }
public void RunTest(bool batchMode) { _app = new IdentityRefTestEntityApp(); Startup.ActivateApp(_app); //if(Startup.ServerType == Data.Driver.DbServerType.SQLite) DeleteAllData(); // We create session this way to set the batch mode flag var ctx = new OperationContext(_app); IEntitySession session = new EntitySession(ctx, options: batchMode ? EntitySessionOptions.None : EntitySessionOptions.DisableBatchMode); var john = session.NewUser("john"); var post1 = john.NewPost("john post 1", 1); var post2 = john.NewPost("john post 2", 2); var post3 = john.NewPost("john post 3", 3); var ben = session.NewUser("ben"); var post1b = ben.NewPost("ben post 1", 1); var post2b = ben.NewPost("ben post 2", 2); var post3b = ben.NewPost("ben post 3", 3); session.SaveChanges(); //Check that Identity values immediately changed to actual positive values loaded from database Assert.IsTrue(post1.OrderId > 0, "Invalid OrderID - expected positive value."); Assert.IsTrue(post2.OrderId > 0, "Invalid OrderID - expected positive value."); Assert.IsTrue(post3.OrderId > 0, "Invalid OrderID - expected positive value."); //Start new session, load all and check that IDs and relationships are correct session = _app.OpenSession(); var posts = session.EntitySet <IUserPost>().ToList(); foreach (var post in posts) { Assert.IsTrue(post.OrderId > 0); } }//method
public WebCallContextHandler(EntityApp app, WebCallContextHandlerSettings settings) { App = app; Settings = settings ?? new WebCallContextHandlerSettings(); App.RegisterConfig(Settings); _webCallLog = App.GetService<IWebCallLogService>(); _errorLog = App.GetService<IErrorLogService>(); App.RegisterService<IWebCallNotificationService>(this); }
public void Init() { if (_app == null) { _app = new MiscLinqEntityApp(); Startup.ActivateApp(_app); } }
public void Init(EntityApp app) { _smtpService = _app.GetService <ISmtpService>(); Util.Check(_smtpService != null, "EmailNotificationProvider: failed to retrieve {0} instance.", typeof(ISmtpService)); _templateService = _app.GetService <ITemplateTransformService>(); Util.Check(_templateService != null, "EmailNotificationProvider: failed to retrieve {0} instance, add Template module to your app.", typeof(ITemplateTransformService)); }
public static void EnableTimers(EntityApp app, bool enable) { EnableAppTimers(app, enable); foreach (var linked in app.LinkedApps) { EnableAppTimers(linked, enable); } }
public void Init(EntityApp app) { _timerContext = app.CreateSystemContext(); _logService = app.GetService<IOperationLogService>(); _timer = new Timer(100); _timer.Elapsed += Timer_Elapsed; app.AppEvents.Initializing += Events_Initializing; }
public DataSource(string name, Database database, CacheSettings cacheSettings = null) { Database = database; App = Database.DbModel.EntityApp; Name = database.Settings.DataSourceName; if(cacheSettings != null && cacheSettings.HasTypes()) Cache = new EntityCache(App, cacheSettings, this.Database); }
public LogFileWriter(EntityApp app, string logPath) { _app = app; LogPath = logPath; _logService = app.GetService <IOperationLogService>(); _saveService = app.GetService <IBackgroundSaveService>(); _saveService.Saving += SaveService_Saving; }
public DbVersionInfo(EntityApp app, DbModelConfig config) { Version = app.Version; foreach (var m in app.Modules) { var schema = config.GetSchema(m.Area); Modules.Add(new ModuleDbVersionInfo(schema, m.Name, m.Version)); } }
public void Init(EntityApp app) { _log = app.GetService <ILogService>(); app.AppEvents.Initializing += Events_Initializing; _timer = new System.Timers.Timer(BaseTimerIntervalMs); _timer.Elapsed += Timer_Elapsed; _timer.Enabled = true; }
public NotificationListener(EntityApp app, Func<NotificationMessage, bool> filter = null, bool blockAll = false, int maxMessages = 100) { _blockAll = blockAll; _filter = filter; _maxMessages = maxMessages; _notificationService = app.GetService<INotificationService>(); Util.Check(_notificationService != null, "Notification service is not registered."); _notificationService.Sending += NotificationService_Sending; }
public void Init(EntityApp app) { _app = app; _errorLog = _app.GetService <IErrorLogService>(); _operationLog = _app.GetService <IOperationLogService>(); _timerService = _app.GetService <ITimerService>(); _timerService.Elapsed1Second += TimerService_Elapsed1Second; _app.AppEvents.FlushRequested += Events_FlushRequested; }
public DbUpgradeManager(DataSource dataSource) { _dataSource = dataSource; _dataAccess = (DataAccessService) _dataSource.App.DataAccess; _database = _dataSource.Database; _app = _database.DbModel.EntityApp; _log = _app.ActivationLog; _timeService = _app.GetService<ITimeService>(); }
public LogFileWriter(EntityApp app, string logPath) { _app = app; LogPath = logPath; _logService = app.GetService<IOperationLogService>(); Util.Check(_logService != null, "OperationLog service not registered, cannot attach LogFileWriter."); if (_logService != null) _logService.Saving += logService_Saving; }
public void Init(EntityApp app) { _app = app; _authorityByRoleSet = new ObjectCache <string, Authority>( expirationSeconds: RoleCacheExpirationSec, maxLifeSeconds: RoleCacheExpirationSec * 5); _authorityByUserId = new ObjectCache <string, AuthorityDescriptor>( expirationSeconds: UserCacheExpirationSec, maxLifeSeconds: UserCacheExpirationSec * 5); _authorityByUserId.Removed += AuthorityByUserId_Removed; }
public void Init() { if (_app == null) { Startup.DropSchemaObjects("misc"); _app = new MiscTestsEntityApp(); Startup.ActivateApp(_app); } }
public DbVersionInfo(EntityApp app, DbModelConfig config) { Version = app.Version; foreach (var m in app.Modules) { var schema = config.GetSchema(m.Area); Modules.Add(new ModuleDbVersionInfo(schema, m.Name, m.Version)); } }
private static void EnableAppTimers(EntityApp app, bool enable) { var timers = app.GetService <ITimerServiceControl>(); if (timers != null) { timers.EnableAutoFire(enable); } }
public DbUpgradeManager(DataSource dataSource) { _dataSource = dataSource; _dataAccess = (DataAccessService)_dataSource.App.DataAccess; _database = _dataSource.Database; _app = _database.DbModel.EntityApp; _log = _app.SystemLog; _timeService = _app.GetService <ITimeService>(); }
public NotificationListener(EntityApp app, Func <NotificationMessage, bool> filter = null, bool blockAll = false, int maxMessages = 100) { _blockAll = blockAll; _filter = filter; _maxMessages = maxMessages; _notificationService = app.GetService <INotificationService>(); Util.Check(_notificationService != null, "Notification service is not registered."); _notificationService.Sending += NotificationService_Sending; }
internal void OnServiceAdded(EntityApp app, Type serviceType, object serviceInstance) { var evt = ServiceAdded; if (evt != null) { evt(this, new ServiceEventArgs(app, serviceType, serviceInstance)); } }
public void Init(EntityApp app) { _app = app; _errorLog = _app.GetService<IErrorLogService>(); _operationLog = _app.GetService<IOperationLogService>(); _timerService = _app.GetService<ITimerService>(); _timerService.Elapsed1Second += TimerService_Elapsed1Second; _app.AppEvents.FlushRequested += Events_FlushRequested; }
public DataSource(string name, Database database, CacheSettings cacheSettings = null) { Database = database; App = Database.DbModel.EntityApp; Name = database.Settings.DataSourceName; if (cacheSettings != null && cacheSettings.HasTypes()) { Cache = new EntityCache(App, cacheSettings, this.Database); } }
public static void ConfigureSlimApiControllers(HttpConfiguration config, EntityApp app) { var actionSelector = new SlimApiActionSelector(app.ApiConfiguration); config.Services.Replace(typeof(System.Web.Http.Controllers.IHttpActionSelector), actionSelector); var prov = new SlimApiDirectRouteProvider(); config.MapHttpAttributeRoutes(prov); // config.ParameterBindingRules.Add(typeof(DateTime), p => new DateTimeParameterBinding(p)); }
public void WriteCsSources(EntityApp app, DbFirstConfig config) { _app = app; _config = config; HasErrors = false; var fileStream = File.Create(_config.OutputPath); _output = new StreamWriter(fileStream); WriteSource(); _output.Flush(); _output.Close(); }
public void LinkTo(EntityApp mainApp) { MainApp = mainApp; MainApp.LinkedApps.Add(this); MainApp.ImportServices(this, typeof(IErrorLogService), typeof(IOperationLogService), typeof(IIncidentLogService), typeof(ITransactionLogService), typeof(IWebCallLogService), typeof(INotificationLogService), typeof(ILoginLogService), typeof(IDbUpgradeLogService), typeof(IUserSessionService), typeof(IEventLogService) ); _transactionLogModule.TargetApp = MainApp; //Replace time service with the instance from the main app base.TimeService = MainApp.TimeService; this.ImportServices(MainApp, typeof(ITimeService)); }
public EntityCache(EntityApp app, CacheSettings settings, Database database) { _app = app; Settings = settings; _dataStore = database; _sparseCache = new SparseEntityCache(Settings); var dbIsCaseInsensitive = database.Settings.Driver.Features.IsSet(Data.Driver.DbFeatures.DefaultCaseInsensitive); var caseMode = dbIsCaseInsensitive ? StringCaseMode.CaseInsensitive : StringCaseMode.CaseSensitive; _fullSetCache = new FullSetEntityCache(_app, Settings, _dataStore, caseMode); _timeService = _app.GetService<ITimeService>(); _logService = _app.GetService<IOperationLogService>(); _errorLog = _app.GetService<IErrorLogService>(); MarkCachedEntities(); _app.AppEvents.SavedChanges += Events_SavedChanges; }
public void ImportBooks(EntityApp app, int count = 250) { _app = app; _session = _app.OpenSystemSession(); //Preload caches _bookCache = _session.GetEntities<IBook>(take: 1000).ToDictionary(b => b.Title, StringComparer.InvariantCultureIgnoreCase); _publishersCache = _session.GetEntities<IPublisher>(take: 200).ToDictionary(p => p.Name, StringComparer.InvariantCultureIgnoreCase); _authorsCache = _session.GetEntities<IAuthor>(take: 1000).ToDictionary(a => a.FirstName + a.LastName, StringComparer.InvariantCultureIgnoreCase); _client = new GoogleBooksApiClient(); var batchSize = count / 5; ImportBooksInCategory(BookCategory.Programming, "c#", batchSize); ImportBooksInCategory(BookCategory.Programming, "Linux", batchSize); ImportBooksInCategory(BookCategory.Fiction, "Comics", batchSize); ImportBooksInCategory(BookCategory.Fiction, "Science fiction", batchSize); ImportBooksInCategory(BookCategory.Kids, "Fairy tales", batchSize); }
public static EntityApp ActivateApp(EntityApp app, bool updateSchema = true, bool dropUnknownTables = false) { DeleteLocalLogFile(); app.LogPath = LogFilePath; //If driver is not set, it means we are running from Test Explorer in VS. Use ServerTypeForTestExplorer if(Driver == null) SetupForTestExplorerMode(); try { app.Init(); var upgradeMode = updateSchema ? DbUpgradeMode.Always : DbUpgradeMode.Never; var upgradeOptions = DbUpgradeOptions.Default; if(dropUnknownTables) upgradeOptions |= DbUpgradeOptions.DropUnknownObjects; var dbSettings = new DbSettings(Driver, DbOptions, ConnectionString, upgradeMode: upgradeMode, upgradeOptions: upgradeOptions); app.ConnectTo(dbSettings); return app; } catch (StartupFailureException sx) { //Unit test framework shows only ex message, not details; let's write specifics into debug output - it will be shown in test failure report Debug.WriteLine("EntityApp init exception: "); Debug.WriteLine(sx.Log); throw; } }
public EmailNotificationProvider(EntityApp app) { _app = app; }
private void SetupUpdateLogging() { TargetApp = TargetApp ?? App; TargetApp.AppEvents.SavedChanges += Events_SavedChanges; TargetApp.AppEvents.ExecutedNonQuery += AppEvents_ExecutedNonQuery; // remove entities in ignore areas or with DoNotTrack attribute if(Settings.IgnoreAreas.Count > 0) { foreach(var ent in TargetApp.Model.Entities) if(Settings.IgnoreAreas.Contains(ent.Area)) ent.Flags |= EntityFlags.DoNotTrack; } }
public void TestIdentityInLargeBatch() { _app = new IdentityTestsEntityApp(); SetupHelper.DropSchemaObjects("ident"); SetupHelper.ActivateApp(_app); var saveParamCount = SetupHelper.Driver.MaxParamCount; SetupHelper.Driver.MaxParamCount = 20; //to cause update batch split into multiple commands var session = _app.OpenSession(); // add 50 owners, then 200 cars with random owners // our goal is to create update set with inserts of linked entities with identity pk/fk // we test how identity values are carried between commands (from IPerson.Id to ICar.OwnerId) var owners = new List<IPerson>(); var rand = new Random(); for (int i = 0; i < 50; i++) { var owner = session.NewEntity<IPerson>(); owner.Name = "Owner" + i; owners.Add(owner); } for (int i = 0; i < 100; i++) { var car = session.NewEntity<ICar>(); car.Model = "Model" + i; car.Owner = owners[rand.Next(owners.Count)]; } try { session.SaveChanges(); //we just test that it succeeds } finally { //revert max param count back to normal - to avoid disturbing other tests SetupHelper.Driver.MaxParamCount = saveParamCount; } }
public WebCallInfo(EntityApp app, WebCallContextHandlerSettings settings, HttpRequestMessage request) { Request = request; WebContext = new WebCallContext(request, app.TimeService.UtcNow, app.TimeService.ElapsedMilliseconds, GetIncomingCookies, GetIncomingHeaderValues); WebContext.OperationContext = new OperationContext(app, UserInfo.Anonymous, WebContext, settings.ConnectionReuseMode); Request.Properties[WebCallContext.WebCallContextKey] = WebContext; WebContext.RequestUrl = request.RequestUri.ToString(); WebContext.HttpMethod = request.Method.ToString().ToUpperInvariant(); WebContext.RequestSize = request.Content.GetLength(); //Check if it is one of the sensitive URLs var path = request.RequestUri.LocalPath; // The only way to get IPaddress it seems is thru use of HttpContext (from ASP.NET host). // NOTE: it is available only under ASP.NET/IIS host, not in self-hosting scenario var ctxWrapper = WebHelper.GetHttpContextWrapper(request); if (ctxWrapper != null) { //IIS hosting WebContext.Referrer = ctxWrapper.Request.UrlReferrer + string.Empty; WebContext.IPAddress = ctxWrapper.Request.UserHostAddress; } else { //Self hosting // webCallContext.IPAddress = "(unknown)"; } //Set log level for this call WebContext.OperationContext.LogLevel = settings.LogLevel; }
public static void CreateUnitTestData(EntityApp app) { CreateBasicTestData(app); CreateSampleBooks(app); }
public static void CreateSampleBooks(EntityApp app) { //Create identity for sample data generator; this results in SampleDataGenerator showing up in UserSession/UserTransaction tables // Books and coupons will reference these transactions as 'CreatedIn' var session = app.OpenSystemSession(); var dataGenUser = session.NewUser("SampleDataGenerator", UserType.StoreAdmin); session.SaveChanges(); var userInfo = new UserInfo(dataGenUser.Id, dataGenUser.UserName); var dataGenOpCtx = new OperationContext(app, userInfo); session = dataGenOpCtx.OpenSystemSession(); session.EnableCache(false); //Publishers and authors var msPub = session.NewPublisher("MS Books"); //we are using extension method here var kidPub = session.NewPublisher("Kids Books"); var johnBio = ConstructLongText(4000); var authorJohn = session.NewAuthor("John", "Sharp", johnBio); var authorJack = session.NewAuthor("Jack", "Pound"); var authorJim = session.NewAuthor("Jim", "Hacker"); //this author is not user - we'll use this author to check some tricky query in tests var john = authorJohn.User = session.CreateUser("John", UserType.Author); var pubDate = DateTime.Today.AddYears(-1); //Books on programming from MS Books var csBook = session.NewBook(BookEdition.Paperback | BookEdition.EBook, BookCategory.Programming, "c# Programming", "Expert programming in c#", msPub, pubDate, 20.0m); // Some multiline text in Abstract csBook.Abstract = @"Expert guide to programming in c# 4.0. Highly recommended for beginners and experts. Covers c# 4.0."; csBook.CoverImage = LoadImageFromResource(session, "csBookCover.jpg"); csBook.Authors.Add(authorJohn); //this is many-to-many csBook.Authors.Add(authorJack); csBook.Editor = session.EntitySet<IUser>().First(u => u.UserName == "Linda"); var vbBook = session.NewBook(BookEdition.Paperback | BookEdition.Hardcover, BookCategory.Programming, "VB Programming", "Expert programming in VB", msPub, pubDate, 25.0m); vbBook.Authors.Add(authorJack); vbBook.CoverImage = LoadImageFromResource(session, "vbBookCover.jpg"); //Folk tale, no authors var kidBook = session.NewBook(BookEdition.Hardcover, BookCategory.Kids, "Three little pigs", "Folk tale", kidPub, pubDate, 10.0m); var winBook = session.NewBook(BookEdition.Hardcover, BookCategory.Programming, "Windows Programming", "Introduction to Windows Programming", msPub, pubDate.AddYears(-10), 30.0m); winBook.Authors.Add(authorJohn); winBook.CoverImage = LoadImageFromResource(session, "winBookCover.jpg"); var comicBook = session.NewBook(BookEdition.Paperback, BookCategory.Fiction, "IronMan", null, kidPub, null, 3); //Coupons var coupon1 = session.NewCoupon("C1", 10, DateTime.Now.AddMonths(1)); var coupon2 = session.NewCoupon("C2", 10, DateTime.Now.AddMonths(1)); var coupon3 = session.NewCoupon("C3", 10, DateTime.Now.AddMonths(1)); try { session.SaveChanges(); //Save books, coupons, users and logins } catch(ClientFaultException ex) { var msgs = ex.GetMessages(); Debug.WriteLine(msgs); throw; } //Orders var dora = session.EntitySet<IUser>().First(u => u.UserName == "Dora"); var doraOrder = session.NewOrder(dora); doraOrder.Add(csBook, 1); doraOrder.Add(kidBook, 2); doraOrder.CompleteOrder("C1"); //Create one empty order, for testing includes in queries var doraOrder2 = session.NewOrder(dora); doraOrder2.Status = OrderStatus.Canceled; var diego = session.EntitySet<IUser>().First(u => u.UserName == "Diego"); var diegoOrder = session.NewOrder(diego); diegoOrder.Add(vbBook, 1); diegoOrder.Add(csBook, 1); diegoOrder.CompleteOrder(); //Reviews var doraReview = session.NewReview(dora, csBook, 5, "Very interesting book!", "Liked it very much!"); var diegoReview = session.NewReview(diego, vbBook, 1, "Not worth it.", "Did not like it at all."); // special reviews with text including wildcards for LIKE operator - will use them to test wildcard escaping in LIKE var duffy = session.EntitySet<IUser>().First(u => u.UserName == "Duffy"); session.NewReview(duffy, comicBook, 1, "'Boo", "'Boo"); session.NewReview(duffy, comicBook, 1, "_Boo", "_Boo"); session.NewReview(duffy, comicBook, 1, "%Boo", "%Boo"); session.NewReview(duffy, comicBook, 1, "[Boo]", "[Boo]"); session.NewReview(duffy, comicBook, 1, "]Boo[", "]Boo["); session.NewReview(duffy, comicBook, 1, @"\Boo\oo", @"\Boo\oo"); session.NewReview(duffy, comicBook, 1, @"/Boo/oo", @"/Boo/oo"); //Save orders try { session.SaveChanges(); } catch (ClientFaultException ex) { var msgs = ex.GetMessages(); Debug.WriteLine(msgs); throw; } }
private Dictionary<Type, EntityInfo> _entitiesByType = new Dictionary<Type, EntityInfo>(); //interfaceType -> EntityInfo #endregion Fields #region Constructors public EntityModel(EntityApp app) { App = app; ModelState = EntityModelState.Created; }
public AppInitEventArgs(EntityApp app, MemoryLog log, EntityAppInitStep step) { App = app; Log = log; Step = step; }
public EntityAppEvents(EntityApp app) { _app = app; }