Exemple #1
0
 public void Delete(int id)
 {
     lock (_session)
     {
         _session.Delete <Demographic>(id);
     }
 }
Exemple #2
0
 public void Delete(int id)
 {
     lock (_session)
     {
         _session.Delete <ClashException>(id);
     }
 }
        private void DeleteSalesArea(Guid salesAreaId)
        {
            var salesArea = _session.Load <SalesArea>(salesAreaId);

            _session.Delete(salesArea);

            _session.SaveChanges();
        }
Exemple #4
0
        public void DeleteRangeByExternalRefs(IEnumerable <string> externalRefs)
        {
            var products = _session.GetAll <Product>(s => s.Externalidentifier.In(externalRefs.ToList()));

            foreach (var product in products)
            {
                _session.Delete(product);
            }
        }
 public void Delete(int id)
 {
     lock (_session)
     {
         var item = Get(id);
         if (item != null)
         {
             _session.Delete(item);
         }
     }
 }
Exemple #6
0
        public void Delete(Guid uid)
        {
            var item = Get(uid);

            if (item is null)
            {
                return;
            }

            _session.Delete(item);
        }
        public void DeleteRange(IEnumerable <Guid> ids)
        {
            lock (_session)
            {
                var programmes = _session.GetAll <Programme>(s => s.Id.In(ids));

                foreach (var programme in programmes)
                {
                    _session.Delete(programme);
                }
            }
        }
Exemple #8
0
        // SAMPLE: deletes
        public void delete_documents(IDocumentSession session)
        {
            var user = new User();

            session.Delete(user);
            session.SaveChanges();

            // OR

            session.Delete(user.Id);
            session.SaveChanges();
        } 
Exemple #9
0
        // SAMPLE: deletes
        public void delete_documents(IDocumentSession session)
        {
            var user = new User();

            session.Delete(user);
            session.SaveChanges();

            // OR

            session.Delete(user.Id);
            session.SaveChanges();
        }
Exemple #10
0
        public void DeleteBySalesAreaName(string name)
        {
            lock (_session)
            {
                var salesAreaDemographics = _session.GetAll <SalesAreaDemographic>(x => x.SalesArea == name);

                foreach (var salesAreaDemographic in salesAreaDemographics)
                {
                    _session.Delete <SalesAreaDemographic>(salesAreaDemographic.Id);
                }
            }
        }
Exemple #11
0
        public void Remove(Guid uid)
        {
            lock (_session)
            {
                Spot spotToDelete = Find(uid);
                if (spotToDelete is null)
                {
                    return;
                }

                _session.Delete(spotToDelete);
            }
        }
Exemple #12
0
        public void Delete(int id)
        {
            lock (_session)
            {
                var item = Get(id);
                if (item is null)
                {
                    return;
                }

                _session.Delete(item);
            }
        }
        public void Delete(int id)
        {
            lock (_session)
            {
                var positionGroup = Get(id);
                if (positionGroup is null)
                {
                    return;
                }

                _session.Delete(positionGroup);
            }
        }
        public override void RemoveFromSet(string key, string value)
        {
            var id = Repository.GetId(typeof(RavenSet), key);

            var set = _session.Load <RavenSet>(id);

            set.Scores.Remove(value);

            if (set.Scores.Count == 0)
            {
                _session.Delete(set);
            }
        }
Exemple #15
0
        public void Delete(Guid id)
        {
            lock (_session)
            {
                var scenario = Get(id);

                if (scenario is null)
                {
                    return;
                }

                _session.Delete(scenario);
            }
        }
Exemple #16
0
        public override void RemoveFromSet(string key, string value)
        {
            key.ThrowIfNull(nameof(key));

            var id  = _storage.Repository.GetId(typeof(RavenSet), key);
            var set = FindOrCreateSet(id);

            set.Scores.Remove(value);

            if (set.Scores.Count == 0)
            {
                _session.Delete(set);
            }
        }
        public async Task Delete(TodoAggregate item)
        {
            var _item = m_mapper.Map <Documents.TodoDocument>(item);

            m_session.Delete(_item);
            await m_session.SaveChangesAsync();
        }
