Database layer for tenant related data
Inheritance: DbContext
        public void Can_get_and_set_tenant_context()
        {
            HttpContext httpContext = new DefaultHttpContext();

            var tenantContext = new TenantContext<TestTenant>(new TestTenant());
            httpContext.SetTenantContext(tenantContext);

            Assert.Same(tenantContext, httpContext.GetTenantContext<TestTenant>());
        }
Ejemplo n.º 2
0
 public PortfolioRepository(TenantContext context)
 {
     _context = context;
 }
Ejemplo n.º 3
0
        private IServiceProvider GetProviderFromFactory(IServiceCollection collectionClone, TenantContext <TTenant> tenantContext)
        {
            ServiceProvider provider = collectionClone.BuildServiceProvider();
            IServiceProviderFactory <IServiceCollection> factory = provider.GetService <IServiceProviderFactory <IServiceCollection> >();

            using (provider)
            {
                return(factory.CreateServiceProvider(factory.CreateBuilder(collectionClone)));
            }
        }
Ejemplo n.º 4
0
 public DashboardController(TenantContext context)
 {
     _context = context;
 }
Ejemplo n.º 5
0
        private async Task <RequestResult <AuthorizationData> > AddFacebookToExistingUser(TokenInfo tokenInfo,
                                                                                          TenantContext requestTenant)
        {
            var user = await _authRepository
                       .AddFacebookLoginToUser(requestTenant.TenantId, tokenInfo.Email, tokenInfo.ExternalUserId);

            await _avatarRepository
            .StoreAvatar(user.Id, AvatarType.Facebook, tokenInfo.ImageUrl);

            return(await GetAuthorizationDataResult(requestTenant, user));
        }
Ejemplo n.º 6
0
        private async Task <RequestResult <AuthorizationData> > GetAuthorizationDataResult(TenantContext requestTenant,
                                                                                           TenantUser user)
        {
            var tenantSettings = await _tenantsRepository.GetTenantSettings(requestTenant.TenantId);

            var token = _jwtTokenFactory.Create(user, tenantSettings, requestTenant.TenantCode);

            return(RequestResult <AuthorizationData>
                   .Success(
                       new AuthorizationData
            {
                Token = token,
                User = _mapper.Map <UserDto>(user),
            }));
        }
Ejemplo n.º 7
0
 protected override string GetTenantProfileName(TenantContext <AppTenant> tenantContext)
 {
     return(tenantContext.Tenant.Name);
 }
 public TestTenantIdConstraintsTypeDbContext(TenantContext tenantContext,
                                             DbContextOptions <TestTenantIdConstraintsTypeDbContext> options) :
     base(tenantContext, options)
 {
 }
Ejemplo n.º 9
0
 public static void SetTenantContext(this IOwinContext context, TenantContext tenantContext)
 {
     context.Environment.Add(tenantContextKey, tenantContext);
 }
Ejemplo n.º 10
0
 protected MultiTenantIdentityDbContext(TenantContext tenantContext, DbContextOptions options) : base(tenantContext, options)
 {
 }
