예제 #1
0
        public override void Commit()
        {
            var toPatch = _patchRequests.ToLookup(a => a.Key, a => a.Value);

            foreach (var item in toPatch)
            {
                foreach (var patch in item.Select(x => new PatchCommandData(item.Key, null, x, null)))
                {
                    _session.Advanced.Defer(patch);
                }
            }

            try {
                _session.SaveChanges();
                _session.Dispose();
            } catch {
                Logger.Error("- Concurrency exception");
                _session.Dispose();
                throw;
            }

            foreach (var command in _afterCommitCommandQueue)
            {
                command();
            }
        }
        /// <summary>
        /// Occurs after the action method is invoked.
        /// </summary>
        /// <param name="context">The context for the action.</param>
        public void OnActionExecuted(
            HttpActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                return;
            }

            if (_session != null)
            {
                if (_session.Advanced.NumberOfRequests > 30)
                {
                    Debug.WriteLine("Number of recommended (30) remote call requests have been exceeded");
                }

                lock (_session)
                {
                    _session.SaveChanges();
                    _session.Advanced.Clear();
                    _session.Dispose();
                }
            }

            if (_asyncSession != null)
            {
                _asyncSession.SaveChangesAsync();
                _asyncSession.Advanced.Clear();
                _asyncSession.Dispose();
            }
        }
예제 #3
0
        public virtual void SaveChanges()
        {
            if (_session == null)
            {
                return;
            }

            _session.SaveChanges();
            _session.Dispose();
            _session = null;
        }
        public void Add_Adds_Customer_To_Store()
        {
            var customerFake = new CustomerFake();

            _repository.Add(customerFake);

            Received.InOrder(() =>
            {
                _defaultSession.Store(customerFake);
                _defaultSession.SaveChanges();
                _defaultSession.Dispose();
            });
        }
예제 #5
0
        public void AddStoresDocument()
        {
            Expect.Call(() => _session.Store(_document1));
            Expect.Call(() => _session.SaveChanges());
            Expect.Call(() => _session.Dispose());
            _mocks.ReplayAll();

            using (new DocumentSessionScope(_session))
            {
                _repository.Save(_document1);
            }
            _mocks.VerifyAll();
        }
예제 #6
0
        /// <summary>
        /// Occurs after the action method is invoked.
        /// </summary>
        /// <param name="context">The context for the action.</param>
        public void OnActionExecuted(
            HttpActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                return;
            }

            lock (_session)
            {
                _session?.SaveChanges();
                _session?.Advanced.Clear();
                _session?.Dispose();
            }
        }
예제 #7
0
        public void SetOrganisation(Organisation organisation, bool allowReset = false /*some system tasks require us to do this*/)
        {
            if (!allowReset && _organisation != null && _organisation.FriendlyId != organisation.FriendlyId)
            {
                throw new InvalidOperationException("Cannot set Organisation twice in one session.");
            }

            _organisation = organisation;
            if (_organisationSession != null)
            {
                _organisationSession.Dispose();
            }

            _organisationSession = null;
        }
 public override void Dispose()
 {
     if (Session != null)
     {
         Session.Dispose();
     }
 }
        public override void Dispose()
        {
            _session.Dispose();
            _store.Dispose();

            base.Dispose();
        }
예제 #10
0
 public void Dispose()
 {
     if (session != null)
     {
         session.Dispose();
     }
 }
예제 #11
0
        public Task AddTrackInfosAsync(List <TrackInfo> trackInfos, IDocumentSession session = null)
        {
            this.ThrowIfDisposed();
            if (trackInfos == null)
            {
                throw new ArgumentNullException("trackInfo");
            }
            IDocumentSession localSession = session;

            if (session == null)
            {
                localSession = RavenContext.Current.CreateSession();
            }


            foreach (var trackInfo in trackInfos)
            {
                localSession.Store(trackInfo);
            }
            localSession.SaveChanges();
            if (session == null)
            {
                localSession.Dispose();
            }

            return(Task.FromResult(true));
        }
예제 #12
0
        public void GetVersionAndHasVersion()
        {
            Expect.Call(_session.Load <VersionContainerTest>(Id6)).Return(new VersionContainerTest());
            Expect.Call(() => _session.SaveChanges());
            Expect.Call(() => _session.Dispose());
            _mocks.ReplayAll();

            using (new DocumentSessionScope(_session))
            {
                Assert.IsTrue(_repository.HasVersion(Id6));
            }

            _mocks.VerifyAll();

            Assert.IsFalse(_repository.HasVersion(string.Empty));
        }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _documentSession?.Dispose();
     }
 }
예제 #14
0
 public void Dispose()
 {
     store.Dispose();
     session.Dispose();
     store   = null;
     session = null;
 }
