public ActionResult Index(TaxCalculateViewModel model) { if (ModelState.IsValid) { var taxRate = DocumentSession.Load <TaxRate>(model.SelectedYear); model.Result = _calculateService.Calculate(taxRate, model.TaxableIncome.Value); } else { ShowErrorMessage("Please input valid data"); } var list = DocumentSession.Query <TaxRate>() .OrderByDescending(r => r.Year) .ToArray() .Select(r => new SelectListItem { Text = r.Description, Value = r.Id.ToString(), }); ViewBag.TaxRatesList = list; return(View(model)); }
public ActionResult Create(QuestionInputModel inputModel) { try { if (ModelState.IsValid) { var question = Mapper.Map <QuestionInputModel, Core.Entities.Question>(inputModel); question.CreatedByUserId = ClaimsUser == null ? null : ClaimsUser.Id; _questionService.Store(question); DocumentSession.SaveChanges(); return(RedirectToAction("Index", "Home", new { area = "" })); } } catch (Exception exception) { ModelState.AddModelError("RuRoh", exception.Message); } var viewModel = new QuestionViewModel(ClaimsUser); Mapper.Map(inputModel, viewModel); return(View("Create", viewModel)); }
public virtual RenderJsonResult RegisterNewWebAccount(RegisterNewAccountParameters parameters) { var existingWebAccountEmailReferenceId = DocumentSession.GetEntityIdFromValue <WebAccountEmailReference>(parameters.EmailAddress); var existingWebAccountEmailReference = DocumentSession.Load <WebAccountEmailReference>(existingWebAccountEmailReferenceId); if (existingWebAccountEmailReference != null) { DocumentSession.Advanced.Clear(); return(this.RenderJsonErrorCode(1, "An account already exists with this e-mail address.")); } if (string.IsNullOrWhiteSpace(parameters.RequestedPassword)) { DocumentSession.Advanced.Clear(); return(this.RenderJsonErrorCode(2, "A password is required, both passwords must match")); } var newAccount = WebAccount.RegisterNewAccount(parameters); newAccount.ChangePassword(parameters.RequestedPassword); DocumentSession.Store(newAccount); var newAccountEmailReference = new WebAccountEmailReference(existingWebAccountEmailReferenceId, newAccount.Id); DocumentSession.Store(newAccountEmailReference); // TODO: Publish event for e-mail notification return(this.RenderJsonSuccessErrorCode()); }
Query <T> Query <T>() where T : class { var store = DocumentStore.ForTesting(TableMode.UseTempTables, connectionString); var session = new DocumentSession(store); return(new Query <T>(new QueryProvider <T>(session, null))); }
public void Validate() { if (!DocumentSession.Exists <Domain.Model.Speed>(Id)) { throw new BusinessRuleValidationException("Speed cannot be found. "); } if (!DocumentSession.Exists <Person>(PilotId)) { throw new BusinessRuleValidationException("Pilot cannot be found. "); } if (!DocumentSession.Exists <Person>(WitnessId)) { throw new BusinessRuleValidationException("Witness cannot be found. "); } if (!DocumentSession.Exists <Domain.Model.Site>(SiteId)) { throw new BusinessRuleValidationException("Site cannot be found. "); } if (!DocumentSession.Exists <Domain.Model.Aircraft>(AircraftId)) { throw new BusinessRuleValidationException("Airctaft cannot be found. "); } if (DocumentSession.Load <Domain.Model.Speed>(Id).IsVerified) { throw new BusinessRuleValidationException("Cannot edit a verified speed. "); } }
public ActionResult OilPattern(string id) { Roster roster = DocumentSession.Load <Roster>(id); ViewBag.Url = roster.OilPattern.Url; return(View("_BitsIframe")); }
public JsonResult Create(string facebookToken) { var client = new FacebookClient(facebookToken); dynamic user = client.Get("me"); string userId = user.id; var siteUser = DocumentSession.Query <User>() .SingleOrDefault(x => x.Id == userId); if (siteUser == null) { var newUser = new User { Name = user.name, Roles = { Role.User } }; DocumentSession.Store(newUser, user.id); siteUser = newUser; } FormsAuthentication.SetAuthCookie(siteUser.Id, false); return(Json(new { user.id, user.name })); }
private string GetArticlePageId(string key) { var articlePage = DocumentSession.Query <ArticlePage>() .SingleOrDefault(x => x.Key == key); return(articlePage?.Id); }
private string GetDocumentationPageId(string version, string lang, string key) { var documentationPage = DocumentSession.Query <DocumentationPage>() .SingleOrDefault(x => x.Version == version && x.Language.ToString() == lang && x.Key == key); return(documentationPage?.Id); }
public ActionResult UpdateState(string versionNumber, ReleaseCandidateState state) { var candidate = DocumentSession.GetCandidate(versionNumber); candidate.UpdateState(state); return(new EmptyResult()); }
public void FailsOnSaveChangesWhenPreviousSaveFailed() { var fakeStore = A.Fake <IDocumentStore>(x => x.Wrapping(store)); A.CallTo(fakeStore) .Where(x => x.Method.Name == nameof(IDocumentStore.BeginTransaction)) .Throws(() => new Exception()); Document <Entity>(); // The this reference inside OpenSession() is not referencing the fake store, but the wrapped store itself. // Therefore we bypass the OpenSession factory. using (var session = new DocumentSession(fakeStore, fakeStore.Configuration.Resolve <DocumentMigrator>())) { session.Store(new Entity()); try { session.SaveChanges(); // fails when in an inconsitent state } catch (Exception) { } Should.Throw <InvalidOperationException>(() => session.SaveChanges()) .Message.ShouldBe("Session is not in a valid state. Please dispose it and open a new one."); } }
public virtual ActionResult ValidateMappings(string language, string version, bool all) { var query = DocumentSession .Query <DocumentationPage>() .Take(int.MaxValue); if (all == false) { query = query.Where(x => x.Version == CurrentVersion); if (Enum.TryParse(language, true, out Language parsedLanguage)) { query = query.Where(x => x.Language == parsedLanguage || x.Language == Language.All); } } var pages = query.ToList(); var options = new ParserOptions { PathToDocumentationDirectory = GetDocumentationDirectory(), RootUrl = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~")) + "article/" + CurrentVersion + "/" + CurrentLanguage + "/", ImagesUrl = GetImagesUrl(HttpContext, DocumentStore, ArticleType.Documentation) }; var results = new DocumentationValidator(options, CurrentLanguage) .ValidateMappings(pages) .ToList(); return(View(MVC.Docs.Views.ValidateMappings, results)); }
public ActionResult Delete(int id) { var product = DocumentSession.Load <Product>(id); DocumentSession.Delete(product); return(RedirectToAction("Index")); }
Query <T> Query <T>() where T : class { var documentStore = Using(DocumentStore.ForTesting(TableMode.GlobalTempTables, c => c.UseConnectionString(connectionString))); var session = new DocumentSession(documentStore, documentStore.Configuration.Resolve <DocumentMigrator>()); return(new Query <T>(new QueryProvider(session, null))); }
public IActionResult GetById(string serverId) { DatabaseServer server = DocumentSession .Include <DatabaseServer>(databaseServer => databaseServer.TenantId) .Load <DatabaseServer>(serverId); if (server == null) { return(NotFound(new { Id = serverId, EntityType = "DatabaseServer", Message = $"No server found with Id {serverId}." })); } Tenant tenant = DocumentSession.Load <Tenant>(server.TenantId); if (tenant == null) { return(NotFound(new { Id = server.TenantId, EntityType = "Tenant", Message = $"No tenant found with Id {server.TenantId} (referenced by server {serverId})." })); } return(Json( new DatabaseServerDetail(server, tenant) )); }
public IQueryable <App> Recent(int count = 21) { var apps = Queryable.OrderByDescending(DocumentSession.Query <App, Apps_ByLastUpdated>(), a => a.LastUpdated) .Take(count); return(apps); }
public ActionResult Search(string term) { IRavenQueryable <RecentPopularTags.ReduceResult> query = DocumentSession .Query <RecentPopularTags.ReduceResult, RecentPopularTags>() .Where(x => x.Tag == term); // Does this tag exist? RecentPopularTags.ReduceResult tag = query.FirstOrDefault(); var results = new List <string>(); if (tag != null) { results.Add(tag.Tag); } else { // No exact match .. so lets use Suggest. SuggestionQueryResult suggestedTags = query.Suggest(); if (suggestedTags.Suggestions.Length > 0) { results.AddRange(suggestedTags.Suggestions); } } return(Json(results, JsonRequestBehavior.AllowGet)); }
public IQueryable <App> GoneFree(int count = 21) { var apps = Queryable.OrderByDescending(DocumentSession.Query <App>("Apps/GoneFree"), a => a.LastUpdated) .Take(count); return(apps); }
public QueryProvider(DocumentSession session, DocumentDesign design) { this.session = session; this.design = design; store = session.Advanced.DocumentStore; lastQueryStats = new QueryStats(); }
public IQueryable <AppsList> Topics(int count = 10) { var topics = Queryable.OrderByDescending(DocumentSession.Query <AppsList>() .Where(t => !t.IsFeatured), t => t.LastDateSeen); return(topics); }
protected async Task <bool> WaitForDocumentInClusterAsync <T>(DocumentSession session, string docId, Func <T, bool> predicate, TimeSpan timeout, X509Certificate2 certificate = null) { var nodes = session.RequestExecutor.TopologyNodes; var stores = GetDocumentStores(nodes, disableTopologyUpdates: true, certificate: certificate); return(await WaitForDocumentInClusterAsyncInternal(docId, predicate, timeout, stores)); }
public virtual ActionResult Validate(string language, string version, bool all) { if (DebugHelper.IsDebug() == false) { return(RedirectToAction(MVC.Docs.ActionNames.Index, MVC.Docs.Name)); } var query = DocumentSession .Query <DocumentationPage>() .Take(1024); if (all == false) { query = query.Where(x => x.Version == CurrentVersion); } var pages = query.ToList(); var options = new ParserOptions { PathToDocumentationDirectory = GetDocumentationDirectory(), RootUrl = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~")) + "article/" + CurrentVersion + "/" + CurrentLanguage + "/", ImagesUrl = GetImagesUrl(HttpContext, DocumentStore, ArticleType.Documentation) }; var results = new DocumentationValidator(options, CurrentLanguage) .ValidateLinks(pages) .ToList(); return(View(MVC.Docs.Views.Validate, results)); }
public IActionResult GetDatabases(string tenantId, bool ensureUpToDate = false) { Tenant tenant = DocumentSession.Load <Tenant>(tenantId); if (tenant == null) { return(NotFound(new { Id = tenantId, EntityType = "Tenant", Message = $"Tenant not found with Id '{tenantId}." })); } IRavenQueryable <DatabaseInstance> query = DocumentSession.Query <DatabaseInstance, DatabaseInstanceDetails>(); if (ensureUpToDate) { query = query.Customize( queryConfig => queryConfig.WaitForNonStaleResults( waitTimeout: TimeSpan.FromSeconds(5) ) ); } return(Json( query.Where( database => database.TenantId == tenantId ) .ProjectFromIndexFieldsInto <DatabaseInstanceDetail>() )); }
public ActionResult Create(ContatoViewModel contatoViewModel) { if (!ModelState.IsValid) { return(View("New", contatoViewModel)); } var contato = DocumentSession .Query <Contato_Search.ContatoSearch, Contato_Search>() .As <Contato>() .FirstOrDefault(c => c.Nome == contatoViewModel.Nome); if (null == contato) { contato = Mapper.Map <ContatoViewModel, Contato>(contatoViewModel); DocumentSession.Store(contato); TempData["success"] = "Contato incluido com sucesso"; } else { TempData["error"] = string.Format("Já existe um contato com o nome {0}", contato.Nome); } return(RedirectToAction("Edit", new { contato.Id })); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { string email = string.IsNullOrEmpty(value as string) ? string.Empty : ((string)value).ToLower(); if (IgnoreAuthenticatedUserEmail) { string authenticatedUserId = UserContext.GetAuthenticatedUserId(); if (DocumentSession.Query <User>() .Any(x => x.Id != authenticatedUserId && x.Email == email)) { return(new ValidationResult(ErrorMessageString)); } } else { if (DocumentSession.Query <User>() .Any(x => x.Email == email)) { return(new ValidationResult(ErrorMessageString)); } } return(ValidationResult.Success); }
public virtual RenderJsonResult RegisterNewProfile(RegisterNewProfileParameters parameters, bool ignoreMatches) { if (!parameters.AreValid()) { return(this.RenderJsonErrorCode(1, "Invalid Parameters")); } if (!ignoreMatches) { var possibleMatchingProfiles = DocumentSession.Query <DirectoryProfile>() .Where(x => x.FirstName.StartsWith(parameters.FirstName.Take(3))) .Where(x => x.LastName.StartsWith(parameters.LastName.Take(3))) .Take(5) .ToList(); if (possibleMatchingProfiles.Any()) { return(this.RenderJsonErrorCode(2, "Possible Existing Profiles", possibleMatchingProfiles.Select(x => new { firstName = x.FirstName, lastName = x.LastName, emailAddress = x.EmailAddress, }).ToArray())); } } var newProfile = DirectoryProfile.RegisterNewProfile(parameters); DocumentSession.Store(newProfile); return(this.RenderJsonSuccessErrorCode()); }
public virtual RenderJsonResult Login(string emailAddress, string password, bool persist, string returnUrl) { var webAccountEmailReferenceId = DocumentSession.GetEntityIdFromValue <WebAccountEmailReference>(emailAddress); var accountEmailReference = DocumentSession.Load <WebAccountEmailReference>(webAccountEmailReferenceId); if (accountEmailReference == null) { return(this.RenderJsonErrorCode(1, "Bad Username or Password")); } var webAccount = DocumentSession.Load <WebAccount>(accountEmailReference.WebAccountId); if (webAccount == null || !webAccount.PasswordMatches(password)) { return(this.RenderJsonErrorCode(1, "Bad Username or Password")); } if (!webAccount.CanLogin()) { return(this.RenderJsonErrorCode(2, "Account is locked")); } webAccount.IncrementLogin(); FormsAuthentication.SetAuthCookie(webAccount.Id, persist); SetRoles(webAccount.Roles); return(new RenderJsonResult() { Data = new { redirect = Url.IsLocalUrl(returnUrl) ? returnUrl : Url.Action(MVC.Public.Index()) } }); }
public ApiModule() : base("/api") { Get["/teachers"] = _ => Response.AsJson(DocumentSession.Query <Teacher> () .Customize(q => q.WaitForNonStaleResultsAsOfLastWrite()) .ToList(), HttpStatusCode.OK); }
public void Validate() { if (!DocumentSession.Exists <Domain.Model.Speed>(Id)) { throw new BusinessRuleValidationException("Speed to verify cannot be found. "); } }
public ActionResult Index() { return(View(DocumentSession .Query <DeploymentEnvironment>() .OrderBy(x => x.Name) .ToList())); }
public static DocumentSession GetDocumentSession() { DocumentStore documentStore = new DocumentStore(); documentStore.ConnectionStringName = "RavenDB"; documentStore.Initialize(); DocumentSession session = new DocumentSession(documentStore, null, null); return session; }
public IDocumentSession OpenSession() { var session = new DocumentSession(this, DatabaseCommands); session.Stored += entity => { if (Stored != null) Stored(server, port, entity); }; return session; }
public IDocumentSession OpenSession(string database, ICredentials credentialsForSession) { this.EnsureNotClosed(); Guid id = Guid.NewGuid(); DocumentStore.currentSessionId = new Guid?(id); try { DocumentSession documentSession = new DocumentSession(this, this.listeners, id, this.DatabaseCommands.ForDatabase(database).With(credentialsForSession), this.AsyncDatabaseCommands.ForDatabase(database).With(credentialsForSession)); this.AfterSessionCreated((InMemoryDocumentSessionOperations) documentSession); return (IDocumentSession) documentSession; } finally { DocumentStore.currentSessionId = new Guid?(); } }
/// <summary> /// Opens the session for a particular database with the specified credentials /// </summary> public IDocumentSession OpenSession(string database, ICredentials credentialsForSession) { var session = new DocumentSession(this, storeListeners, deleteListeners, DatabaseCommands .ForDatabase(database) .With(credentialsForSession)); session.Stored += OnSessionStored; return session; }
public IDocumentSession OpenSession() { if(DatabaseCommands == null) throw new InvalidOperationException("You cannot open a session before initialising the document store. Did you forgot calling Initialise?"); var session = new DocumentSession(this, DatabaseCommands); session.Stored += entity => { var copy = Stored; if (copy != null) copy(Identifier, entity); }; return session; }
public Task Run(IDocumentStore store) { var logger = store.Configuration.Logger; var configuration = store.Configuration; if (!configuration.RunDocumentMigrationsOnStartup) return Task.FromResult(0); return Task.Factory.StartNew(() => { var migrator = new DocumentMigrator(configuration); foreach (var table in configuration.Tables.Values.OfType<DocumentTable>()) { var baseDesign = configuration.TryGetDesignByTablename(table.Name); if (baseDesign == null) { throw new InvalidOperationException($"Design not found for table '{table.Name}'"); } while (true) { QueryStats stats; var rows = store .Query(table, out stats, @where: "AwaitsReprojection = @AwaitsReprojection or Version < @version", @select: "Id, AwaitsReprojection, Version, Discriminator, Etag", take: 100, @orderby: "newid()", parameters: new { AwaitsReprojection = true, version = configuration.ConfiguredVersion }) .ToList(); if (stats.TotalResults == 0) break; logger.Information("Found {0} document that must be migrated.", stats.TotalResults); foreach (var row in rows) { var key = (string)row[table.IdColumn]; var currentDocumentVersion = (int)row[table.VersionColumn]; var discriminator = ((string)row[table.DiscriminatorColumn]).Trim(); var concreteDesign = store.Configuration.GetOrCreateDesignByDiscriminator(baseDesign, discriminator); var shouldUpdate = false; if ((bool)row[table.AwaitsReprojectionColumn]) { shouldUpdate = true; logger.Information("Reprojection document {0}/{1}.", concreteDesign.DocumentType.FullName, key, currentDocumentVersion, configuration.ConfiguredVersion); } if (migrator.ApplicableCommands(concreteDesign, currentDocumentVersion).Any()) { shouldUpdate = true; } if (shouldUpdate) { try { using (var session = new DocumentSession(store)) { session.Load(concreteDesign.DocumentType, key); session.SaveChanges(lastWriteWins: false, forceWriteUnchangedDocument: true); } } catch (ConcurrencyException) { } catch (Exception exception) { logger.Error(exception, "Error while migrating document of type {0} with id {1}.", concreteDesign.DocumentType.FullName, key); Thread.Sleep(100); } } else { logger.Information("Document did not change."); var projection = new Dictionary<string, object> { {table.VersionColumn, configuration.ConfiguredVersion} }; store.Update(table, key, (Guid)row[table.EtagColumn], projection); } } } } }, TaskCreationOptions.LongRunning); }
/// <summary> /// Opens the session. /// </summary> /// <returns></returns> public IDocumentSession OpenSession() { var session = new DocumentSession(this, storeListeners, deleteListeners, DatabaseCommands); session.Stored += OnSessionStored; return session; }
public IDocumentSession OpenSession() { if(DatabaseCommands == null) throw new InvalidOperationException("You cannot open a session before initialising the document store. Did you forgot calling Initialise?"); var session = new DocumentSession(this, storeListeners, deleteListeners); session.Stored += OnSessionStored; return session; }
/// <summary> /// Opens the session. /// </summary> /// <returns></returns> public IDocumentSession OpenSession() { EnsureNotClosed(); var sessionId = Guid.NewGuid(); currentSessionId = sessionId; try { var session = new DocumentSession(this, sessionId, new SqlDatabaseCommands(new SqlConnection(this.ConnectionString), null, SqlDatabaseSettings.Default)); AfterSessionCreated(session); return session; } finally { currentSessionId = null; } }
public IDocumentSession OpenSession() { this.EnsureNotClosed(); Guid id = Guid.NewGuid(); DocumentStore.currentSessionId = new Guid?(id); try { DocumentSession documentSession = new DocumentSession(this, this.listeners, id, this.DatabaseCommands, this.AsyncDatabaseCommands); this.AfterSessionCreated((InMemoryDocumentSessionOperations) documentSession); return (IDocumentSession) documentSession; } finally { DocumentStore.currentSessionId = new Guid?(); } }
public override IDocumentSession OpenSession(OpenSessionOptions options) { EnsureNotClosed(); var sessionId = Guid.NewGuid(); currentSessionId = sessionId; try { var session = new DocumentSession(options.Database, this, Listeners, sessionId, SetupCommands(DatabaseCommands, options.Database, options.Credentials, options)) { DatabaseName = options.Database ?? DefaultDatabase ?? MultiDatabase.GetDatabaseName(Url) }; AfterSessionCreated(session); return session; } finally { currentSessionId = null; } }
/// <summary> /// Opens the session with the specified credentials. /// </summary> /// <param name="credentialsForSession">The credentials for session.</param> public IDocumentSession OpenSession(ICredentials credentialsForSession) { if (!String.IsNullOrEmpty(DefaultDatabase)) return OpenSession(DefaultDatabase, credentialsForSession); var session = new DocumentSession(this, storeListeners, deleteListeners, DatabaseCommands.With(credentialsForSession)); session.Stored += OnSessionStored; return session; }
public void A_cabin_session() { DocumentSessionFactory.SetEngineFactory(str => new FileStorageEngine(str)); Session = DocumentSessionFactory.Create("session.specs.store"); }
/// <summary> /// Opens the session. /// </summary> /// <returns></returns> public IDocumentSession OpenSession() { if (string.IsNullOrEmpty(DefaultDatabase) == false) return OpenSession(DefaultDatabase); var session = new DocumentSession(this, storeListeners, deleteListeners, DatabaseCommands); session.Stored += OnSessionStored; return session; }