Ejemplo n.º 11
0
 public void TearDown()
 {
     TenantContext.Exit();
     _container.Dispose();
 }
 public CapacidadHandlerEF(TenantContext tc)
 {
     ctx = tc;
 }
 public BroadcastController(IGroupService groupService,
                            IStopService stopService, TenantContext tenantContext)
 {
     this.stopService   = stopService;
     this.tenantContext = tenantContext;
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Checks the <c>TenantId</c> on entities taking into account
        /// the <c>tenantNotSetMode</c> and the <c>tenantMismatchMode</c>.
        /// </summary>
        /// <remarks>
        ///     <list type="bullet">
        ///         <item><description>This method is called from <c>SaveChanges</c> or <c>SaveChangesAsync</c> of the derived <c>DbContext</c>.</description></item>
        ///         <item><description>If any changes are detected in an entitiy with the <c>MultiTenant</c> attribute then the <c>TenantContext</c> must not be null.</description></item>
        ///     </list>
        /// </remarks>
        /// /// <param name="tenantContext"></param>
        /// <param name="changeTracker"></param>
        /// <param name="tenantNotSetMode"></param>
        /// <param name="tenantMismatchMode"></param>
        internal static void EnforceTenantId(TenantContext tenantContext,
                                             ChangeTracker changeTracker,
                                             TenantNotSetMode tenantNotSetMode,
                                             TenantMismatchMode tenantMismatchMode)
        {
            var changedMultiTenantEntities = changeTracker.Entries().
                                             Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted).
                                             Where(e => e.Entity.GetType().GetCustomAttribute <MultiTenantAttribute>() != null);

            // ensure tenant context is valid
            if (changedMultiTenantEntities.Any())
            {
                CheckTenantContext(tenantContext);
            }

            // get list of all added entities with TenantScope attribute
            var addedTenantScopeEntities = changedMultiTenantEntities.
                                           Where(e => e.State == EntityState.Added);

            // handle Tenant Id mismatches for added entities
            var mismatchedAdded = addedTenantScopeEntities.
                                  Where(e => (string)e.Property("TenantId").CurrentValue != null &&
                                        (string)e.Property("TenantId").CurrentValue != tenantContext.Id);

            if (mismatchedAdded.Any())
            {
                switch (tenantMismatchMode)
                {
                case TenantMismatchMode.Throw:
                    throw new MultiTenantException($"{mismatchedAdded.Count()} added entities with Tenant Id mismatch.");;

                case TenantMismatchMode.Ignore:
                    // no action needed
                    break;

                case TenantMismatchMode.Overwrite:
                    foreach (var e in mismatchedAdded)
                    {
                        e.Property("TenantId").CurrentValue = tenantContext.Id;
                    }
                    break;
                }
            }

            // for added entities TenantNotSetMode is always Overwrite
            var notSetAdded = addedTenantScopeEntities.
                              Where(e => (string)e.Property("TenantId").CurrentValue == null);

            foreach (var e in notSetAdded)
            {
                e.Property("TenantId").CurrentValue = tenantContext.Id;
            }

            // get list of all modified entities with TenantScope attribute
            var modifiedTenantScopeEntities = changedMultiTenantEntities.
                                              Where(e => e.State == EntityState.Modified);

            // handle Tenant Id mismatches for modified entities
            var mismatchedModified = modifiedTenantScopeEntities.
                                     Where(e => (string)e.Property("TenantId").CurrentValue != null &&
                                           (string)e.Property("TenantId").CurrentValue != tenantContext.Id);

            if (mismatchedModified.Any())
            {
                switch (tenantMismatchMode)
                {
                case TenantMismatchMode.Throw:
                    throw new MultiTenantException($"{mismatchedModified.Count()} modified entities with Tenant Id mismatch.");;

                case TenantMismatchMode.Ignore:
                    // no action needed
                    break;

                case TenantMismatchMode.Overwrite:
                    foreach (var e in mismatchedModified)
                    {
                        e.Property("TenantId").CurrentValue = tenantContext.Id;
                    }
                    break;
                }
            }

            // handle Tenant Id not set for modified entities
            var notSetModified = modifiedTenantScopeEntities.
                                 Where(e => (string)e.Property("TenantId").CurrentValue == null);

            if (notSetModified.Any())
            {
                switch (tenantNotSetMode)
                {
                case TenantNotSetMode.Throw:
                    throw new MultiTenantException($"{notSetModified.Count()} modified entities with Tenant Id not set.");;

                case TenantNotSetMode.Overwrite:
                    foreach (var e in notSetModified)
                    {
                        e.Property("TenantId").CurrentValue = tenantContext.Id;
                    }
                    break;
                }
            }

            // get list of all deleted  entities with TenantScope attribute
            var deletedTenantScopeEntities = changedMultiTenantEntities.
                                             Where(e => e.State == EntityState.Deleted);

            // handle Tenant Id mismatches for deleted entities
            var mismatchedDeleted = deletedTenantScopeEntities.
                                    Where(e => (string)e.Property("TenantId").CurrentValue != null &&
                                          (string)e.Property("TenantId").CurrentValue != tenantContext.Id);

            if (mismatchedDeleted.Any())
            {
                switch (tenantMismatchMode)
                {
                case TenantMismatchMode.Throw:
                    throw new MultiTenantException($"{mismatchedDeleted.Count()} deleted entities with Tenant Id mismatch.");;

                case TenantMismatchMode.Ignore:
                    // no action needed
                    break;

                case TenantMismatchMode.Overwrite:
                    // no action needed
                    break;
                }
            }

            // handle Tenant Id not set for deleted entities
            var notSetDeleted = deletedTenantScopeEntities.
                                Where(e => (string)e.Property("TenantId").CurrentValue == null);

            if (notSetDeleted.Any())
            {
                switch (tenantNotSetMode)
                {
                case TenantNotSetMode.Throw:
                    throw new MultiTenantException($"{notSetDeleted.Count()} deleted entities with Tenant Id not set.");;

                case TenantNotSetMode.Overwrite:
                    // no action needed
                    break;
                }
            }
        }
