예제 #1
0
        public async Task DeleteAsync(string id, CancellationToken cancellationToken = default)
        {
            var entity = await _session.LoadAsync <TEntity>($"{_entitybasePath}{id}", cancellationToken).ConfigureAwait(false);

            if (entity == null)
            {
                throw new InvalidOperationException($"Entity type {typeof(TEntity).Name} at id {id} is not found");
            }
            _session.Delete(entity);
            var iCollectionType       = typeof(ICollection <>);
            var iEntityIdType         = typeof(IEntityId);
            var subEntitiesProperties = _entityType.GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.ImplementsGenericInterface(iCollectionType) && p.PropertyType.GetGenericArguments()[0].IsAssignableTo(iEntityIdType));

            foreach (var subEntityProperty in subEntitiesProperties)
            {
                var collection = subEntityProperty.GetValue(entity) as ICollection;
                if (collection != null)
                {
                    foreach (IEntityId subItem in collection)
                    {
                        _session.Delete(subItem.Id);
                    }
                }
            }

            await OnDeleteEntityAsync(entity, cancellationToken).ConfigureAwait(false);

            await _session.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            _logger.LogInformation("Entity {EntityId} deleted", entity.Id);
        }
예제 #2
0
        public async Task <IActionResult> TestDouble()
        {
            var e = new BaseOperation()
            {
                Id = null,
                B  = new B()
                {
                    Id = "B-1"
                }
            };

            var e2 = new BaseOperation()
            {
                Id = null,
                B  = new B()
                {
                    Id = "B-2"
                }
            };

            //** Store ***********************//
            await _session.StoreAsync(e);

            await _session.StoreAsync(e2);

            await _session.SaveChangesAsync();

            //** Delete ***********************//
            _session.Delete(e);
            await _session.SaveChangesAsync();

            return(Ok());
        }
예제 #3
0
        public Task DeleteAsync(TUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            _documentSession.Delete <TUser>(user);
            return(_documentSession.SaveChangesAsync());
        }
예제 #4
0
        public void DeleteOnSave <T>(T document)
            where T : IDocument
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            _async.Delete(document);
        }
예제 #5
0
        protected async Task RemoveAsync(string handle)
        {
            var entity = await GetEntityByHandle(handle)
                         .ConfigureAwait(false);

            if (entity == null)
            {
                return;
            }
            _session.Delete(entity);
            await _session.SaveChangesAsync().ConfigureAwait(false);
        }
예제 #6
0
        public async Task <bool> DeleteAllFollower(string userId)
        {
            var followingDoc = await asyncDocumentSession.Advanced.AsyncDocumentQuery <Following>()
                               .WhereEquals(following =>
                                            following.UserId, userId)
                               .SingleOrDefaultAsync();

            asyncDocumentSession.Delete <Following>(followingDoc);
            await asyncDocumentSession.SaveChangesAsync();

            return(true);
        }
예제 #7
0
            public async Task <CommandResult> Handle(DeleteMeasureCommand command)
            {
                _session.Delete(command.Id);
                await _session.SaveChangesAsync();

                return(CommandResult.Ok());
            }
예제 #8
0
        /// <inheritdoc />
        public async Task <IdentityResult> DeleteAsync(TUser user, CancellationToken cancellationToken)
        {
            ThrowIfNullDisposedCancelled(user, cancellationToken);
            cancellationToken.ThrowIfCancellationRequested();

            // Remove the cluster-wide compare/exchange key.
            var deletionResult = await DeleteUserEmailReservation(user.Email);

            if (!deletionResult.Successful)
            {
                return(IdentityResult.Failed(new[]
                {
                    new IdentityError
                    {
                        Code = "ConcurrencyFailure",
                        Description = "Unable to delete user email compare/exchange value"
                    }
                }));
            }


            // Delete the user and save it. We must save it because deleting is a cluster-wide operation.
            // Only if the deletion succeeds will we remove the cluseter-wide compare/exchange key.
            using (IAsyncDocumentSession session = _store.OpenAsyncSession())
            {
                session.Delete(user);
                await session.SaveChangesAsync(cancellationToken);
            }

            return(IdentityResult.Success);
        }