Exemple #18
0
        /// <summary>
        /// Remove a role
        /// </summary>
        /// <param name="applicationName">Application that the request is for.</param>
        /// <param name="roleName">Role to remove</param>
        public void RemoveRole(string applicationName, string roleName)
        {
            var role = _session.Query <Role>().Where(r => r.Name == roleName);

            _session.Delete(role);
            _session.SaveChanges();
        }
Exemple #19
0
            /// <summary>
            /// Deletes a bunch of elements in a single call.
            /// </summary>
            /// <typeparam name="DBType">Type of the element stored in the database. This is used to identify the collection</typeparam>
            /// <param name="ids">Array containing the identifiers of the elements that have to be deleted</param>
            /// <returns>RepositoryResponse.RepositoryDelete if all the elements have been successfully deleted,
            /// RepositoryResponse.RepositoryGenericError otherwise</returns>
            public override RepositoryResponse BulkDelete <DBType>(string[] ids)
            {
                lock (_store)
                {
                    using (IDocumentSession _session = _store.OpenSession())
                    {
                        DBType[] ents = _session.Load <DBType>(ids);

                        /*try
                         * {*/
                        using (TransactionScope tx = new TransactionScope())
                        {
                            foreach (DBType entity in ents)
                            {
                                _session.Delete <DBType>(entity);
                            }
                            _session.SaveChanges();
                            tx.Complete();
                        }
                        return(RepositoryResponse.RepositoryDelete);

                        /*}
                         * catch (TransactionAbortedException tae)
                         * {
                         *  log.Error("Transaction Aborted", tae);
                         *  return RepositoryResponse.RepositoryGenericError;
                         * }*/
                    }
                }
            }
Exemple #20
0
        private async Task applyProjectionsAsync(IDocumentSession session, ICollection <EventProjection> projections, IEnumerable <TView> views)
        {
            var viewMap = createViewMap(session, projections, views);

            foreach (var eventProjection in projections)
            {
                var hasView = viewMap.TryGetValue(eventProjection.ViewId, out TView view);

                if (!hasView)
                {
                    continue;
                }

                if (eventProjection.Type == ProjectionEventType.Delete)
                {
                    if (await eventProjection.ShouldDelete(session, view))
                    {
                        session.Delete(view);
                    }
                }
                else
                {
                    await eventProjection.ProjectTo(session, view);
                }
            }
        }
Exemple #21
0
        public void Apply()
        {
            foreach (string tenantConnectionString in _tenantConnectionStrings)
            {
                using (IDocumentStore documentStore = DocumentStoreFactory.CreateStore(tenantConnectionString))
                    using (IDocumentSession session = documentStore.OpenSession())
                    {
                        var awsconfigs      = session.GetAll <AWSInstanceConfiguration>();
                        var autobookconfigs = session.GetAll <AutoBookInstanceConfiguration>();

                        foreach (AutoBookInstanceConfiguration abic in autobookconfigs)
                        {
                            var aws = awsconfigs.Find(x => x.Id == abic.Id);
                            if (aws != null)
                            {
                                abic.InstanceType  = aws.InstanceType;
                                abic.StorageSizeGb = aws.StorageSizeGb;
                                abic.Cost          = aws.Cost;
                            }
                        }

                        awsconfigs.ForEach(aws => session.Delete(aws));

                        session.SaveChanges();
                    }
            }
        }
Exemple #22
0
            /// <summary>
            /// Method that delete an element of the repository.
            /// </summary>
            /// <typeparam name="DBType">Type of the element stored in the database. This is used to identify the collection</typeparam>
            /// <param name="id">Identifier of the element to delete.</param>
            /// <returns>RepositoryResponse.RepositoryDelete if the element has been successfully deleted,
            /// RepositoryResponse.RepositoryGenericError otherwise</returns>
            public override RepositoryResponse Delete <DBType>(string id)
            {
                lock (_store)
                {
                    using (IDocumentSession _session = _store.OpenSession())
                    {
                        var entity = _session.Load <DBType>(id);
                        if (entity != null)
                        {
                            /*try
                             * {
                             *  using (TransactionScope tx = new TransactionScope())
                             *  {*/
                            _session.Delete <DBType>(entity);
                            _session.SaveChanges();
                            //    tx.Complete();
                            log.Debug("Data with id " + id + " deleted");
                            //}
                            return(RepositoryResponse.RepositoryDelete);

                            /*}
                             * catch (TransactionAbortedException tae)
                             * {
                             *  log.Error("Transaction Aborted", tae);
                             *  return RepositoryResponse.RepositoryGenericError;
                             * }*/
                        }
                        else
                        {
                            return(RepositoryResponse.RepositoryGenericError);
                        }
                    }
                }
            }