Ejemplo n.º 15
0
 protected override IEnumerable <string> GetTenantIdentifiers(TenantContext <Tenant> context)
 => new string[]
 {
     context.Tenant.Domain
 };
 public TestWrongTenantIdTypeDbContext(TenantContext tenantContext,
                                       DbContextOptions <TestWrongTenantIdTypeDbContext> options) :
     base(tenantContext, options)
 {
 }
Ejemplo n.º 17
0
        private async Task InitAsync()
        {
            _maxDispatchedCheckpoint = 0;
            DumpProjections();

            TenantContext.Enter(_config.TenantId);

            await _housekeeper.InitAsync().ConfigureAwait(false);

            await ConfigureProjectionsAsync().ConfigureAwait(false);

            // cleanup
            await _housekeeper.RemoveAllAsync(_persistence).ConfigureAwait(false);

            var allSlots = _projectionsBySlot.Keys.ToArray();

            var allClients = new List <ICommitPollingClient>();

            //recreate all polling clients.
            foreach (var bucket in _config.BucketInfo)
            {
                string pollerId = "bucket: " + String.Join(",", bucket.Slots);
                var    client   = _pollingClientFactory.Create(_persistence, pollerId);
                allClients.Add(client);
                _bucketToClient.Add(bucket, client);
            }

            // Once we created all the buckets we will simply configure all of them.
            foreach (var bucketKeyValue in _bucketToClient)
            {
                var client = bucketKeyValue.Value;
                var bucket = bucketKeyValue.Key;

                var slots = bucket.Slots;
                if (slots[0] == "*")
                {
                    //ok we have all bucket, it is calculated getting all the slots and removing
                    //other slots that are in different slots.
                    var asteriskSlots = _projectionsBySlot.Keys.ToList();
                    foreach (var otherBucket in _bucketToClient.Keys.Where(b => b != bucket))
                    {
                        asteriskSlots.RemoveAll(s => otherBucket.Slots.Contains(s));
                    }

                    slots = asteriskSlots.ToArray();
                }

                client.Configure(GetStartGlobalCheckpoint(slots), 4000);
            }

            _clients = allClients.ToArray();

            foreach (var slotName in allSlots)
            {
                KernelMetricsHelper.CreateMeterForDispatcherCountSlot(slotName);
                var startCheckpoint = GetStartCheckpointForSlot(slotName);
                _logger.InfoFormat("Slot {0} starts from {1}", slotName, startCheckpoint);

                var name = slotName;
                //find right consumer
                var slotBucket = _config.BucketInfo.SingleOrDefault(b =>
                                                                    b.Slots.Any(s => s.Equals(slotName, StringComparison.OrdinalIgnoreCase))) ??
                                 _config.BucketInfo.Single(b => b.Slots[0] == "*");
                var client = _bucketToClient[slotBucket];
                client.AddConsumer($"SLOT: {slotName}", commit => DispatchCommitAsync(commit, name, startCheckpoint));
            }

            Initialized = true;
            KernelMetricsHelper.SetProjectionEngineCurrentDispatchCount(() => _countOfConcurrentDispatchingCommit);
        }
Ejemplo n.º 18
0
 public TenantProvider(TenantContext context, IHttpContextAccessor accessor)
 {
     _context  = context;
     _accessor = accessor;
 }