예제 #9
0
        /// <summary>
        /// Removes the <paramref name="claims"/> given from the specified <paramref name="user"/>.
        /// </summary>
        /// <param name="user">The user to remove the claims from.</param>
        /// <param name="claims">The claim to remove.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
        public override async Task RemoveClaimsAsync(TUser user, IEnumerable <Claim> claims, CancellationToken cancellationToken = default)
        {
            CheckParameters(user, claims);

            var userId = ConvertIdToString(user.Id);
            var data   = await _session.LoadAsync <UserData>($"userdata/{userId}", cancellationToken).ConfigureAwait(false);

            var toDeleteList = new List <string>();

            foreach (var claimId in data.ClaimIds)
            {
                var userClaim = await _session.LoadAsync <UserClaim>(claimId, cancellationToken).ConfigureAwait(false);

                if (claims.Any(c => userClaim.Issuer == c.Issuer && userClaim.ClaimType == c.Type && userClaim.ClaimValue == c.Value))
                {
                    toDeleteList.Add(claimId);
                }
            }

            foreach (var claimId in toDeleteList)
            {
                _session.Delete(claimId);
                data.ClaimIds.Remove(claimId);
            }
        }
        public async Task DeleteUserAsync(string userId)
        {
            var user = await GetUserAsync(userId);

            _connection.Delete(user);
            await _connection.SaveChangesAsync();
        }
        public async Task Delete(StringIdentity <T> id, IAsyncDocumentSession session)
        {
            var entity = await session.LoadAsync <T>(id.Value);

            session.Delete(entity);
            await session.SaveChangesAsync();
        }
예제 #12
0
        private async Task <bool> ForwardCurrentBatch(IAsyncDocumentSession session, CancellationToken cancellationToken)
        {
            Log.Debug("Looking for batch to forward");

            var nowForwarding = await session.Include <RetryBatchNowForwarding, RetryBatch>(r => r.RetryBatchId)
                                .LoadAsync <RetryBatchNowForwarding>(RetryBatchNowForwarding.Id)
                                .ConfigureAwait(false);

            if (nowForwarding != null)
            {
                Log.DebugFormat("Loading batch {0} for forwarding", nowForwarding.RetryBatchId);

                var forwardingBatch = await session.LoadAsync <RetryBatch>(nowForwarding.RetryBatchId).ConfigureAwait(false);

                if (forwardingBatch != null)
                {
                    Log.InfoFormat("Found batch {0}. Forwarding...", forwardingBatch.Id);
                    Forward(forwardingBatch, session, cancellationToken);
                    Log.DebugFormat("Retry batch {0} forwarded.", forwardingBatch.Id);
                }
                else
                {
                    Log.WarnFormat("Could not find retry batch {0} to forward", nowForwarding.RetryBatchId);
                }

                Log.Debug("Removing Forwarding record");

                session.Delete(nowForwarding);
                return(true);
            }

            Log.Debug("No batch found to forward");

            return(false);
        }
예제 #13
0
        async Task Forward(RetryBatch forwardingBatch, IAsyncDocumentSession session, CancellationToken cancellationToken)
        {
            var messageCount = forwardingBatch.FailureRetries.Count;

            Log.InfoFormat("Forwarding batch {0} with {1} messages", forwardingBatch.Id, messageCount);
            await retryingManager.Forwarding(forwardingBatch.RequestId, forwardingBatch.RetryType)
            .ConfigureAwait(false);

            if (isRecoveringFromPrematureShutdown)
            {
                Log.Warn("Recovering from premature shutdown. Starting forwarder in timeout mode");
                await returnToSender.Run(IsPartOfStagedBatch(forwardingBatch.StagingId), cancellationToken)
                .ConfigureAwait(false);

                await retryingManager.ForwardedBatch(forwardingBatch.RequestId, forwardingBatch.RetryType, forwardingBatch.InitialBatchSize)
                .ConfigureAwait(false);
            }
            else
            {
                Log.DebugFormat("Starting forwarder in counting mode with {0} messages", messageCount);
                await returnToSender.Run(IsPartOfStagedBatch(forwardingBatch.StagingId), cancellationToken, messageCount)
                .ConfigureAwait(false);

                await retryingManager.ForwardedBatch(forwardingBatch.RequestId, forwardingBatch.RetryType, messageCount)
                .ConfigureAwait(false);
            }

            session.Delete(forwardingBatch);

            Log.InfoFormat("Retry batch {0} done", forwardingBatch.Id);
        }
 public static Task Del(
     this IAsyncDocumentSession session,
     string id
     )
 {
     session.Delete(id);
     return(Task.CompletedTask);
 }
        public async Task DeleteUserAsync(string userId, OutboxMessageModel message)
        {
            var user = await GetUserAsyncInternal(userId);

            if (user == null)
            {
                return;
            }

            _connection.Delete(user);
            if (message != null)
            {
                await _connection.StoreAsync(message.ToRavendDb());
            }

            await _connection.SaveChangesAsync();
        }
