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 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(); }
// We use sessions bound to particular user, to test that retries are executed as the same user private OperationContext GetUserBoundContext() { var session = _app.OpenSystemSession(); var dora = session.EntitySet <IUser>().Where(u => u.UserName == "Dora").Single(); var userInfo = new UserInfo(dora.Id, dora.UserName); var context = new OperationContext(_app, userInfo); return(context); }
private void Flush() { if (_flushing) { return; } if (!_app.IsConnected()) { return; } lock (_lock) { try { _flushing = true; var start = _app.TimeService.ElapsedMilliseconds; var list = DequeuAll(); if (list.Count == 0) { return; } //fire event Saving?.Invoke(this, new BackgroundSaveEventArgs(list)); var session = (EntitySession)_app.OpenSystemSession(); session.LogDisabled = true; //do not log operations; what we save are log entries themselves most of the time if (list.Count > 0) { var byHandler = list.GroupBy(o => GetHandler(o)); foreach (var group in byHandler) { var handler = group.Key; if (handler == null) { continue; } handler.SaveObjects(session, group.ToList()); } } //Get stats var recCount = session.GetChangeCount(); var startSaving = _app.TimeService.ElapsedMilliseconds; session.SaveChanges(); var endSaving = _app.TimeService.ElapsedMilliseconds; //log stats if (_operationLog != null && OkToLogStatsMessage(list)) { var logEntry = new Logging.InfoLogEntry(session.Context, "Background save completed, records: {0}, save time: {1} ms, total time: {2} ms.", recCount, (endSaving - startSaving), (endSaving - start)); _operationLog.Log(logEntry); } } catch (Exception ex) { //System.Diagnostics.Debugger.Break(); _errorLog.LogError(ex); } finally { _flushing = false; } } }//method
private void ApplyPostUpgradeMigrations(DbUpgradeInfo upgradeInfo) { if (upgradeInfo.PostUpgradeMigrations == null || upgradeInfo.PostUpgradeMigrations.Count == 0) { return; } var session = _app.OpenSystemSession(); foreach (var m in upgradeInfo.PostUpgradeMigrations) { m.Action(session); } session.SaveChanges(); }
private void PersisteEntries(IList <LogEntry> entries) { try { var entriesByType = entries.GroupBy(e => e.BatchGroup).ToDictionary(g => g.Key, g => g.ToArray()); var session = _app.OpenSystemSession(); var batch = new LogEntryBatch() { Session = session, Entries = entries, EntriesByType = entriesByType }; Broadcast(batch); session.SaveChanges(); } catch (Exception ex) { _app.LogService.LogError(ex); } }
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 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.OrdinalIgnoreCase); _publishersCache = _session.GetEntities <IPublisher>(take: 200).ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase); _authorsCache = _session.GetEntities <IAuthor>(take: 1000).ToDictionary(a => a.FirstName + a.LastName, StringComparer.OrdinalIgnoreCase); _client = new GoogleBooksApiClient(_session.Context); 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); }//method
private void ApplyPostUpgradeMigrations() { if (_upgradeInfo.PostUpgradeMigrations == null || _upgradeInfo.PostUpgradeMigrations.Count == 0) { return; } _app.DataSourceEvents.OnDbUpgrading(new DbUpgradeEventArgs(_database, DbUpgradeEventType.MigrationScriptsApplying, _upgradeInfo)); var session = (EntitySession)_app.OpenSystemSession(); // set explicit, admin-level connection session.CurrentConnection = new DataConnection(session, _database.Settings, DbConnectionLifetime.Operation, admin: true); foreach (var m in _upgradeInfo.PostUpgradeMigrations) { m.Action(session); } session.SaveChanges(); _app.DataSourceEvents.OnDbUpgraded(new DbUpgradeEventArgs(_database, DbUpgradeEventType.MigrationScriptsApplying, null)); }
public override void OnNewIncident(IIncidentLog newEntry) { //if login failed with user name that matches a login in database, we log this loginId in KeyId1 var failedUserName = newEntry.Key1; if (string.IsNullOrWhiteSpace(failedUserName)) { return; } var tenantId = newEntry.KeyId2; var utcNow = _app.TimeService.UtcNow; var session = _app.OpenSystemSession(); var fromDate = utcNow.Subtract(Settings.TimeWindow); var strLoginFailed = LoginEventType.LoginFailed.ToString(); var qryRecentFailures = from lg in session.EntitySet <IIncidentLog>() where lg.CreatedOn >= fromDate && lg.Key1 == failedUserName && lg.Type == LoginModule.LoginIncidentType && lg.SubType == strLoginFailed select lg; //Note: currently LINQ translator does not handle correctly comparing nullable values, so adding this separately if (tenantId != null) { qryRecentFailures = qryRecentFailures.Where(lg => lg.KeyId2 == tenantId.Value); } var failCount = qryRecentFailures.Count(); if (failCount < Settings.FailureCount) { return; //not yet } // We have repeated login failures in short period of time; this might be an attack - suspend account(s) for several minutes // find Login(s) - might be more than one - we may have the same username for different tenants var loginSet = session.EntitySet <ILogin>(); var loginQuery = from lg in loginSet where lg.UserName == failedUserName select lg; if (tenantId != null) { loginQuery = loginQuery.Where(lg => lg.TenantId == tenantId.Value); } var logins = loginQuery.ToList(); if (logins.Count == 0) { return; //it might happen if user name is not known } //Suspend login var suspendedUntil = utcNow.Add(Settings.SuspensionPeriod); var loginLogService = _app.GetService <ILoginLogService>(); var msg = StringHelper.SafeFormat("{0} login failures. Login {1} suspended until {2}", failCount, failedUserName, suspendedUntil); var loginModule = _app.GetModule <LoginModule>(); foreach (var lg in logins) { // if already suspended or disabled, do not suspend again if (lg.Flags.IsSet(LoginFlags.Disabled | LoginFlags.Suspended)) { continue; } lg.Flags |= LoginFlags.Suspended; lg.SuspendedUntil = suspendedUntil; //raise event - it will log to login log loginModule.OnLoginEvent(session.Context, LoginEventType.LoginSuspended, lg, msg, failedUserName); } session.SaveChanges(); var incService = _app.GetService <IIncidentLogService>(); incService.LogIncident(LoginModule.LoginIncidentType, msg, LoginEventType.LoginSuspended.ToString(), key1: failedUserName, keyId2: tenantId); }
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; } }
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.Add(winBook, 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; } }