Ejemplo n.º 19
0
        private async Task DispatchCommitAsync(IChunk chunk, string slotName, Int64 startCheckpoint)
        {
            Interlocked.Increment(ref _countOfConcurrentDispatchingCommit);

            _loggerThreadContextManager.SetContextProperty("commit", $"{chunk.OperationId}/{chunk.Position}");

            if (_logger.IsDebugEnabled)
            {
                _logger.DebugFormat("Dispatching checkpoit {0} on tenant {1}", chunk.Position, _config.TenantId);
            }
            TenantContext.Enter(_config.TenantId);
            var chkpoint = chunk.Position;

            if (!lastCheckpointDispatched.ContainsKey(slotName))
            {
                lastCheckpointDispatched[slotName] = 0;
            }

            if (lastCheckpointDispatched[slotName] >= chkpoint)
            {
                var error = String.Format("Sequence broken, last checkpoint for slot {0} was {1} and now we dispatched {2}",
                                          slotName, lastCheckpointDispatched[slotName], chkpoint);
                _logger.Error(error);
                throw new JarvisFrameworkEngineException(error);
            }

            if (lastCheckpointDispatched[slotName] + 1 != chkpoint && lastCheckpointDispatched[slotName] > 0)
            {
                _logger.DebugFormat("Sequence of commit not consecutive (probably holes), last dispatched {0} receiving {1}",
                                    lastCheckpointDispatched[slotName], chkpoint);
            }
            lastCheckpointDispatched[slotName] = chkpoint;

            if (chkpoint <= startCheckpoint)
            {
                //Already dispatched, skip it.
                Interlocked.Decrement(ref _countOfConcurrentDispatchingCommit);
                return;
            }

            var projections = _projectionsBySlot[slotName];

            object[] events = GetArrayOfObjectFromChunk(chunk);

            var eventCount = events.Length;

            //now it is time to dispatch the commit, we will dispatch each projection
            //and for each projection we dispatch all the events present in changeset
            bool someProjectionProcessedTheEvent = false;

            foreach (var projection in projections)
            {
                var    cname        = projection.Info.CommonName;
                Object eventMessage = null;
                try
                {
                    //Foreach projection we need to dispach every event
                    for (int index = 0; index < eventCount; index++)
                    {
                        eventMessage = events[index];

                        var    message   = eventMessage as IMessage;
                        string eventName = eventMessage.GetType().Name;
                        _loggerThreadContextManager.SetContextProperty("evType", eventName);
                        _loggerThreadContextManager.SetContextProperty("evMsId", message?.MessageId);
                        _loggerThreadContextManager.SetContextProperty("evCheckpointToken", chunk.Position);
                        _loggerThreadContextManager.SetContextProperty("prj", cname);

                        var  checkpointStatus = _checkpointTracker.GetCheckpointStatus(cname, chunk.Position);
                        long ticks            = 0;

                        try
                        {
                            //pay attention, stopwatch consumes time.
                            var sw = new Stopwatch();
                            sw.Start();
                            var eventProcessed = await projection
                                                 .HandleAsync(eventMessage, checkpointStatus.IsRebuilding)
                                                 .ConfigureAwait(false);

                            someProjectionProcessedTheEvent |= eventProcessed;
                            sw.Stop();
                            ticks = sw.ElapsedTicks;
                            KernelMetricsHelper.IncrementProjectionCounter(cname, slotName, eventName, ticks, sw.ElapsedMilliseconds);

                            if (_logger.IsDebugEnabled)
                            {
                                _logger.DebugFormat("[Slot:{3}] [Projection {4}] Handled checkpoint {0}: {1} > {2}",
                                                    chunk.Position,
                                                    chunk.PartitionId,
                                                    $"eventName: {eventName} [event N°{index}]",
                                                    slotName,
                                                    cname
                                                    );
                            }
                        }
                        catch (Exception ex)
                        {
                            var error = String.Format("[Slot: {3} Projection: {4}] Failed checkpoint: {0} StreamId: {1} Event Name: {2}",
                                                      chunk.Position,
                                                      chunk.PartitionId,
                                                      eventName,
                                                      slotName,
                                                      cname);
                            _logger.Fatal(error, ex);
                            _engineFatalErrors.Add(String.Format("{0}\n{1}", error, ex));
                            throw;
                        }
                    } //End of event cycle
                }
                catch (Exception ex)
                {
                    _loggerThreadContextManager.ClearContextProperty("commit");
                    _logger.ErrorFormat(ex, "Error dispathing Chunk [{0}]\n Message: {1}\n Error: {2}\n",
                                        chunk.Position, eventMessage?.GetType()?.Name, ex.Message);
                    throw;
                }
                finally
                {
                    _loggerThreadContextManager.ClearContextProperty("evType");
                    _loggerThreadContextManager.ClearContextProperty("evMsId");
                    _loggerThreadContextManager.ClearContextProperty("evCheckpointToken");
                    _loggerThreadContextManager.ClearContextProperty("prj");
                }

                projection.CheckpointProjected(chunk.Position);

                //TODO: Evaluate if it is needed to update single projection checkpoint
                //Update this projection, set all events of this checkpoint as dispatched.
                //await _checkpointTracker.UpdateProjectionCheckpointAsync(cname, chunk.Position).ConfigureAwait(false);
            } //End of projection cycle.

            await _checkpointTracker.UpdateSlotAndSetCheckpointAsync(
                slotName,
                projections.Select(_ => _.Info.CommonName),
                chunk.Position,
                someEventDispatched : someProjectionProcessedTheEvent).ConfigureAwait(false);

            KernelMetricsHelper.MarkCommitDispatchedCount(slotName, 1);

            await _notifyCommitHandled.SetDispatched(slotName, chunk).ConfigureAwait(false);

            // ok in multithread wihout locks!
            if (_maxDispatchedCheckpoint < chkpoint)
            {
                if (_logger.IsDebugEnabled)
                {
                    _logger.DebugFormat("Updating last dispatched checkpoint from {0} to {1}",
                                        _maxDispatchedCheckpoint,
                                        chkpoint
                                        );
                }
                _maxDispatchedCheckpoint = chkpoint;
            }
            _loggerThreadContextManager.ClearContextProperty("commit");
            Interlocked.Decrement(ref _countOfConcurrentDispatchingCommit);
        }