예제 #16
0
 public void Delete <T>(T entity)
 {
     if (entity is ITenantedEntity tenantedEntity && tenantedEntity.TenantId != _currentTenantId)
     {
         throw new ArgumentException("Attempt to delete a record for another tenant");
     }
     _dbSession.Delete(entity);
 }
예제 #17
0
 private async void DeleteItem <T>(T item) where T : IEntity
 {
     try {
         _dao.Delete(item);
         await _dao.SaveChangesAsync();
     } catch (Exception e) {
         Logger.ErrorException(e.Message, e);
     }
 }
예제 #18
0
        async Task <int> Stage(RetryBatch stagingBatch, IAsyncDocumentSession session)
        {
            var stagingId = Guid.NewGuid().ToString();
            var failedMessageRetryDocs = await session.LoadAsync <FailedMessageRetry>(stagingBatch.FailureRetries).ConfigureAwait(false);

            var matchingFailures = failedMessageRetryDocs
                                   .Where(r => r != null && r.RetryBatchId == stagingBatch.Id)
                                   .Distinct(FailedMessageEqualityComparer.Instance)
                                   .ToArray();

            foreach (var failedMessageRetry in failedMessageRetryDocs)
            {
                if (failedMessageRetry != null)
                {
                    session.Advanced.Evict(failedMessageRetry);
                }
            }

            var failedMessagesById = matchingFailures.ToDictionary(x => x.FailedMessageId, x => x);

            if (!failedMessagesById.Any())
            {
                Log.Info($"Retry batch {stagingBatch.Id} cancelled as all matching unresolved messages are already marked for retry as part of another batch.");
                session.Delete(stagingBatch);
                return(0);
            }

            var failedMessagesDocs = await session.LoadAsync <FailedMessage>(failedMessagesById.Keys).ConfigureAwait(false);

            var messages = failedMessagesDocs
                           .Where(m => m != null)
                           .ToArray();

            Log.Info($"Staging {messages.Length} messages for retry batch {stagingBatch.Id} with staging attempt Id {stagingId}.");

            await Task.WhenAll(messages.Select(m => TryStageMessage(m, stagingId, failedMessagesById[m.Id])).ToArray()).ConfigureAwait(false);

            if (stagingBatch.RetryType != RetryType.FailureGroup) //FailureGroup published on completion of entire group
            {
                var failedIds = messages.Select(x => x.UniqueMessageId).ToArray();
                await domainEvents.Raise(new MessagesSubmittedForRetry
                {
                    FailedMessageIds       = failedIds,
                    NumberOfFailedMessages = failedIds.Length,
                    Context = stagingBatch.Context
                }).ConfigureAwait(false);
            }

            var msgLookup = messages.ToLookup(x => x.Id);

            stagingBatch.Status         = RetryBatchStatus.Forwarding;
            stagingBatch.StagingId      = stagingId;
            stagingBatch.FailureRetries = matchingFailures.Where(x => msgLookup[x.FailedMessageId].Any()).Select(x => x.Id).ToArray();
            Log.Info($"Retry batch {stagingBatch.Id} staged with Staging Id {stagingBatch.StagingId} and {stagingBatch.FailureRetries.Count} matching failure retries");
            return(messages.Length);
        }