예제 #15
0
 public virtual void Dispose()
 {
     if (_disposeDocumentSession && _documentSession != null)
     {
         _documentSession.Dispose();
     }
 }
예제 #16
0
 public void Dispose()
 {
     if (_documentSession != null)
     {
         _documentSession.Dispose();
     }
 }
예제 #17
0
 public override void Dispose()
 {
     Debug.WriteLine("I AM BEING DISPOSED!");
     theSession.Dispose();
     theStore.Dispose();
     theContainer.Dispose();
 }
예제 #18
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         session.Dispose();
     }
 }
        public static AuthorizedSession OpenSession(IDocumentStore store, string userId, string password)
        {
            IDocumentSession session = null;

            try
            {
                session = store.OpenSession();
                var user = session.Load <AuthorizedUser>(userId);
                if (user == null)
                {
                    ThrowNoPermissions(userId);
                }
                //TODO:change to graph query
                if (CheckValidAuthorizedUser(userId, password, user.PasswordHash) == false)
                {
                    ThrowNoPermissions(userId);
                }
                return(new AuthorizedSession(store, session, user));
            }
            catch
            {
                session?.Dispose();
                throw;
            }
        }
        public async Task ShouldUpdateDocumentInRepository()
        {
            var address = await InsertAddress();

            Guid meterId = Guid.NewGuid();

            var repo = CreateGenericMartenRepository();

            var loadedAddress = await repo.Get(address);

            loadedAddress.AssignMeter(meterId);

            repo.Update(loadedAddress);

            await _session.SaveChangesAsync();

            _session.Dispose();

            _session = _fixture.DocumentStore.OpenSession();

            repo = CreateGenericMartenRepository();

            loadedAddress = await repo.Get(address);

            Assert.True(loadedAddress.GetMeters().Any(i => i == meterId));
        }
예제 #21
0
        public void EndSession(bool succesfully)
        {
            ICallContext currentContext = this.callContextFactory.RetrieveCallContext();

            IDocumentSession session = currentContext[SessionStateKey] as IDocumentSession;

            if (session == null)
            {
                logger.Debug("There is no session into the current context.");
                return;
            }

            try
            {
                if (succesfully)
                {
                    logger.Debug("Saving changes");
                    session.SaveChanges();
                }
                else
                {
                    logger.Debug("An error occured, so I'm not flushing the changes");
                }
            }
            finally
            {
                session.Dispose();
                currentContext[SessionStateKey] = null;
                logger.Debug("Session Removed");
            }
        }
예제 #22
0
        private void LoadAndSubscribeButton_Click(object sender, EventArgs e)
        {
            _session  = DocumentStoreHolder.Store.OpenSession();
            _category = _session.Load <Category>(CategoryIdTextbox.Text);

            if (_category == null)
            {
                MessageBox.Show("Category not found!");
                _session.Dispose();
            }
            else
            {
                NameTextbox.Text        = _category.Name;
                DescriptionTextbox.Text = _category.Description;

                _localEtag    = _session.Advanced.GetEtagFor(_category);
                _subscription = DocumentStoreHolder.Store
                                .Changes()
                                .ForDocument(CategoryIdTextbox.Text)
                                .Where(DocumentChangedByOtherUser)
                                .Subscribe(DocumentChangedOnServer);

                ToggleEditing();
            }
        }
예제 #23
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;
            }
        }
예제 #24
0
        /// <summary>
        /// Customize the store configuration for one off tests.
        /// The return value is the database schema
        /// </summary>
        /// <param name="configure"></param>
        /// <returns></returns>
        protected string StoreOptions(Action <StoreOptions> configure)
        {
            if (_session != null)
            {
                _session.Dispose();
                Disposables.Remove(_session);
                _session = null;
            }


            var options = new StoreOptions();

            options.Connection(ConnectionSource.ConnectionString);

            // Can be overridden
            options.AutoCreateSchemaObjects = AutoCreate.All;
            options.NameDataLength          = 100;
            options.DatabaseSchemaName      = GetType().Name.Sanitize();

            configure(options);

            _store = new DocumentStore(options);
            Disposables.Add(_store);

            _store.Advanced.Clean.CompletelyRemoveAll();

            return(options.DatabaseSchemaName);
        }
예제 #25
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         documentSession.Dispose();
     }
     base.Dispose(disposing);
 }
예제 #26
0
 public virtual void Dispose()
 {
     _store?.Dispose();
     if (_session != null)
     {
         _session.Dispose();
     }
 }
예제 #27
0
 public void Dispose()
 {
     foreach (var disposable in _stores)
     {
         disposable.Dispose();
     }
     _session?.Dispose();
     _store?.Dispose();
 }
