public ActionResult Handle([FromBody] CommandRequest command) { var content = new ContentResult(); CommandResult result = null; try { _executionContextConfigurator.ConfigureFor(_tenantResolver.Resolve(HttpContext.Request), command.CorrelationId, ClaimsPrincipal.Current.ToClaims()); result = _commandCoordinator.Handle(command); } catch (Exception ex) { _logger.Error(ex, "Could not handle command request"); result = new CommandResult() { Command = command, Exception = ex, ExceptionMessage = ex.Message }; } content.Content = _serializer.ToJson(result, SerializationOptions.CamelCase); content.ContentType = "application/json"; return(content); }
public void Append(AggregateCommit aggregateCommit) { if (ReferenceEquals(null, aggregateCommit) == true) { throw new ArgumentNullException(nameof(aggregateCommit)); } var tenant = tenantResolver.Resolve(aggregateCommit); var store = factory.GetEventStore(tenant); store.Append(aggregateCommit); }
public ActionResult Handle([FromBody] QueryRequest queryRequest) { _executionContextConfigurator.ConfigureFor(_tenantResolver.Resolve(HttpContext.Request), Dolittle.Execution.CorrelationId.New(), ClaimsPrincipal.Current.ToClaims()); QueryResult queryResult = null; try { _logger.Information($"Executing query : {queryRequest.NameOfQuery}"); var queryType = _typeFinder.GetQueryTypeByName(queryRequest.GeneratedFrom); var query = _container.Get(queryType) as IQuery; PopulateProperties(queryRequest, queryType, query); queryResult = _queryCoordinator.Execute(query, new PagingInfo()); if (queryResult.Success) { AddClientTypeInformation(queryResult); } } catch (Exception ex) { _logger.Error(ex, $"Error executing query : '{queryRequest.NameOfQuery}'"); queryResult = new QueryResult { Exception = ex }; } var content = new ContentResult(); content.Content = _serializer.ToJson(queryResult, SerializationOptions.CamelCase); content.ContentType = "application/json"; return(content); }
protected void Session_Start() { if (Context.Session != null) { if (Context.Session.IsNewSession) { string sCookieHeader = Request.Headers["Cookie"]; if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) { //intercept current route HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current); RouteData routeData = RouteTable.Routes.GetRouteData(currentContext); Response.Redirect("~/Home/SessionTimeout"); Response.Flush(); Response.End(); } } } //set session culture using DefaultCulture key IoCFactory.Container.StartSessionLevelContainer(); Session.ApplyCulture(AppConfiguration.DefaultCulture); ITenantResolver tenantResolver = IoCFactory.Container.Resolve <ITenantResolver>(); Tenant tenant = tenantResolver.Resolve(this.Request); this.Session.SetTenant(tenant); }
public bool Rebuild(Type projectionType, ProjectionVersion version, DateTime replayUntil) { DateTime startRebuildTimestamp = DateTime.UtcNow; int progressCounter = 0; log.Info(() => $"Start rebuilding projection `{projectionType.Name}` for version {version}. Deadline is {replayUntil}"); var projection = FastActivator.CreateInstance(projectionType) as IProjectionDefinition; var projectionEventTypes = GetInvolvedEvents(projectionType).ToList(); projectionStore.InitializeProjectionStore(version); snapshotStore.InitializeProjectionSnapshotStore(version); var indexState = index.GetIndexState(); if (indexState.IsPresent() == false) { return(false); } foreach (var eventType in projectionEventTypes) { log.Debug(() => $"Rebuilding projection `{projectionType.Name}` for version {version} using eventType `{eventType}`. Deadline is {replayUntil}"); var indexId = new EventStoreIndexEventTypeId(eventType); IEnumerable <ProjectionCommit> indexCommits = index.EnumerateCommitsByEventType(indexId); foreach (var indexCommit in indexCommits) { progressCounter++; if (progressCounter % 1000 == 0) { log.Trace(() => $"Rebuilding projection {projectionType.Name} => PROGRESS:{progressCounter} Version:{version} EventType:{eventType} Deadline:{replayUntil} Total minutes working:{(DateTime.UtcNow - startRebuildTimestamp).TotalMinutes}. logId:{Guid.NewGuid().ToString()}"); } // if the replay did not finish in time (specified by the AR) we need to abort. if (DateTime.UtcNow >= replayUntil) { log.Info(() => $"Rebuilding projection `{projectionType.Name}` stopped bacause the deadline has been reached. PROGRESS:{progressCounter} Version:{version} EventType:`{eventType}` Deadline:{replayUntil}."); return(false); } IAggregateRootId arId = GetAggregateRootId(indexCommit.EventOrigin.AggregateRootId); IEventStore eventStore = eventStoreFactory.GetEventStore(tenantResolver.Resolve(arId)); EventStream stream = eventStore.Load(arId, theId => projectionType.GetBoundedContext().BoundedContextName); foreach (AggregateCommit arCommit in stream.Commits) { for (int i = 0; i < arCommit.Events.Count; i++) { IEvent theEvent = arCommit.Events[i].Unwrap(); if (projectionEventTypes.Contains(theEvent.GetType().GetContractId())) { var origin = new EventOrigin(Convert.ToBase64String(arCommit.AggregateRootId), arCommit.Revision, i, arCommit.Timestamp); projectionRepository.Save(projectionType, theEvent, origin); // overwrite } } } } } log.Info(() => $"Finish rebuilding projection `{projectionType.Name}` for version {version}. Deadline was {replayUntil}"); return(true); }
protected void Session_Start() { ITenantResolver tenantResolver = IoCFactory.Container.Resolve <ITenantResolver>(); Tenant tenant = tenantResolver.Resolve(this.Request); this.Session.SetTenant(tenant); }
protected void Session_Start() { if (Context.Session != null) { if (Context.Session.IsNewSession) { string sCookieHeader = Request.Headers["Cookie"]; if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) { //intercept current route HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current); RouteData routeData = RouteTable.Routes.GetRouteData(currentContext); Response.Redirect("~/Home/SessionTimeout"); Response.Flush(); Response.End(); } } } //set session culture using DefaultCulture key IoCFactory.Container.StartSessionLevelContainer(); Session.ApplyCulture(AppConfiguration.DefaultCulture); ITenantResolver tenantResolver = IoCFactory.Container.Resolve <ITenantResolver>(); Tenant tenant = tenantResolver.Resolve(this.Request); // if the tenant has no landing page, set the application's default landing page for it. GeneralSettings generalSettings = IoCFactory.Container.Resolve <GeneralSettings>(); var landingPage = generalSettings.GetEntryValue("landingPage").ToString(); tenant.LandingPage = landingPage; // checks and sets this.Session.SetTenant(tenant); }
void EnsureTenantIsSet(IServiceScope scope, CronusMessage message) { var cronusContext = scope.ServiceProvider.GetRequiredService <CronusContext>(); if (cronusContext.IsNotInitialized) { string tenant = tenantResolver.Resolve(message); cronusContext.Initialize(tenant, scope.ServiceProvider); } }
public ActionResult Handle([FromBody] CommandRequest command) { _executionContextConfigurator.ConfigureFor(_tenantResolver.Resolve(HttpContext.Request), command.CorrelationId, ClaimsPrincipal.Current.ToClaims()); var result = _commandCoordinator.Handle(command); var content = new ContentResult(); content.Content = _serializer.ToJson(result, SerializationOptions.CamelCase); content.ContentType = "application/json"; return(content); }
public CronusContext GetContext(object obj, IServiceProvider serviceProvider) { if (context.IsNotInitialized) { string tenant = tenantResolver.Resolve(obj); EnsureValidTenant(tenant); context.Tenant = tenant; context.ServiceProvider = serviceProvider; } return(context); }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { var accessor = context.RequestServices.GetRequiredService <ICurrentTenantAccessor>(); if (accessor.CurrentTenant == null) { var tenate = await _tenantResolver.Resolve(context).ConfigureAwait(false); accessor.CurrentTenant = tenate; } await next.Invoke(context).ConfigureAwait(false); }
public async Task Invoke( HttpContext httpContext, IExportLocatorScope locatorScope, Lazy <ITenantContainerBuilder <TTenant> > builder ) { var tenant = _tenantResolver.Resolve(httpContext); using (var scope = await builder.Value.BuildAsync(tenant)) { httpContext.RequestServices = scope.Locate <IServiceProvider>(); await _next(httpContext); } }
public async Task <IActionResult> Handle([FromBody] QueryRequest queryRequest) { var content = new ContentResult(); QueryResult queryResult = null; try { _executionContextConfigurator.ConfigureFor(_tenantResolver.Resolve(HttpContext.Request), Dolittle.Execution.CorrelationId.New(), ClaimsPrincipal.Current.ToClaims()); _logger.Information($"Executing query : {queryRequest.NameOfQuery}"); var queryType = _typeFinder.GetQueryTypeByName(queryRequest.GeneratedFrom); var query = _container.Get(queryType) as IQuery; var properties = queryType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty).ToDictionary(p => p.Name.ToLowerInvariant(), p => p); CopyPropertiesFromRequestToQuery(queryRequest, query, properties); queryResult = await _queryCoordinator.Execute(query, new PagingInfo()); if (queryResult.Success) { AddClientTypeInformation(queryResult); } } catch (Exception ex) { _logger.Error(ex, $"Error executing query : '{queryRequest.NameOfQuery}'"); queryResult = new QueryResult { Exception = ex, QueryName = queryRequest.NameOfQuery }; } content.Content = _serializer.ToJson(queryResult, SerializationOptions.CamelCase); content.ContentType = "application/json"; return(content); }
public async Task Invoke(HttpContext ctx, ITenantResolver tenantResolver, DatabaseContext db) { var host = ctx.Request.GetTypedHeaders().Host.Value; var tenant = await tenantResolver.Resolve(host); if (tenant == null) { throw new Exception("Tenant not found"); } else { db.SetActiveTenant(tenant); await Next(ctx); } }
protected virtual Dictionary <string, string> BuildHeaders(TMessage message, Dictionary <string, string> messageHeaders) { messageHeaders = messageHeaders ?? new Dictionary <string, string>(); if (messageHeaders.ContainsKey(MessageHeader.PublishTimestamp) == false) { messageHeaders.Add(MessageHeader.PublishTimestamp, DateTime.UtcNow.ToFileTimeUtc().ToString()); } if (messageHeaders.ContainsKey(MessageHeader.Tenant) == false) { messageHeaders.Add(MessageHeader.Tenant, tenantResolver.Resolve(message)); } if (messageHeaders.ContainsKey(MessageHeader.BoundedContext)) { var bc = message.GetType().GetBoundedContext(boundedContext.Name); messageHeaders[MessageHeader.BoundedContext] = bc; } else { var bc = message.GetType().GetBoundedContext(boundedContext.Name); messageHeaders.Add(MessageHeader.BoundedContext, bc); } string messageId = string.Empty; if (messageHeaders.ContainsKey(MessageHeader.MessageId) == false) { messageId = $"urn:cronus:{messageHeaders[MessageHeader.BoundedContext]}:{messageHeaders[MessageHeader.Tenant]}:{Guid.NewGuid()}"; messageHeaders.Add(MessageHeader.MessageId, messageId); } else { messageId = messageHeaders[MessageHeader.MessageId]; } if (messageHeaders.ContainsKey(MessageHeader.CorelationId) == false) { messageHeaders.Add(MessageHeader.CorelationId, messageId); } messageHeaders.Remove("contract_name"); messageHeaders.Add("contract_name", message.GetType().GetContractId()); return(messageHeaders); }
public async Task Invoke(HttpContext context, ITenantResolver tenantResolver) { if (context.Request.RouteValues.ContainsKey(RouteValueKey)) { var tenant = tenantResolver.Resolve(); var user = context.User; if (!UserHasPermissionForTenant(tenant, user)) { context.Response.StatusCode = 401; await context.Response.WriteAsync($"You do not have permission to access '{tenant}'."); return; } } await _next.Invoke(context); }
public async Task Invoke(HttpContext context, ITenantResolver <TTenant> tenantResolver) { log.LogDebug("Resolving TenantContext using {loggerType}.", tenantResolver.GetType().Name); var tenantContext = await tenantResolver.Resolve(context); if (tenantContext != null) { log.LogDebug("TenantContext Resolved. Adding to HttpContext."); context.SetTenantContext(tenantContext); } else { log.LogDebug("TenantContext Not Resolved."); } await next.Invoke(context); }
/// <inheritdoc /> public async Task Handle(HttpRequest request, HttpResponse response, RouteData routeData) { _executionContextConfigurator.ConfigureFor(_tenantResolver.Resolve(request), Guid.NewGuid(), ClaimsPrincipal.Current.ToClaims()); var installationId = long.Parse(request.Query["installation_id"].Single()); switch (request.Query["setup_action"].Single()) { case "install": _callbackHandler.Install(installationId, response); break; case "update": _callbackHandler.Update(installationId, response); break; } await Task.CompletedTask; }
public void Process(CronusMessage message) { using (IServiceScope scope = ioc.CreateScope()) { var cronusContext = scope.ServiceProvider.GetRequiredService <CronusContext>(); if (cronusContext.IsNotInitialized) { string tenant = tenantResolver.Resolve(message); cronusContext.Initialize(tenant, scope.ServiceProvider); } var index = indexProvider(scope); var indexRecord = new List <IndexRecord>(); var @event = message.Payload as IEvent; string eventTypeId = @event.Unwrap().GetType().GetContractId(); indexRecord.Add(new IndexRecord(eventTypeId, Encoding.UTF8.GetBytes(message.GetRootId()))); index.Apend(indexRecord); } }
public bool Publish(TMessage message, Dictionary <string, string> messageHeaders) { try { messageHeaders = messageHeaders ?? new Dictionary <string, string>(); string messageId = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); messageHeaders.Add(MessageHeader.MessageId, messageId); if (messageHeaders.ContainsKey(MessageHeader.CorelationId) == false) { messageHeaders.Add(MessageHeader.CorelationId, messageId); } if (messageHeaders.ContainsKey(MessageHeader.PublishTimestamp) == false) { messageHeaders.Add(MessageHeader.PublishTimestamp, DateTime.UtcNow.ToFileTimeUtc().ToString()); } if (messageHeaders.ContainsKey(MessageHeader.Tenant) == false) { messageHeaders.Add(MessageHeader.Tenant, tenantResolver.Resolve(message)); } var cronusMessage = new CronusMessage(message, messageHeaders); var published = PublishInternal(cronusMessage); if (published == false) { log.Error(() => "Failed to publish => " + BuildDebugLog(message, messageHeaders)); return(false); } log.Info(() => message.ToString()); log.Debug(() => "PUBLISH => " + BuildDebugLog(message, messageHeaders)); return(true); } catch (Exception ex) { log.ErrorException(ex.Message, ex); return(false); } }
/// <summary> /// Method to receive a new request /// </summary> /// <param name="context">The OWIN Context</param> /// <returns>The next Task</returns> public override async Task Invoke(IOwinContext context) { var tenant = Resolver.Resolve(context.Request); if (tenant != null) { tenant.Resolver = Resolver; var callBackResult = Callback?.Invoke(tenant); if (callBackResult == false) { // Do something maybe } } context.Set(OwinPropertyName, tenant); await Next.Invoke(context); }
private DbContextOptions BuildTenantOptions() { var tenant = _tenantResolver.Resolve(); var key = $"ConnString_{tenant}"; var optionsBuilder = new DbContextOptionsBuilder <TenantContext>(); string connectionString; if (!_cache.TryGetValue(key, out connectionString)) { var authContext = (AuthContext)_serviceProvider.GetRequiredService(typeof(AuthContext)); connectionString = authContext.Tenants .Where(x => x.Name.ToUpper() == tenant.ToUpper()) .Select(x => x.ConnectionString) .SingleOrDefault(); _cache.Set(key, connectionString); } optionsBuilder.UseSqlServer(connectionString); return(optionsBuilder.Options); }
public async Task Handle(HttpRequest request, HttpResponse response, RouteData routeData) { // TODO: This endpoint should be secured like all the others, so that when the final request gets here, we should know the tenant _executionContextConfigurator.ConfigureFor(_tenantResolver.Resolve(request), Guid.NewGuid(), ClaimsPrincipal.Current.ToClaims()); var installationId = long.Parse(request.Query["installation_id"].Single()); switch (request.Query["setup_action"].Single()) { case "install": _callbackHandler.Install(installationId, response); break; case "update": _callbackHandler.Update(installationId, response); break; } await Task.CompletedTask; }
public IActionResult Get() { _executionContextConfigurator.ConfigureFor(_tenantResolver.Resolve(HttpContext.Request), Dolittle.Execution.CorrelationId.New(), ClaimsPrincipal.Current.ToClaims()); return(Ok(_allCaseReports().Query.ToList())); }
public bool Publish(TMessage message, Dictionary <string, string> messageHeaders) { try { messageHeaders = messageHeaders ?? new Dictionary <string, string>(); string messageId = string.Empty; if (messageHeaders.ContainsKey(MessageHeader.MessageId) == false) { messageHeaders.Add(MessageHeader.MessageId, messageId); } else { messageId = messageHeaders[MessageHeader.MessageId]; } if (messageHeaders.ContainsKey(MessageHeader.CorelationId) == false) { messageHeaders.Add(MessageHeader.CorelationId, messageId); } if (messageHeaders.ContainsKey(MessageHeader.PublishTimestamp) == false) { messageHeaders.Add(MessageHeader.PublishTimestamp, DateTime.UtcNow.ToFileTimeUtc().ToString()); } if (messageHeaders.ContainsKey(MessageHeader.Tenant) == false) { messageHeaders.Add(MessageHeader.Tenant, tenantResolver.Resolve(message)); } if (messageHeaders.ContainsKey(MessageHeader.BoundedContext)) { if (messageHeaders[MessageHeader.BoundedContext] == "implicit") { messageHeaders[MessageHeader.BoundedContext] = boundedContext.Name; } } else { var bc = message.GetType().GetBoundedContext(boundedContext.Name); messageHeaders.Add(MessageHeader.BoundedContext, bc); } var cronusMessage = new CronusMessage(message, messageHeaders); var published = PublishInternal(cronusMessage); if (published == false) { logger.Error(() => "Failed to publish => " + BuildDebugLog(message, messageHeaders)); return(false); } logger.Info(() => message.ToString()); logger.Debug(() => "PUBLISH => " + BuildDebugLog(message, messageHeaders)); return(true); } catch (Exception ex) { logger.ErrorException(ex, () => ex.Message); return(false); } }
/// <summary> /// 解析租户编号 /// </summary> /// <param name="resultModel"></param> /// <returns></returns> protected Task ResolveTenant(LoginResultModel resultModel) { //解析租户编号 return(_tenantResolver.Resolve(resultModel)); }
public AnnalContext(ITenantResolver tenantResolver) { _tenant = tenantResolver.Resolve().GetAwaiter().GetResult(); Database.EnsureCreated(); }
public IContainer Resolve(ITenantResolver resolver) { return(resolver.Resolve(this.Tenants).DependencyContainer); }