Ejemplo n.º 20
0
        protected override void ConfigureTenantProfileContainer(IContainer tenantProfile, TenantContext <AppTenant> tenantContext)
        {
            // NOTE:
            // - Could configure profile as part of Container configuration, then just retrieve it using the tenant/profile name, but we are going to configure it here
            // - as we are doing tenant configuring here, could equally use "Container.CreateChildContainer();"
            // more info on Profiles and Child Containers -> http://structuremap.github.io/the-container/profiles-and-child-containers/


            // for Tenant 2, want to override IMessageService to use OtherMessageService
            if (tenantProfile.ProfileName.Equals("Tenant 2", StringComparison.InvariantCultureIgnoreCase))
            {
                tenantProfile.Configure(c =>
                {
                    c.For <IMessageService>().Use <OtherMessageService>();
                });
            }

            // Tenant 2 -> IMessageService should use OtherMessageService
            // all other tenants -> IMessageService should use the default MessageService
            //var whatDoIHave = tenantProfile.WhatDoIHave();
        }
        /// <summary>
        /// Start rebuild process.
        /// </summary>
        /// <returns></returns>
        public async Task <RebuildStatus> RebuildAsync()
        {
            if (Logger.IsInfoEnabled)
            {
                Logger.InfoFormat("Starting rebuild projection engine on tenant {0}", _config.TenantId);
            }
            DumpProjections();

            await _eventUnwinder.UnwindAsync().ConfigureAwait(false);

            _status = new RebuildStatus();
            TenantContext.Enter(_config.TenantId);

            await ConfigureProjections().ConfigureAwait(false);

            var allSlots = _projectionsBySlot.Keys.ToArray();

            //initialize dispatching of the commits
            foreach (var bucket in _config.BucketInfo)
            {
                _consumers.Add(bucket, new List <RebuildProjectionSlotDispatcher>());
                _status.AddBucket();
            }

            //Setup the slots
            foreach (var slotName in allSlots)
            {
                Logger.InfoFormat("Slot {0} will be rebuilded", slotName);

                var   projectionsForThisSlot = _projectionsBySlot[slotName];
                Int64 maximumDispatchedValue = projectionsForThisSlot
                                               .Select(p => _checkpointTracker.GetCheckpoint(p))
                                               .Max();
                var dispatcher = new RebuildProjectionSlotDispatcher(Logger, slotName, _config, projectionsForThisSlot, maximumDispatchedValue, _loggerThreadContextManager);
                KernelMetricsHelper.SetCheckpointCountToDispatch(slotName, () => dispatcher.CheckpointToDispatch);
                _rebuildDispatchers.Add(dispatcher);

                //find right consumer
                var slotBucket = _config.BucketInfo.SingleOrDefault(b =>
                                                                    b.Slots.Any(s => s.Equals(slotName, StringComparison.OrdinalIgnoreCase))) ??
                                 _config.BucketInfo.Single(b => b.Slots[0] == "*");
                var consumerList = _consumers[slotBucket];
                consumerList.Add(dispatcher);
            }

            //Creates TPL chain and start polling everything on the consumer
            foreach (var consumer in _consumers)
            {
                var bucketInfo = String.Join(",", consumer.Key.Slots);

                if (consumer.Value.Count == 0)
                {
                    Logger.InfoFormat("Bucket {0} has no active slot, and will be ignored!", bucketInfo);
                    _status.BucketDone(bucketInfo, 0, 0, 0);
                    continue;
                }
                var consumerBufferOptions = new DataflowBlockOptions();
                consumerBufferOptions.BoundedCapacity = consumer.Key.BufferSize;
                var _buffer = new BufferBlock <UnwindedDomainEvent>(consumerBufferOptions);

                ExecutionDataflowBlockOptions executionOption = new ExecutionDataflowBlockOptions();
                executionOption.BoundedCapacity = consumer.Key.BufferSize;

                var dispatcherList = consumer.Value;
                _projectionInspector.ResetHandledEvents();
                List <SlotGuaranteedDeliveryBroadcastBlock.SlotInfo <UnwindedDomainEvent> > consumers =
                    new List <SlotGuaranteedDeliveryBroadcastBlock.SlotInfo <UnwindedDomainEvent> >();
                foreach (var dispatcher in dispatcherList)
                {
                    ExecutionDataflowBlockOptions consumerOptions = new ExecutionDataflowBlockOptions();
                    consumerOptions.BoundedCapacity = consumer.Key.BufferSize;
                    var            actionBlock      = new ActionBlock <UnwindedDomainEvent>((Func <UnwindedDomainEvent, Task>)dispatcher.DispatchEventAsync, consumerOptions);
                    HashSet <Type> eventsOfThisSlot = new HashSet <Type>();
                    foreach (var projection in dispatcher.Projections)
                    {
                        var domainEventTypesHandledByThisProjection = _projectionInspector.InspectProjectionForEvents(projection.GetType());
                        foreach (var type in domainEventTypesHandledByThisProjection)
                        {
                            eventsOfThisSlot.Add(type);
                        }
                    }

                    SlotGuaranteedDeliveryBroadcastBlock.SlotInfo <UnwindedDomainEvent> slotInfo =
                        new SlotGuaranteedDeliveryBroadcastBlock.SlotInfo <UnwindedDomainEvent>(
                            actionBlock,
                            dispatcher.SlotName,
                            eventsOfThisSlot);
                    consumers.Add(slotInfo);
                    KernelMetricsHelper.CreateMeterForRebuildDispatcherBuffer(dispatcher.SlotName, () => actionBlock.InputCount);
                }
                var allTypeHandledStringList = _projectionInspector.EventHandled.Select(t => t.Name).ToList();

                var broadcaster = SlotGuaranteedDeliveryBroadcastBlock.Create(consumers, bucketInfo, consumer.Key.BufferSize);
                _buffer.LinkTo(broadcaster, new DataflowLinkOptions()
                {
                    PropagateCompletion = true
                });

                KernelMetricsHelper.CreateGaugeForRebuildFirstBuffer(bucketInfo, () => _buffer.Count);
                KernelMetricsHelper.CreateGaugeForRebuildBucketDBroadcasterBuffer(bucketInfo, () => broadcaster.InputCount);

                KernelMetricsHelper.CreateMeterForRebuildEventCompleted(bucketInfo);

                //fire each bucket in own thread
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Task.Factory.StartNew(() => StartPoll(
                                          _buffer,
                                          broadcaster,
                                          bucketInfo,
                                          dispatcherList,
                                          allTypeHandledStringList,
                                          consumers));

                //await StartPoll(_buffer, _broadcaster, bucketInfo, dispatcherList, allTypeHandledStringList, consumers).ConfigureAwait(false);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }

            KernelMetricsHelper.SetProjectionEngineCurrentDispatchCount(() => RebuildProjectionMetrics.CountOfConcurrentDispatchingCommit);
            return(_status);
        }
Ejemplo n.º 22
0
        private async Task <RequestResult <AuthorizationData> > CreateNewFacebookUser(TokenInfo tokenInfo,
                                                                                      TenantContext requestTenant)
        {
            var userGuid = _guid.GetGuid();

            var userData = _mapper.Map <CreateUserData>(tokenInfo);

            userData.UserGuid   = userGuid;
            userData.TenantId   = requestTenant.TenantId;
            userData.AvatarType = AvatarType.Facebook;

            var user = await _authRepository.CreateFacebookUser(userData);

            await _avatarRepository
            .StoreAvatar(user.Id, AvatarType.Facebook, tokenInfo.ImageUrl);

            return(await GetAuthorizationDataResult(requestTenant, user));
        }
    public void HandleTenantMismatchWhenDeleting()
    {
        try
        {
            _connection.Open();
            var tenant1 = new TenantContext("abc", "abc", "abc",
                                            "DataSource=testdb.db", null, null);

            // TenantMismatchMode.Throw
            using (var db = new TestDbContext(tenant1, _options))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                var blog1 = new Blog {
                    Title = "abc"
                };
                db.Blogs.Add(blog1);
                db.SaveChanges();

                db.TenantMismatchMode = TenantMismatchMode.Throw;
                db.Entry(blog1).Property("TenantId").CurrentValue = "17";
                db.Blogs.Remove(blog1);

                var e = Assert.Throws <MultiTenantException>(() => db.SaveChanges());
            }

            // TenantMismatchMode.Ignore
            using (var db = new TestDbContext(tenant1, _options))
            {
                db.TenantMismatchMode = TenantMismatchMode.Ignore;
                var blog1 = db.Blogs.First();
                db.Entry(blog1).Property("TenantId").CurrentValue = "17";
                db.Blogs.Remove(blog1);

                Assert.Equal(1, db.SaveChanges());
            }

            // TenantMismatchMode.Overwrite
            using (var db = new TestDbContext(tenant1, _options))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                var blog1 = new Blog {
                    Title = "abc"
                };
                db.Blogs.Add(blog1);
                db.SaveChanges();

                db.TenantMismatchMode = TenantMismatchMode.Overwrite;
                db.Entry(blog1).Property("TenantId").CurrentValue = "17";
                db.Blogs.Remove(blog1);

                Assert.Equal(1, db.SaveChanges());
            }
        }
        finally
        {
            _connection.Close();
        }
    }