예제 #28
0
 /// <summary>
 /// Closes the session.
 /// </summary>
 protected void PossiblyCloseSession()
 {
     // Only close the session for the instance that opened it originally.
     if (_isInitialDalInstance == true)
     {
         _session.Dispose();
         _session = null;
     }
 }
예제 #29
0
 protected override void OnUnload(EventArgs e)
 {
     if (_session != null)
     {
         _session.Dispose();
         _session = null;
     }
     base.OnUnload(e);
 }
예제 #30
0
        public void Read()
        {
            _reader.OnDocument += _reader_OnDocument;
            _session = MvcApplication.DocumentStore.OpenSession();
            _reader.Read();

            _session.SaveChanges();
            _session.Dispose();
        }
예제 #31
0
 public void Dispose()
 {
     Repository.Dispose();
     _session.Dispose();
     if (_scope != null)
     {
         _scope.Dispose();
     }
 }
예제 #32
0
        public DeviceModule(ILogger logger, IDeviceRepository deviceRepository, IDocumentSession documentSession)
            : base("/devices")
        {
            Get["/"] = p =>
            {
                var registeredDevices = deviceRepository.GetAll();
                var registeredDeviceDtos = Mapper.Map<IEnumerable<RegisteredDeviceDto>>(registeredDevices);
                return Response.AsJson(registeredDeviceDtos);
            };

            Post["/"] = p =>
            {
                var newDeviceRequest = this.Bind<DeviceSetupRequest>();

                var registeredDevice = new RegisteredDevice(newDeviceRequest.DeviceName, newDeviceRequest.DeviceType, newDeviceRequest.IpAddress);
                deviceRepository.Add(registeredDevice);

                documentSession.SaveChanges();
                documentSession.Dispose();

                return HttpStatusCode.OK;
            };

            Post["/{name}/{commandRoute}"] = p =>
            {
                Response response = HttpStatusCode.NotFound;

                //Lookup IP address and device type from device
                //TODO: Implement singleton DeviceMap object to cache and return this data
                var device = deviceRepository.FindByName(p.name);

                if (device != null)
                {
                    var commandRoute = String.Format("/{0}/{1}", device.Type, p.commandRoute);
                    response = new Response();
                    response.Headers.Add("cmd-route", commandRoute);
                    response.Headers.Add("cmd-ip", device.IpAddress);
                    response.StatusCode = HttpStatusCode.OK;

                    logger.Info(String.Format("Recievied the {0} command for the {1}.  Routing it to {2}", p.commandRoute, p.device, commandRoute));
                }

                return response;
            };

            Delete["/{name}"] = p =>
            {
                Response response = HttpStatusCode.NotFound;

                return response;
            };
        }
예제 #33
0
        public void CanUpdateTasks()
        {
            Task task = new Task { Description = "kuvaus", Status = "ToDo" };
            taskRepository.Save(task);
            session.Dispose();

            session = documentStore.OpenSession();
            taskRepository=new TaskRepository(session);
            var updateTask = taskRepository.Find().First();
            updateTask.Status = "Done";
            taskRepository.Update(updateTask);
            session.Dispose();

            session = documentStore.OpenSession();
            taskRepository = new TaskRepository(session);
            var result = taskRepository.Find().First();

            Assert.That(result.Status,Is.EqualTo("Done"));
        }
예제 #34
0
		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();
			}
		}
예제 #35
0
        private IEnumerable<EventBase> ConsumeEvents(IEnumerable<EventBase> events, IDocumentSession session)
        {
            var concurrencyExceptions = new List<EventBase>();

            foreach (var @event in events)
            {
                var interfaceType = typeof (IConsumerOf<>).MakeGenericType(@event.GetType());
                if (_eventConsumers.ContainsKey(interfaceType) == false)
                    continue;

                var consumers = _eventConsumers[interfaceType];

                foreach (var consumer in consumers)
                {
                    var instance = Activator.CreateInstance(consumer);
                    instance.GetType().GetProperty("Session").SetValue(instance, session);

                    if (instance is INeedClientSettings)
                    {
                        ((INeedClientSettings) instance).ClientSettings = _clientSettings;
                    }

                    try
                    {
                        instance.GetType().GetMethod("Consume", new[] { @event.GetType() }).Invoke(instance, new[] { @event });
                    }
                    catch (Exception exception)
                    {
                        throw new MessageConsumeException(exception, interfaceType, instance.GetType().Name);
                    }
                }

                try
                {
                    if(session.Advanced.HasChanges)
                        session.SaveChanges();
                }
                catch (ConcurrencyException)
                {
                    concurrencyExceptions.Add(@event);
                }
                finally
                {
                    session.Dispose();
                }
            }
            return concurrencyExceptions;
        }
예제 #36
0
 internal static void SaveAndCloseSession(IDocumentSession session)
 {
     session.SaveChanges();
     session.Dispose();
 }