Exemple #23
0
        static void RenewUniqueness(IDocumentSession session, ISagaData sagaData)
        {
            var ids = GetUniquePropertyIdsFromMetaData(session, sagaData);
            var uniqueSagaProperties  = session.Load <UniqueSagaProperty>(ids);
            var uniqueSagaPropertyIds = new List <string>();

            foreach (var uniqueSagaProperty in uniqueSagaProperties)
            {
                var value          = Reflect.Value(sagaData, uniqueSagaProperty.PropertyPath);
                var id             = GetIdForUniqueProperty(sagaData.GetType(), uniqueSagaProperty.PropertyPath, value);
                var sagaDocumentId = session.Advanced.GetDocumentId(sagaData);

                if (id != uniqueSagaProperty.Id)
                {
                    session.Delete(uniqueSagaProperty);
                    session.Store(new UniqueSagaProperty {
                        Id = id, PropertyPath = uniqueSagaProperty.PropertyPath, SagaId = sagaDocumentId
                    });
                }

                uniqueSagaPropertyIds.Add(id);
            }

            SetUniquePropertyIdsToMetaData(session, sagaData, uniqueSagaPropertyIds);
        }
Exemple #24
0
        /// <summary>
        ///     Releases the mutex.
        /// </summary>
        private void Dispose(bool disposing)
        {
            if (_session != null && _lock != null)
            {
                try
                {
                    _session.Delete(_lock);
                    _session.SaveChanges();
                }
                finally
                {
                    _lock = null;
                }
            }

            if (_session != null)
            {
                _session.Dispose();
            }

            if (disposing)
            {
                _session = null;
            }
        }
 public void Execute(IDocumentSession session, IEnumerable <object> objects)
 {
     foreach (var document in objects.OfType <T>())
     {
         session.Delete(document);
     }
 }
        public static string ValidateUser(IDocumentSession ravenSession, string username, string password)
        {
            // try to get a user from the database that matches the given username and password
            var userRecord = ravenSession.Load<User>("users/" + username);
            if (userRecord == null)
            {
                return null;
            }

            // verify password
            var hashedPassword = GenerateSaltedHash(password, userRecord.Salt);
            if (!CompareByteArrays(hashedPassword, userRecord.Password))
                return null;

            // cleanup expired or unusesd tokens
            foreach (var token in ravenSession.Query<ApiKeyToken>().Where(x => x.UserId == userRecord.Id))
            {
                if (DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(7)) > token.LastActivity)
                    ravenSession.Delete(token);
            }

            // now that the user is validated, create an api key that can be used for subsequent requests
            var apiKey = Guid.NewGuid().ToString();
            ravenSession.Store(new ApiKeyToken { UserId = userRecord.Id, SessionStarted = DateTimeOffset.UtcNow, LastActivity = DateTimeOffset.UtcNow }, GetApiKeyDocumentId(apiKey));
            ravenSession.SaveChanges();

            return apiKey;
        }
        private bool ForwardCurrentBatch(IDocumentSession session, CancellationToken cancellationToken)
        {
            Log.Debug("Looking for batch to forward");

            var nowForwarding = session.Include <RetryBatchNowForwarding, RetryBatch>(r => r.RetryBatchId)
                                .Load <RetryBatchNowForwarding>(RetryBatchNowForwarding.Id);

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

                var forwardingBatch = session.Load <RetryBatch>(nowForwarding.RetryBatchId);

                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);
        }