예제 #19
0
        async Task <int> Stage(RetryBatch stagingBatch, IAsyncDocumentSession session)
        {
            var stagingId = Guid.NewGuid().ToString();
            var failedMessageRetryDocs = await session.LoadAsync <FailedMessageRetry>(stagingBatch.FailureRetries).ConfigureAwait(false);

            var matchingFailures = failedMessageRetryDocs
                                   .Where(r => r != null && r.RetryBatchId == stagingBatch.Id)
                                   .ToArray();

            foreach (var failedMessageRetry in failedMessageRetryDocs)
            {
                if (failedMessageRetry != null)
                {
                    session.Advanced.Evict(failedMessageRetry);
                }
            }

            var messageIds = matchingFailures.Select(x => x.FailedMessageId).ToArray();

            if (!messageIds.Any())
            {
                Log.Info($"Retry batch {stagingBatch.Id} cancelled as all matching unresolved messages are already marked for retry as part of another batch");
                session.Delete(stagingBatch);
                return(0);
            }

            var failedMessagesDocs = await session.LoadAsync <FailedMessage>(messageIds).ConfigureAwait(false);

            var messages = failedMessagesDocs
                           .Where(m => m != null)
                           .ToArray();

            Log.DebugFormat("Staging {0} messages for Retry Batch {1} with staging attempt Id {2}", messages.Length, stagingBatch.Id, stagingId);

            Parallel.ForEach(messages, message => StageMessage(message, stagingId));

            if (stagingBatch.RetryType != RetryType.FailureGroup) //FailureGroup published on completion of entire group
            {
                var failedIds = messages.Select(x => x.UniqueMessageId).ToArray();
                domainEvents.Raise(new MessagesSubmittedForRetry
                {
                    FailedMessageIds       = failedIds,
                    NumberOfFailedMessages = failedIds.Length,
                    Context = stagingBatch.Context
                });
            }

            var msgLookup = messages.ToLookup(x => x.Id);

            stagingBatch.Status         = RetryBatchStatus.Forwarding;
            stagingBatch.StagingId      = stagingId;
            stagingBatch.FailureRetries = matchingFailures.Where(x => msgLookup[x.FailedMessageId].Any()).Select(x => x.Id).ToArray();
            Log.DebugFormat("Retry batch {0} staged with Staging Id {1} and {2} matching failure retries", stagingBatch.Id, stagingBatch.StagingId, stagingBatch.FailureRetries.Count);
            Log.InfoFormat("Retry batch {0} staged {1} messages", stagingBatch.Id, messages.Length);
            return(messages.Length);
        }
예제 #20
0
        /// <summary>
        ///     Update database provisioning status.
        /// </summary>
        /// <param name="databaseProvisioningNotification">
        ///     A <see cref="DatabaseStatusChanged"/> message describing the change.
        /// </param>
        /// <returns>
        ///     A <see cref="Task"/> representing the operation.
        /// </returns>
        async Task UpdateDatabaseProvisioningStatus(DatabaseStatusChanged databaseProvisioningNotification)
        {
            if (databaseProvisioningNotification == null)
            {
                throw new ArgumentNullException(nameof(databaseProvisioningNotification));
            }

            using (IAsyncDocumentSession session = DocumentStore.OpenAsyncSession())
            {
                DatabaseInstance database = await session
                                            .Include <DatabaseInstance>(db => db.ServerId)
                                            .LoadAsync <DatabaseInstance>(databaseProvisioningNotification.DatabaseId);

                if (database == null)
                {
                    Log.Warning("Received DatabaseStatusChanged notification for non-existent database (Id:{DatabaseId}).",
                                databaseProvisioningNotification.DatabaseId
                                );

                    return;
                }

                DatabaseServer server = await session.LoadAsync <DatabaseServer>(database.ServerId);

                if (server == null)
                {
                    Log.Warning("Received DatabaseStatusChanged notification for database in non-existent server (Id:{ServerId}).",
                                database.ServerId
                                );

                    return;
                }

                database.Status = databaseProvisioningNotification.Status;
                switch (database.Status)
                {
                case ProvisioningStatus.Ready:
                case ProvisioningStatus.Error:
                {
                    database.Action = ProvisioningAction.None;

                    break;
                }

                case ProvisioningStatus.Deprovisioned:
                {
                    server.DatabaseIds.Remove(database.Id);
                    session.Delete(database);

                    break;
                }
                }

                await session.SaveChangesAsync();
            }
        }
예제 #21
0
        public virtual async Task RemoveAllAsync(PersistedGrantFilter filter)
        {
            filter.Validate();

            var persistedGrants = await Filter(filter).ToArrayAsync();

            Logger.LogDebug("removing {persistedGrantCount} persisted grants from database for {@filter}", persistedGrants.Length, filter);

            Session.Delete(persistedGrants);

            try
            {
                await Session.SaveChangesAsync();
            }
            catch (ConcurrencyException ex)
            {
                Logger.LogInformation("removing {persistedGrantCount} persisted grants from database for subject {@filter}: {error}", persistedGrants.Length, filter, ex.Message);
            }
        }
예제 #22
0
        public async Task <Tweets> DeleteTweet(string tweetId)
        {
            //asyncDocumentSession.Advanced.DocumentStore.Conventions.
            var tweets = await asyncDocumentSession.LoadAsync <Tweets>(tweetId);

            asyncDocumentSession.Delete <Tweets>(tweets);
            await asyncDocumentSession.SaveChangesAsync();

            return(tweets);
        }
예제 #23
0
        /// <inheritdoc />
        public async Task RemoveTokenAsync(TUser user, string loginProvider, string name, CancellationToken cancellationToken)
        {
            var id = IdentityUserAuthToken.GetWellKnownId(_store, user.Id, loginProvider, name);

            using (IAsyncDocumentSession session = _store.OpenAsyncSession())
            {
                session.Delete(id);
                await session.SaveChangesAsync(cancellationToken);
            }
        }