Ejemplo n.º 24
0
 public CostoHandlerEF(TenantContext tc)
 {
     ctx = tc;
 }
Ejemplo n.º 25
0
 protected override IEnumerable <string> GetTenantIdentifiers(TenantContext <TestTenant> context)
 {
     return(context?.Tenant?.Paths);
 }
Ejemplo n.º 26
0
        public async Task Invoke(HttpContext httpContext, ITenantResolverService tenantResolverService, ITenantMapperService <TTenantMapping> tenantMapperService,
                                 ITenantInfoService <TTenant> tenantInfoService)
        {
            TenantContext <TTenant> _tenantContext = null;

            TenantResolveResult _tenantResolveResult          = null;
            TenantMapResult <TTenantMapping> _tenantMapResult = null;

            TTenant        _tenant        = default;
            TTenantMapping _tenantMapping = default;

            ResolutionResult _resolutionResult = ResolutionResult.NotFound;
            MappingResult    _mappingResult    = MappingResult.NotFound;
            ResolutionType   _resolutionType   = ResolutionType.Nothing;

            string _tenantResolvedData = "";

            _tenantResolveResult = await tenantResolverService.ResolveTenantAsync(httpContext);

            _resolutionResult = _tenantResolveResult.ResolutionResult;

            switch (_resolutionResult)
            {
            case ResolutionResult.Success:

                _resolutionType     = _tenantResolveResult.ResolutionType;
                _tenantResolvedData = _tenantResolveResult.Value;

                switch (_resolutionType)
                {
                case ResolutionType.TenantId:
                    _mappingResult = MappingResult.NotApply;
                    break;

                case ResolutionType.TenantName:
                    _mappingResult = MappingResult.Success;
                    break;
                }

                break;

            case ResolutionResult.NotApply:

                _mappingResult      = MappingResult.NotApply;
                _tenantResolvedData = "";
                break;

            case ResolutionResult.NotFound:

                _mappingResult      = MappingResult.NotFound;
                _tenantResolvedData = "";
                break;

            case ResolutionResult.Error:

                _mappingResult      = MappingResult.Error;
                _tenantResolvedData = "";
                break;
            }

            if (_resolutionResult == ResolutionResult.Success)
            {
                if (_mappingResult != MappingResult.NotApply) //if applies mapping call mapping service
                {
                    _tenantMapResult = await tenantMapperService.MapTenantAsync(_tenantResolveResult.Value);

                    _mappingResult = _tenantMapResult.MappingResult;

                    switch (_mappingResult)
                    {
                    case MappingResult.Success:

                        _tenantMapping      = _tenantMapResult.Value;
                        _tenantResolvedData = _tenantMapping.TenantId;

                        break;

                    case MappingResult.NotFound:

                        _tenantResolvedData = "";
                        _resolutionResult   = ResolutionResult.NotFound;
                        _resolutionType     = ResolutionType.Nothing;

                        break;

                    case MappingResult.Error:

                        _tenantResolvedData = "";
                        _resolutionResult   = ResolutionResult.Error;
                        _resolutionType     = ResolutionType.Nothing;

                        break;
                    }
                }

                //at this point it must be the id
                if (!string.IsNullOrWhiteSpace(_tenantResolvedData))
                {
                    _tenant = await tenantInfoService.GetTenantInfoAsync(_tenantResolvedData);
                }
            }

            _tenantContext = new TenantContext <TTenant>(_tenant, _resolutionResult, _mappingResult, _resolutionType);

            httpContext.SetTenantContext(_tenantContext);

            await _next(httpContext);
        }