Exemple #28
0
        private static void SetupTestData(IDocumentStore store)
        {
            new Product_AvailableForSale2().Execute(store);

            Product product1 = new Product("MyName1", "MyBrand1");
            Product product2 = new Product("MyName2", "MyBrand2");

            FacetSetup facetSetup = new FacetSetup {
                Id = "facets/ProductFacets", Facets = new List <Facet> {
                    new Facet {
                        FieldName = "Brand"
                    }
                }
            };

            using (IDocumentSession docSession = store.OpenSession())
            {
                foreach (var productDoc in docSession.Query <Product>())
                {
                    docSession.Delete(productDoc);
                }
                docSession.SaveChanges();

                docSession.Store(product1);
                docSession.Store(product2);
                docSession.Store(facetSetup);
                docSession.SaveChanges();
            }
        }
        public static void DeleteOwnerById(IDocumentStore store)
        {
            string id = NormalizeOwnerId(ReadNotEmptyString("Enter the Id of the owner to delete."));

            double Num;

            bool isNum = double.TryParse(id, out Num);

            if (isNum)
            {
                Console.WriteLine(id);
            }
            else
            {
                Console.WriteLine("Invalid Number");
            }


            using (IDocumentSession session = store.OpenSession())
            {
                session.Delete(id);
                session.SaveChanges();
                Console.WriteLine("Deleted user " + id);
            }
            PressAnyKeyToContinue();
        }
Exemple #30
0
        private async Task applyProjectionsAsync(IDocumentSession session, ICollection <EventProjection> projections, IEnumerable <TView> views)
        {
            var idAssigner = session.Tenant.IdAssignmentFor <TView>();
            var resolver   = session.Tenant.StorageFor <TView>();
            var viewMap    = views.ToDictionary(view => (TId)resolver.IdentityFor(view), view => view);

            foreach (var eventProjection in projections)
            {
                var viewId          = eventProjection.ViewId;
                var hasExistingView = viewMap.TryGetValue(viewId, out var view);
                if (!hasExistingView)
                {
                    if (eventProjection.Type == ProjectionEventType.CreateAndUpdate)
                    {
                        view = newView(session.Tenant, idAssigner, viewId);
                        viewMap.Add(viewId, view);
                        hasExistingView = true;
                    }
                }

                if (eventProjection.Type == ProjectionEventType.CreateAndUpdate ||
                    (eventProjection.Type == ProjectionEventType.UpdateOnly && hasExistingView))
                {
                    session.Store(view);
                    eventProjection.ProjectTo(session, view).Wait();
                }
                else if (eventProjection.Type == ProjectionEventType.Delete &&
                         hasExistingView &&
                         await eventProjection.ShouldDelete(session, view))
                {
                    session.Delete(view);
                }
            }
        }
        public static string ValidateUser(IDocumentSession ravenSession, string username, string password)
        {
            // try to get a user from the database that matches the given username and password
            var userRecord = ravenSession.Load <User>("users/" + username);

            if (userRecord == null)
            {
                return(null);
            }

            // verify password
            var hashedPassword = GenerateSaltedHash(password, userRecord.Salt);

            if (!CompareByteArrays(hashedPassword, userRecord.Password))
            {
                return(null);
            }

            // clear previous tokens
            foreach (var token in ravenSession.Query <ApiKeyToken>().Where(x => x.UserId == userRecord.Id))
            {
                ravenSession.Delete(token);
            }

            // now that the user is validated, create an api key that can be used for subsequent requests
            var apiKey = Guid.NewGuid().ToString();

            ravenSession.Store(new ApiKeyToken {
                UserId = userRecord.Id, SessionStarted = DateTimeOffset.UtcNow
            }, GetApiKeyDocumentId(apiKey));
            ravenSession.SaveChanges();

            return(apiKey);
        }
Exemple #32
0
        private void applyProjections(IDocumentSession session, ICollection <EventProjection> projections, IEnumerable <TView> views)
        {
            var viewMap = createViewMap(session, projections, views);

            foreach (var eventProjection in projections)
            {
                var hasView = viewMap.TryGetValue(eventProjection.ViewId, out TView view);

                if (!hasView)
                {
                    continue;
                }

                using (Util.NoSynchronizationContextScope.Enter())
                {
                    if (eventProjection.Type == ProjectionEventType.Delete)
                    {
                        var shouldDeleteTask = eventProjection.ShouldDelete(session, view);
                        shouldDeleteTask.Wait();
                        if (shouldDeleteTask.Result)
                        {
                            session.Delete(view);
                        }
                    }
                    else
                    {
                        eventProjection.ProjectTo(session, view).Wait();
                    }
                }
            }
        }
 public static void Delete(this Project project, IDocumentSession session)
 {
     session.Query<Activity>()
         .Where(a => a.Project == project.Id).ToList().ForEach(a => a.Delete(session));
     session.Query<Discussion>()
         .Where(d => d.Entity == project.Id).ToList().ForEach(d => d.Delete(session));
     session.Delete(project);
 }
        /// <summary>
        /// delete an HRProcess and any assocoiated child tasks and meetings
        /// </summary>
        /// <param name="process"></param>
        /// <param name="session"></param>
        public static void DeleteProcessAndChildren(HRProcess process, IDocumentSession session)
        {
            var subject = session.Load<User>(process.Subject.UserId);
            subject.CurrentState = string.Empty;
            session.Delete(process);

            var childtasks = session.Query<Task>().Where(t => t.ParentItemId == process.Id);
            foreach (var t in childtasks)
            {
                session.Delete(t);
            }
            var childmeetings = session.Query<Meeting>().Where(t => t.ParentItemId == process.Id);
            foreach (var t in childmeetings)
            {
                session.Delete(t);
            }

        }