예제 #24
0
        public async Task DeleteHardAsync <T>(IDataStoreWriteOperation <T> aggregateHardDeleted) where T : class, IAggregate, new()
        {
            using (IAsyncDocumentSession session = store.OpenAsyncSession())
            {
                T aggregate = await session.LoadAsync <T>(aggregateHardDeleted.Model.id.ToString());

                await Task.Run(() => session.Delete <T>(aggregate));

                await session.SaveChangesAsync().ConfigureAwait(false);
            }
        }
        public async Task RemovePlatformDataForPlatform(string userId, string platformId, IAsyncDocumentSession session,
                                                        CancellationToken cancellationToken = default)
        {
            var existingPlatformData = await GetPlatformData(userId, platformId, session, cancellationToken);

            if (existingPlatformData == null)
            {
                return;
            }

            session.Delete(existingPlatformData.Id);
        }
예제 #26
0
        public async Task DeleteUserInfoAsync(string userId)
        {
            var user = await GetUserAuthInfoAsyncInternal(userId);

            if (user == null)
            {
                return;
            }

            _connection.Delete(user);
            await _connection.SaveChangesAsync();
        }
예제 #27
0
        public async Task DeleteAsync(TUser user)
        {
            ThrowIfDisposed();

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            _documentSession.Delete(user);
            await _documentSession.SaveChangesAsync();
        }
예제 #28
0
        async Task DeleteCorrelationProperties(IEnumerable <string> correlationPropertyIds, IAsyncDocumentSession session)
        {
            var existingSagaCorrelationPropertyDocuments =
                await session.LoadAsync <SagaCorrelationPropertyDocument>(
                    correlationPropertyIds);

            //delete the existing saga correlation documents
            foreach (var existingSagaCorrelationPropertyDocument in existingSagaCorrelationPropertyDocuments)
            {
                session.Delete(existingSagaCorrelationPropertyDocument);
            }
        }
        Task SagaConsumeContext <TSaga> .SetCompleted()
        {
            _session.Delete(Saga);
            IsCompleted = true;
            if (Log.IsDebugEnabled)
            {
                Log.DebugFormat("SAGA:{0}:{1} Removed {2}", TypeMetadataCache <TSaga> .ShortName, TypeMetadataCache <TMessage> .ShortName,
                                Saga.CorrelationId);
            }

            return(TaskUtil.Completed);
        }
예제 #30
0
        public async System.Threading.Tasks.Task <int> DeleteAsync(long id)
        {
            int count    = 0;
            var existing = await AsyncSession.LoadAsync <T>(EntityUtility.GetRecordId <T>(id));

            if (existing != null)
            {
                count = 1;
                AsyncSession.Delete(existing);
            }
            return(count);
        }
예제 #31
0
        async Task DeleteCorrelationProperties(IEnumerable<string> correlationPropertyIds, IAsyncDocumentSession session)
        {
            var existingSagaCorrelationPropertyDocuments =
                await session.LoadAsync<SagaCorrelationPropertyDocument>(
                    correlationPropertyIds);

            //delete the existing saga correlation documents
            foreach (var existingSagaCorrelationPropertyDocument in existingSagaCorrelationPropertyDocuments)
            {
                session.Delete(existingSagaCorrelationPropertyDocument);
            }
        }
예제 #32
0
        private async Task DeleteCorrelationPropertyDataForSaga(SagaDataDocument sagaDataDocument,
            IAsyncDocumentSession session)
        {
            var existingSagaCorrelationPropertyDocuments =
                await session.LoadAsync<SagaCorrelationPropertyDocument>(
                    sagaDataDocument.SagaCorrelationPropertyDocumentIds);

            //delete the existing saga correlation documents
            foreach (var existingSagaCorrelationPropertyDocument in existingSagaCorrelationPropertyDocuments)
            {
                session.Delete(existingSagaCorrelationPropertyDocument);
            }
        }
예제 #33
0
        private static async Task DeletedPosts(IAsyncDocumentSession session, IEnumerable<BlogPostBase> deletedPosts)
        {
            foreach (var deletedPost in deletedPosts)
            {
                string postId = RavenDbIdConventions.GetBlogPostId(deletedPost.BlogKey, deletedPost.BlavenId);

                var existingPost = await session.LoadAsync<BlogPost>(postId);
                if (existingPost != null)
                {
                    session.Delete(existingPost);
                }
            }
        }