Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        protected void Session_Start()
        {
            ITenantResolver tenantResolver = IoCFactory.Container.Resolve <ITenantResolver>();
            Tenant          tenant         = tenantResolver.Resolve(this.Request);

            this.Session.SetTenant(tenant);
        }
Ejemplo n.º 7
0
        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);
        }
Ejemplo n.º 8
0
        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);
            }
        }
Ejemplo n.º 9
0
        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);
        }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        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);
            }
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
        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);
            }
        }
Ejemplo n.º 15
0
        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);
        }
Ejemplo n.º 17
0
        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);
        }
Ejemplo n.º 18
0
        /// <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;
        }
Ejemplo n.º 19
0
        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);
            }
        }
Ejemplo n.º 20
0
        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);
            }
        }
Ejemplo n.º 21
0
        /// <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);
        }
Ejemplo n.º 22
0
        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);
        }
Ejemplo n.º 23
0
        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;
        }
Ejemplo n.º 24
0
        public IActionResult Get()
        {
            _executionContextConfigurator.ConfigureFor(_tenantResolver.Resolve(HttpContext.Request), Dolittle.Execution.CorrelationId.New(), ClaimsPrincipal.Current.ToClaims());

            return(Ok(_allCaseReports().Query.ToList()));
        }
Ejemplo n.º 25
0
        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);
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// 解析租户编号
 /// </summary>
 /// <param name="resultModel"></param>
 /// <returns></returns>
 protected Task ResolveTenant(LoginResultModel resultModel)
 {
     //解析租户编号
     return(_tenantResolver.Resolve(resultModel));
 }
Ejemplo n.º 27
0
 public AnnalContext(ITenantResolver tenantResolver)
 {
     _tenant = tenantResolver.Resolve().GetAwaiter().GetResult();
     Database.EnsureCreated();
 }
Ejemplo n.º 28
0
 public IContainer Resolve(ITenantResolver resolver)
 {
     return(resolver.Resolve(this.Tenants).DependencyContainer);
 }