Exemple #35
0
        /// <summary>
        /// Deletes the user.
        /// </summary>
        /// <param name="ravenSession">The raven session.</param>
        /// <param name="id">The identifier.</param>
        /// <returns>The identifier of the deleted user.</returns>
        public string DeleteUser(IDocumentSession ravenSession, string id)
        {
            var currentDbModel = ravenSession.Load<User>(id);

            if (currentDbModel == null)
            {
                return null;
            }

            ravenSession.Delete<User>(currentDbModel);
            ravenSession.SaveChanges();

            return id;
        }
        public static IUserIdentity GetUserFromApiKey(IDocumentSession ravenSession, string apiKey)
        {
            if (apiKey == null)
                return null;

            var activeKey = ravenSession.Include<ApiKeyToken>(x => x.UserId).Load(GetApiKeyDocumentId(apiKey));
            if (activeKey == null)
                return null;

            if (DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(7)) > activeKey.LastActivity)
            {
                ravenSession.Delete(activeKey);
                ravenSession.SaveChanges();
                return null;
            }

            activeKey.LastActivity = DateTimeOffset.Now;
            ravenSession.SaveChanges();
            return ravenSession.Load<User>(activeKey.UserId);
        }
        public TodoModule(IDocumentStore documentStore, IDocumentSession documentSession)
            : base("todo")
        {
            _documentStore = documentStore;
            _documentSession = documentSession;

            Get["/"] = _ =>
            {
                return Response.AsJson<List<Todo>>(_documentSession.Query<Todo>().ToList());
            };

            Post["/"] = _ =>
            {
                var todo = this.Bind<Todo>();
                _documentSession.Store(todo);
                return Response.AsJson<Todo>(todo, HttpStatusCode.Created);
            };

            Put["/"] = _ =>
            {
                var todo = this.Bind<Todo>();

                _documentSession.Store(todo);

                return Response.AsJson<Todo>(todo);
            };

            Delete["/"] = _ =>
            {
                var todo = this.Bind<Todo>();

                todo = _documentSession.Load<Todo>(todo.Id);
                _documentSession.Delete<Todo>(todo);

                return Response.AsJson<Todo>(todo);
            };
        }
 private static void DeleteConfiguration(IDocumentSession session, string key)
 {
     var applicantsConfiguration = session.Load<dynamic>(key);
     if (applicantsConfiguration != null)
         session.Delete(applicantsConfiguration);
 }
        public HomeModule(DataUploadHelper dataUploadHelper, IDocumentSession session, DropboxHelper dropboxHelper)
        {
            _dataUploadHelper = dataUploadHelper;
            _session = session;
            _dropboxHelper = dropboxHelper;

            Get["/"] = x =>
            {
                TaskExecutor.DropboxHelper = _dropboxHelper;
                TaskExecutor.ExecuteTask(new DeleteDataMoreThanDayTask());

                return View["index.html"];
            };

            Post["/fileupload"] = x =>
            {
                var file = this.Request.Files.FirstOrDefault();
                string dataId;
                try
                {
                    if (file == null)
                    {
                        var str = Request.Form["data"].Value as string;
                        dataId = _dataUploadHelper.UploadData(Request.Form["data"].Value as string);
                    }
                    else
                    {

                        dataId = _dataUploadHelper.UploadData(file.ContentType, file.Value, Path.GetExtension(file.Name));
                    }
                }
                catch (FileLoadException)
                {
                    return HttpStatusCode.InsufficientStorage;
                }

                return dataId;
            };

            Get["/view/datas/{Id}"] = x =>
            {
                string id = x.Id.Value;

                Data data = _session.Load<Data>("datas/" + id);
                if (data == null)
                {
                    return View["expire.html"];
                }
                data.TimesView--;

                if (data.TimesView == 0)
                {
                    if (data.Url != null && data.Url != string.Empty)
                    {
                        _dropboxHelper.DeleteFile(data.Url);
                    }

                    session.Delete<Data>(data);
                    return View["expire.html"];
                }

                if (data.ContentType == "text/plain" && data.Url == null || data.Url == string.Empty)
                    return View["view", new { Data = data.Text, SessionId = Guid.NewGuid().ToString() }];

                var fileBytes = _dropboxHelper.GetFile(data.Url);
                var memoryStream = new MemoryStream(fileBytes);

                return Response.FromStream(memoryStream, data.ContentType);
            };
        }
