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 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 Question Store(Question question) { Condition.Requires(question).IsNotNull(); // First, validate the question. ValidateQuestion(question); if (!string.IsNullOrEmpty(question.Id)) { var existingQuestion = DocumentSession.Load <Question>(question.Id); if (existingQuestion != null) { existingQuestion.Subject = question.Subject; existingQuestion.Content = question.Content; existingQuestion.Tags = question.Tags; existingQuestion.CreatedByUserId = question.CreatedByUserId; question = existingQuestion; } } // Save. DocumentSession.Store(question); return(question); }
public ActionResult Delete(int id) { var product = DocumentSession.Load <Product>(id); DocumentSession.Delete(product); return(RedirectToAction("Index")); }
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 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 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()); }
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 OilPattern(string id) { Roster roster = DocumentSession.Load <Roster>(id); ViewBag.Url = roster.OilPattern.Url; return(View("_BitsIframe")); }
public IActionResult CreateSqlServer([FromBody] NewSqlServer newDatabaseServer) { if (newDatabaseServer == null) { return(BadRequest(new { EntityType = "DatabaseServer", Reason = "InvalidRequest", Message = "Must supply database details in the request body." })); } Tenant tenant = DocumentSession.Load <Tenant>(newDatabaseServer.TenantId); if (tenant == null) { return(NotFound(new { Id = newDatabaseServer.TenantId, EntityType = "Tenant", Message = $"No tenant found with Id {newDatabaseServer.TenantId}." })); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var databaseServer = new DatabaseServer { Name = newDatabaseServer.Name, Kind = DatabaseServerKind.SqlServer, Settings = new SqlServerSettings { AdminPassword = newDatabaseServer.AdminPassword, Storage = { SizeMB = newDatabaseServer.SizeMB } }, TenantId = tenant.Id, Action = ProvisioningAction.Provision, Status = ProvisioningStatus.Pending, }; DocumentSession.Store(databaseServer); databaseServer.AddProvisioningEvent($"Provisioning requested for '${databaseServer.Id}'."); DocumentSession.SaveChanges(); return(StatusCode(StatusCodes.Status202Accepted, new { Id = databaseServer.Id, Name = databaseServer.Name, Message = $"SQL Server instance {databaseServer.Id} queued for creation." })); }
public HttpResponseMessage Delete(int id) { var config = DocumentSession.Load <TaxRate>(id); DocumentSession.Delete(config); return(new HttpResponseMessage(HttpStatusCode.OK)); }
public ActionResult Details(Guid id) { var aircraftReadModel = DocumentSession.Load <AircraftReadModel>(id); var model = new AircraftModel(aircraftReadModel); return(View("Details", model)); }
public ActionResult Details(Guid id) { var siteData = DocumentSession.Load <SiteReadModel>(id); var model = new SiteModel(siteData); return(View("Details", model)); }
public ActionResult Details(Guid id) { var personReadModel = DocumentSession.Load <PersonReadModel>(id); var model = new PersonModel(personReadModel); return(View("Details", model)); }
public OptimisticConcurrency() { using (var store = new DocumentStore()) { #region optimistic_concurrency_1 using (IDocumentSession session = store.OpenSession()) { session.Advanced.UseOptimisticConcurrency = true; Product product = new Product { Name = "Some Name" }; session.Store(product, "products/999"); session.SaveChanges(); using (IDocumentSession otherSession = store.OpenSession()) { Product otherProduct = otherSession.Load <Product>("products/999"); otherProduct.Name = "Other Name"; otherSession.SaveChanges(); } product.Name = "Better Name"; session.SaveChanges(); // will throw ConcurrencyException } #endregion #region optimistic_concurrency_2 store.Conventions.DefaultUseOptimisticConcurrency = true; using (IDocumentSession session = store.OpenSession()) { bool isSessionUsingOptimisticConcurrency = session.Advanced.UseOptimisticConcurrency; // will return true } #endregion #region optimistic_concurrency_3 store.Conventions.DefaultUseOptimisticConcurrency = true; using (DocumentSession session = (DocumentSession)store.OpenSession()) using (session.DatabaseCommands.ForceReadFromMaster()) { // In replicated setup where ONLY reads are load balanced (FailoverBehavior.ReadFromAllServers) // and optimistic concurrency checks are turned on // you must set 'ForceReadFromMaster' to get the appropriate ETag value for the document // when you want to perform document updates (writes) // because writes will go to the master server and ETag values between servers are not synchronized Product product = session.Load <Product>("products/999"); product.Name = "New Name"; session.SaveChanges(); } #endregion } }
private async Task <IHttpActionResult> Handle(GetPlayersFromBitsMessage message) { WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId); PlayerResult playersResult = await bitsClient.GetPlayers(websiteConfig.ClubId); Player[] players = DocumentSession.Query <Player, PlayerSearch>() .ToArray(); // update existing players by matching on license number var playersByLicense = playersResult.Data.ToDictionary(x => x.LicNbr); foreach (Player player in players.Where(x => x.PlayerItem != null)) { if (playersByLicense.TryGetValue(player.PlayerItem.LicNbr, out PlayerItem playerItem)) { player.PlayerItem = playerItem; playersByLicense.Remove(player.PlayerItem.LicNbr); Log.Info($"Updating player with existing PlayerItem: {player.PlayerItem.LicNbr}"); } else { Log.Info($"Player with {player.PlayerItem.LicNbr} not found from BITS"); } } // add missing players, i.e. what is left from first step // try first to match on name, update those, add the rest var playerNamesWithoutPlayerItem = players.Where(x => x.PlayerItem == null).ToDictionary(x => x.Name); foreach (PlayerItem playerItem in playersByLicense.Values) { // look for name string nameFromBits = $"{playerItem.FirstName} {playerItem.SurName}"; if (playerNamesWithoutPlayerItem.TryGetValue(nameFromBits, out Player player)) { player.PlayerItem = playerItem; Log.Info($"Updating player with missing PlayerItem: {nameFromBits}"); } else { // create new var newPlayer = new Player( $"{playerItem.FirstName} {playerItem.SurName}", playerItem.Email, playerItem.Inactive ? Player.Status.Inactive : Player.Status.Active, playerItem.GetPersonalNumber(), string.Empty, new string[0]) { PlayerItem = playerItem }; Log.Info($"Created player {playerItem.FirstName} {playerItem.SurName}"); DocumentSession.Store(newPlayer); } } return(Ok()); }
public void DeserializeRegularClass() { var session = new DocumentSession(); var doc = session.Load <TestClass>("1"); Assert.Equal("1", doc.Id); Assert.Equal("test", doc.Name); }
public void TestWithCustomTheory(string id) { var session = new DocumentSession(); var doc = session.Load <dynamic>("1"); Assert.Equal("1", (string)doc.Id); Assert.Equal("test", (string)doc.Name); }
public ActionResult Delete(int id) { var contato = DocumentSession.Load <Contato>(id); DocumentSession.Delete(contato); TempData["success"] = "Contato deletado com sucesso"; return(null); }
private async Task <IHttpActionResult> Handle(RegisterMatchMessage message) { WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId); Player[] players = DocumentSession.Query <Player, PlayerSearch>() .ToArray() .Where(x => x.PlayerItem?.LicNbr != null) .ToArray(); Roster pendingMatch = DocumentSession.Load <Roster>(message.RosterId); try { var parser = new BitsParser(players); BitsMatchResult bitsMatchResult = await bitsClient.GetBitsMatchResult(pendingMatch.BitsMatchId); if (bitsMatchResult.HeadInfo.MatchFinished == false) { Log.Info($"Match {pendingMatch.BitsMatchId} not yet finished"); return(Ok()); } if (pendingMatch.IsFourPlayer) { Parse4Result parse4Result = parser.Parse4(bitsMatchResult, websiteConfig.ClubId); if (parse4Result != null) { List <string> allPlayerIds = GetPlayerIds(parse4Result); pendingMatch.SetPlayers(allPlayerIds); ExecuteCommand(new RegisterMatch4Command(pendingMatch, parse4Result)); } } else { ParseResult parseResult = parser.Parse(bitsMatchResult, websiteConfig.ClubId); if (parseResult != null) { List <string> allPlayerIds = GetPlayerIds(parseResult); pendingMatch.SetPlayers(allPlayerIds); ExecuteCommand(new RegisterMatchCommand(pendingMatch, parseResult)); } } } catch (Exception e) { ErrorSignal .FromCurrentContext() .Raise(new Exception($"Unable to auto register match {pendingMatch.Id} ({pendingMatch.BitsMatchId})", e)); Log.Warn(e); return(Ok(e.ToString())); } return(Ok()); }
private IHttpActionResult Handle(GetTeamNamesQuery query) { WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId); GetTeamNamesQuery.TeamNameAndLevel[] teamNameAndLevels = websiteConfig.TeamNamesAndLevels .Select(x => new GetTeamNamesQuery.TeamNameAndLevel(x.TeamName, x.Level)) .ToArray(); var result = new GetTeamNamesQuery.Result(teamNameAndLevels); return(Ok(result)); }
public int Copy(int id) { var taxRate = DocumentSession.Load <TaxRate>(id); var copy = Mapper.Map <TaxRate>(taxRate); copy.CreateAt = DateTime.Now; DocumentSession.Store(copy); return(copy.Id); }
private List <User> ConvertResultsToUsersViewModel(List <Users_Smart_Search.Projection> inputList) { List <User> result = new List <User>(); var roles = DocumentSession.Load <Roles>("Roles-1"); foreach (var i in inputList) { result.Add(i.ToUserViewModel(roles)); } return(result); }
public virtual RenderJsonResult VerifyWebAccount(long webAccountId) { var account = DocumentSession.Load <WebAccount>(webAccountId); if (account == null) { return(this.RenderJsonErrorCode(1, "Missing Account")); } account.Verify(); return(this.RenderJsonSuccessErrorCode()); }
public virtual ActionResult Link(long id) { var account = DocumentSession.Load <WebAccount>(id); if (account == null) { return(Content("Account Not Found")); } ViewBag.Id = id; return(View(account)); }
public IHttpActionResult Get(int id) { var taxRate = DocumentSession.Load <TaxRate>(id); if (taxRate == null) { return(NotFound()); } return(Ok(taxRate)); }
public ActionResult Create() { WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId); ViewBag.TeamNamesAndLevels = websiteConfig.TeamNamesAndLevels; var vm = new CreateRosterViewModel { Season = DocumentSession.LatestSeasonOrDefault(DateTime.Now.Year) }; return(View(vm)); }
public ActionResult DeletePhone(int id, TelefoneViewModel telefoneViewModel) { var telefone = Mapper.Map <TelefoneViewModel, Telefone>(telefoneViewModel); var contato = DocumentSession.Load <Contato>(id); contato.RemoveTelefone(telefone); TempData["success"] = string.Format("Telefone {0} removido.", telefone); return(null); }
private IHttpActionResult Handle(RegisterMatchesMessage message) { WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId); Roster[] pendingMatches = ExecuteQuery(new GetPendingMatchesQuery(websiteConfig.SeasonId)); foreach (Roster pendingMatch in pendingMatches.Where(x => x.SkipRegistration == false)) { PublishMessage(new RegisterMatchMessage(pendingMatch.Id)); } return(Ok()); }
public ActionResult Featured(int count = 10) { var featuredApps = DocumentSession .Load <AppsList>("AppsLists/1"); var apps = DocumentSession .Load <App>(featuredApps.Apps.RandomSample(count)); Debug.Assert(apps.All(a => a != null)); return(PartialView("ListApps", apps.Where(a => a != null))); }
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); }