Ejemplo n.º 27
0
 public SampleApplicationController(TenantContext <Tenant> tenantContext, IContainer container)
 {
     this.tenantContext = tenantContext;
     this.container     = container;
 }
Ejemplo n.º 28
0
 public RecursosHandlerEF(TenantContext tc)
 {
     ctx = tc;
 }
        internal void UploadFile(String jobFile, DocumentImportTask task)
        {
            String fname = "";

            try
            {
                TenantContext.Enter(task.Tenant);

                if (!task.Uri.IsFile)
                {
                    LogAndThrow("Error importing task file {0}: Uri is not a file: {1}", jobFile, task.Uri);
                }

                fname = task.Uri.LocalPath;

                if (FileHasImportFailureMarker(fname, task.FileTimestamp))
                {
                    return;
                }

                if (!File.Exists(fname))
                {
                    LogAndThrow("Error importing task file {0}: File missing: {1}", jobFile, fname);
                }

                var blobStore         = GetBlobStoreForTenant();
                var identityGenerator = GetIdentityGeneratorForTenant();
                if (blobStore == null || identityGenerator == null)
                {
                    Logger.ErrorFormat("Tenant {1} not found or not configured for file: {1}", task.Tenant, fname);
                    return;
                }

                BlobId blobId;
                if (!String.IsNullOrEmpty(task.FileName))
                {
                    //use the real file name from the task not the name of the file
                    using (FileStream fs = File.Open(fname, FileMode.Open, FileAccess.Read))
                    {
                        blobId = blobStore.Upload(task.Format, new FileNameWithExtension(task.FileName), fs);
                    }
                }
                else
                {
                    //No filename given in task, use name of the blob
                    blobId = blobStore.Upload(task.Format, fname);
                }

                if (task.Format == OriginalFormat)
                {
                    var descriptor = blobStore.GetDescriptor(blobId);
                    var fileName   = new FileNameWithExtension(task.FileName);
                    var handleInfo = new DocumentHandleInfo(task.Handle, fileName, task.CustomData);
                    var documentId = identityGenerator.New <DocumentDescriptorId>();

                    var createDocument = new InitializeDocumentDescriptor(
                        documentId,
                        blobId,
                        handleInfo,
                        descriptor.Hash,
                        fileName
                        );
                    _commandBus.Send(createDocument, "import-from-file");
                }
                else
                {
                    var reader     = _tenantAccessor.Current.Container.Resolve <IDocumentWriter>();
                    var handle     = reader.FindOneById(task.Handle);
                    var documentId = handle.DocumentDescriptorId;

                    var command = new AddFormatToDocumentDescriptor(
                        documentId,
                        task.Format,
                        blobId,
                        new PipelineId("user-content")
                        );
                    _commandBus.Send(command, "import-from-file");
                }

                TaskExecuted(task);
                DeleteImportFailure(fname);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(ex, "Job Import Queue - Error importing {0} - {1}", jobFile, ex.Message);
                ImportFailure failure = new ImportFailure()
                {
                    Error     = ex.ToString(),
                    FileName  = fname,
                    Timestamp = DateTime.Now,
                    ImportFileTimestampTicks = task.FileTimestamp.Ticks,
                };
                MarkImportFailure(failure);
            }
            finally
            {
                TenantContext.Exit();
            }
        }
 protected override IEnumerable <string> GetTenantIdentifiers(TenantContext <AppTenant> context)
 {
     return(context.Tenant.Hostnames);
 }
 public TestDbContext(TenantContext tenantContext,
                      DbContextOptions <TestDbContext> options) :
     base(tenantContext, options)
 {
 }