Exemple #40
0
        private static void ImportFolder(string folderName, IDocumentSession session, string bookName = "")
        {
            Console.WriteLine("Importing folder " + folderName);
            Book book = null;
            if (!string.IsNullOrEmpty(bookName))
            {
                var books = session.Query<Book>().Where(x => x.Name.Equals(bookName)).ToList();
                book = books.FirstOrDefault();
                if (book != null)
                {
                    Console.WriteLine("Deleting book " + book.Name);
                    session.Delete<Book>(book);
                }

                book = new Book() { Name = bookName };
                session.Store(book);
                Console.WriteLine("Saved book " + book.Name);
            }

            foreach (var filePath in Directory.GetFiles(folderName))
            {
                ImportFile(session, filePath, book);
                //File.Delete(filePath);
            }
        }
Exemple #41
0
		private static void PurgeSystemLog(IDocumentSession session)
		{
			bool done = false;
			int batchSize = 100;
			int totalDeleted = 0;
			while(!done)
			{
				var list = session.Query<SystemLog>()
				//.Customize(i=>i.WaitForNonStaleResultsAsOfNow())
					.Take(batchSize);
				if(list.Count() < batchSize)
				{
					done = true;
				}
				foreach(var item in list)
				{
					session.Delete(item);
					totalDeleted++;
				}
				session.SaveChanges();
				Console.WriteLine(totalDeleted.ToString() + " records deleted");
				Debug.WriteLine(totalDeleted.ToString() + " records deleted");
			}
		}
 public static void Delete(this Activity activity,IDocumentSession session)
 {
     session.Query<Discussion>()
         .Where(d => d.Entity == activity.Id).ToList().ForEach(d => d.Delete(session));
     session.Delete(activity);
 }
 private static void Remove(IDocumentSession session, string subscriber, string messageType)
 {
     var subscription = session.Query<Subscription>()
         .Where(s => s.Subscriber == subscriber && s.MessageType == messageType).SingleOrDefault();
     if (subscription != null)
         session.Delete(subscription);
 }
        void Forward(RetryBatch forwardingBatch, IDocumentSession session)
        {
            var messageCount = forwardingBatch.FailureRetries.Count;

            if (isRecoveringFromPrematureShutdown)
            {
                returnToSender.Run(IsPartOfStagedBatch(forwardingBatch.StagingId));
            }
            else if(messageCount > 0)
            {
                returnToSender.Run(IsPartOfStagedBatch(forwardingBatch.StagingId), messageCount);
            }

            session.Delete(forwardingBatch);

            Log.InfoFormat("Retry batch {0} done", forwardingBatch.Id);
        }
        bool Stage(RetryBatch stagingBatch, IDocumentSession session)
        {
            var stagingId = Guid.NewGuid().ToString();

            var matchingFailures = session.Load<FailedMessageRetry>(stagingBatch.FailureRetries)
                .Where(r => r != null && r.RetryBatchId == stagingBatch.Id)
                .ToArray();

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

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

            var messages = session.Load<FailedMessage>(messageIds);

            foreach (var message in messages)
            {
                StageMessage(message, stagingId);
            }

            bus.Publish<MessagesSubmittedForRetry>(m =>
            {
                m.FailedMessageIds = messages.Select(x => x.UniqueMessageId).ToArray();
                m.Context = stagingBatch.Context;
            });

            stagingBatch.Status = RetryBatchStatus.Forwarding;
            stagingBatch.StagingId = stagingId;
            stagingBatch.FailureRetries = matchingFailures.Select(x => x.Id).ToArray();

            Log.InfoFormat("Retry batch {0} staged {1} messages", stagingBatch.Id, messages.Length);
            return true;
        }
        bool ProcessBatches(IDocumentSession session)
        {
            var nowForwarding = session.Include<RetryBatchNowForwarding, RetryBatch>(r => r.RetryBatchId)
                .Load<RetryBatchNowForwarding>(RetryBatchNowForwarding.Id);

            if (nowForwarding != null)
            {
                var forwardingBatch = session.Load<RetryBatch>(nowForwarding.RetryBatchId);

                if (forwardingBatch != null)
                {
                    Forward(forwardingBatch, session);
                }

                session.Delete(nowForwarding);
                return true;
            }

            isRecoveringFromPrematureShutdown = false;

            var stagingBatch = session.Query<RetryBatch>()
                .Customize(q => q.Include<RetryBatch, FailedMessageRetry>(b => b.FailureRetries))
                .FirstOrDefault(b => b.Status == RetryBatchStatus.Staging);

            if (stagingBatch != null)
            {
                if (Stage(stagingBatch, session))
                {
                    session.Store(new RetryBatchNowForwarding { RetryBatchId = stagingBatch.Id }, RetryBatchNowForwarding.Id);
                }
                return true;
            }

            return false;
        }
 public static void Delete(this Discussion discussion, IDocumentSession session)
 {
     session.Delete(discussion);
 }
        public DinnerModuleAuth(IDocumentSession documentSession)
            : base("/dinners")
        {
            this.RequiresAuthentication();

            Get["/create"] = parameters =>
            {
                Dinner dinner = new Dinner()
                {
                    EventDate = DateTime.Now.AddDays(7)
                };

                base.Page.Title = "Host a Nerd Dinner";

                base.Model.Dinner = dinner;

                return View["Create", base.Model];
            };

            Post["/create"] = parameters =>
                {
                    var dinner = this.Bind<Dinner>();
                    var result = this.Validate(dinner);

                    if (result.IsValid)
                    {
                        UserIdentity nerd = (UserIdentity)this.Context.CurrentUser;
                        dinner.HostedById = nerd.UserName;
                        dinner.HostedBy = nerd.FriendlyName;

                        RSVP rsvp = new RSVP();
                        rsvp.AttendeeNameId = nerd.UserName;
                        rsvp.AttendeeName = nerd.FriendlyName;

                        dinner.RSVPs = new List<RSVP>();
                        dinner.RSVPs.Add(rsvp);

                        documentSession.Store(dinner);
                        documentSession.SaveChanges();

                        return this.Response.AsRedirect("/dinners/" + dinner.DinnerID);
                    }
                    else
                    {
                        base.Page.Title = "Host a Nerd Dinner";
                        base.Model.Dinner = dinner;
                        foreach (var item in result.Errors)
                        {
                            foreach (var member in item.MemberNames)
                            {
                                base.Page.Errors.Add(new ErrorModel() { Name = member, ErrorMessage = item.GetMessage(member) });
                            }
                        }
                    }

                    return View["Create", base.Model];
                };

            Get["/delete/" + Route.AnyIntAtLeastOnce("id")] = parameters =>
                {
                    Dinner dinner = documentSession.Load<Dinner>((int)parameters.id);

                    if (dinner == null)
                    {
                        base.Page.Title = "Nerd Dinner Not Found";
                        return View["NotFound", base.Model];
                    }

                    if (!dinner.IsHostedBy(this.Context.CurrentUser.UserName))
                    {
                        base.Page.Title = "You Don't Own This Dinner";
                        return View["InvalidOwner", base.Model];
                    }

                    base.Page.Title = "Delete Confirmation: " + dinner.Title;

                    base.Model.Dinner = dinner;

                    return View["Delete", base.Model];
                };

            Post["/delete/" + Route.AnyIntAtLeastOnce("id")] = parameters =>
                {
                    Dinner dinner = documentSession.Load<Dinner>((int)parameters.id);

                    if (dinner == null)
                    {
                        base.Page.Title = "Nerd Dinner Not Found";
                        return View["NotFound", base.Model];
                    }

                    if (!dinner.IsHostedBy(this.Context.CurrentUser.UserName))
                    {
                        base.Page.Title = "You Don't Own This Dinner";
                        return View["InvalidOwner", base.Model];
                    }

                    documentSession.Delete(dinner);
                    documentSession.SaveChanges();

                    base.Page.Title = "Deleted";
                    return View["Deleted", base.Model];
                };

            Get["/edit" + Route.And() + Route.AnyIntAtLeastOnce("id")] = parameters =>
                {
                    Dinner dinner = documentSession.Load<Dinner>((int)parameters.id);

                    if (dinner == null)
                    {
                        base.Page.Title = "Nerd Dinner Not Found";
                        return View["NotFound", base.Model];
                    }

                    if (!dinner.IsHostedBy(this.Context.CurrentUser.UserName))
                    {
                        base.Page.Title = "You Don't Own This Dinner";
                        return View["InvalidOwner", base.Model];
                    }

                    base.Page.Title = "Edit: " + dinner.Title;
                    base.Model.Dinner = dinner;

                    return View["Edit", base.Model];
                };

            Post["/edit" + Route.And() + Route.AnyIntAtLeastOnce("id")] = parameters =>
                {
                    Dinner dinner = documentSession.Load<Dinner>((int)parameters.id);

                    if (!dinner.IsHostedBy(this.Context.CurrentUser.UserName))
                    {
                        base.Page.Title = "You Don't Own This Dinner";
                        return View["InvalidOwner", base.Model];
                    }

                    this.BindTo(dinner);

                    var result = this.Validate(dinner);

                    if (!result.IsValid)
                    {
                        base.Page.Title = "Edit: " + dinner.Title;
                        base.Model.Dinner = dinner;
                        foreach (var item in result.Errors)
                        {
                            foreach (var member in item.MemberNames)
                            {
                                base.Page.Errors.Add(new ErrorModel() { Name = member, ErrorMessage = item.GetMessage(member) });
                            }
                        }

                        return View["Edit", base.Model];
                    }

                    documentSession.SaveChanges();

                    return this.Response.AsRedirect("/" + dinner.DinnerID);

                };

            Get["/my"] = parameters =>
                {
                    string nerdName = this.Context.CurrentUser.UserName;

                    var userDinners = documentSession.Query<Dinner, Dinners_Index>()
                                    .Where(x => x.HostedById == nerdName || x.HostedBy == nerdName || x.RSVPs.Any(r => r.AttendeeNameId == nerdName || (r.AttendeeNameId == null && r.AttendeeName == nerdName)))
                                    .OrderBy(x => x.EventDate)
                                    .AsEnumerable();

                    base.Page.Title = "My Dinners";
                    base.Model.Dinners = userDinners;

                    return View["My", base.Model];
                };
        }
		public void Leave(string roomName, IDocumentSession session = null)
		{
			//using (var session = store.OpenSession())
			var isExternalSession = session == null;
			if (session == null)
				session = store.OpenSession();

			try
			{
				if (!joinedRooms.Any(r => r.Name.Equals(roomName, StringComparison.InvariantCultureIgnoreCase)))
				{
					Console.WriteLine("Cannot leave because not joined..");
					return;
				}

				var roomToLeave = session.Load<Room>($"rooms/{roomName}");
				if (roomToLeave != null)
				{
					roomToLeave.Users.Remove($"users/{username}");
					if (roomToLeave.Users.Count == 0) //room is empty - no need to keep it
					{
						var idsToDelete = new List<string>();
						using (var stream = session.Advanced.Stream(
							session.Query<Message, MessagesByRoomIndex>()))
						{
							do
							{
								if(stream.Current != null)
									session.Delete(stream.Current.Key);
							} while (stream.MoveNext());
						}
						session.Delete(roomToLeave);
					}
				}

				joinedRooms.RemoveAt(joinedRooms.FindIndex(r => r.Id == roomToLeave.Id));
				session.SaveChanges();
				Console.WriteLine($"Left room {roomName}");
			}
			finally
			{
				if (isExternalSession)
					session.Dispose();
			}
		}