/// <summary>
 /// Throws an exception if the specified object has been disposed.
 /// </summary>
 /// <param name="obj">The object in question.</param>
 public static void NotDisposed( DisposableObject obj )
 {
     if ( obj.IsDisposed )
     {
         throw new ObjectDisposedException( obj.GetType().Name );
     }
 }
 private void UsingKeyword()
 {
     using (DisposableObject disposable = new DisposableObject())
     {
         disposable.WriteOut("Invoking Method on IDisposable instnace.");
     }
 }
Exemplo n.º 3
0
 public void CastingWillSkipModulesWhichAreNotValidTargetsForTheCast()
 {
     var inner = new DisposableObject();
     dynamic value = new DelegatingObject( inner, new DelegatingObject() );
     IDisposable instance = value;
     Assert.AreSame( instance, inner );
 }
Exemplo n.º 4
0
 public void CastingToAnInterfaceWhenThereIsAConflictBetweenModulesPrefersTheModuleThatWasLoadedLast()
 {
     var first = new DisposableObject();
     var second = new DisposableObject();
     dynamic value = new DelegatingObject( first, second );
     IDisposable instance = value;
     Assert.AreSame( second, instance );
 }
Exemplo n.º 5
0
        public void DisposingContainerDisposesOwnedInstances()
        {
            DisposableObject o         = new DisposableObject();
            IUnityContainer  container = new UnityContainer()
                                         .RegisterInstance(typeof(object), o);

            container.Dispose();
            Assert.IsTrue(o.WasDisposed);
        }
Exemplo n.º 6
0
 protected override void DoCloseStream()
 {
     if (m_Writer != null)
     {
         m_Writer.Flush();
         m_Writer.Close();
         DisposableObject.DisposeAndNull(ref m_Writer);
     }
 }
Exemplo n.º 7
0
 public void AccessingDisposedClosure()
 {
     using (var disposableObject = new DisposableObject())
     {
         // Cannot fix this without rewriting - genuine bug
         SetAction(() => disposableObject.DoSomething(42));
     }
     CallAction();
 }
Exemplo n.º 8
0
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            m_Pile.WaitForCompleteStop();
            DisposableObject.DisposeAndNull(ref m_Threads);
            DisposableObject.DisposeAndNull(ref m_Graph);

            //DisposableObject.DisposeAndNull(ref m_CLRStore);
            //DisposableObject.DisposeAndNull(ref m_CLRThreads);
        }
Exemplo n.º 9
0
        public void ContainerDefaultsToInstanceOwnershipViaGenericMethod()
        {
            DisposableObject o         = new DisposableObject();
            IUnityContainer  container = new UnityContainer()
                                         .RegisterInstance(typeof(DisposableObject), o);

            container.Dispose();
            Assert.IsTrue(o.WasDisposed);
        }
Exemplo n.º 10
0
        public void DisposingContainerDoesNotDisposeUnownedInstances()
        {
            DisposableObject o         = new DisposableObject();
            IUnityContainer  container = new UnityContainer()
                                         .RegisterInstance(typeof(object), o, new ExternallyControlledLifetimeManager());

            container.Dispose();
            Assert.IsFalse(o.WasDisposed);
            GC.KeepAlive(o);
        }
Exemplo n.º 11
0
        protected override void Destructor()
        {
            base.Destructor();

            App.Singletons.Remove <PortalHub>();

            m_Portals.ForEach(p => p.Dispose());

            DisposableObject.DisposeAndNull(ref m_ContentFS);
        }
Exemplo n.º 12
0
        public void DisposingContainerDisposesOwnedObjects()
        {
            ILifetimeContainer container = new LifetimeContainer();
            DisposableObject   mdo       = new DisposableObject();

            container.Add(mdo);
            container.Dispose();

            Assert.IsTrue(mdo.WasDisposed);
        }
Exemplo n.º 13
0
        protected override void Destructor()
        {
            foreach (var hs in m_HostSets)
            {
                hs.Dispose();
            }

            DisposableObject.DisposeAndNull(ref m_InstrumentationEvent);
            base.Destructor();
        }
Exemplo n.º 14
0
        public void TestTryAddReferenceFailsAfterDispose()
        {
            var target = new DisposableObject();

            var reference = new ReferenceCountedDisposable <DisposableObject>(target);

            reference.Dispose();

            Assert.Null(reference.TryAddReference());
        }
Exemplo n.º 15
0
        /// <summary>
        /// Starts the application container, used by daemons directly
        /// </summary>
        public static void Stop()
        {
            DisposableObject.DisposeAndNull(ref s_Server);
            DisposableObject.DisposeAndNull(ref s_Application);

            if (s_Sipc != null)
            {
                DisposableObject.DisposeAndNull(ref s_Sipc);
            }
        }
Exemplo n.º 16
0
        public static IDisposable Binding <TFilter, TObject>(
            this AutoCompleteBox acb,
            IFilterViewModel <TFilter, TObject> filterViewModel,
            Action <IFilterViewModel <TFilter, TObject>, string> action = null,
            Action <bool> busy = null,
            int startWith      = 1)
        {
            var disposableObject = new DisposableObject();

            var searchTextEntered = acb.WhenAny(x => x.SearchText, x => x.Value)
                                    .Do(_ => filterViewModel.Abort())
                                    .Throttle(TimeSpan.FromSeconds(1))
                                    .Where(text => !string.IsNullOrWhiteSpace(text))
                                    .Where(text => text.Length >= startWith)
                                    .ObserveOnUiSafeScheduler()
                                    .Do(text =>
            {
                if (action != null)
                {
                    action(filterViewModel, string.Concat(text, "*"));
                }
            });

            disposableObject.Add(
                searchTextEntered.Subscribe(
                    _ =>
            {
                if (filterViewModel.Result != null)
                {
                    filterViewModel.Result.Clear();
                }

                filterViewModel.InvokeCommand.Execute(null);
            }));

            var loadCompleted = filterViewModel.WhenAny(x => x.Result, x => x.Value)
                                .Where(x => x != null && x.Count > 0);

            disposableObject.Add(loadCompleted.ObserveOnUiSafeScheduler().Subscribe(
                                     result =>
            {
                acb.ItemsSource = result;
                if (acb.IsKeyboardFocusWithin)
                {
                    acb.IsDropDownOpen = true;
                }
            }));

            if (busy != null)
            {
                disposableObject.Add(filterViewModel.WhenAnyValue(x => x.IsBusy).Subscribe(busy));
            }

            return(disposableObject);
        }
Exemplo n.º 17
0
        public void RemovingItemsFromContainerDoesNotDisposeThem()
        {
            ILifetimeContainer container = new LifetimeContainer();
            DisposableObject   mdo       = new DisposableObject();

            container.Add(mdo);
            container.Remove(mdo);
            container.Dispose();

            Assert.IsFalse(mdo.WasDisposed);
        }
Exemplo n.º 18
0
        protected override void Destructor()
        {
            DisposableObject.DisposeAndNull(ref m_ManagementEvent);

            foreach (var server in m_Servers)
            {
                server.Dispose();
            }

            base.Destructor();
        }
Exemplo n.º 19
0
        public static void DisposeMany()
        {
            var obj1 = new DisposableObject();
            var obj2 = new DisposableObject();

            False(obj1.IsDisposed);
            False(obj2.IsDisposed);
            Disposable.Dispose(obj1, obj2, null);
            True(obj1.IsDisposed);
            True(obj2.IsDisposed);
        }
Exemplo n.º 20
0
        protected override void DoStart()
        {
            if (m_TargetName.IsNullOrWhiteSpace())
            {
                throw new MDBException(StringConsts.MDB_STORE_CONFIG_NO_TARGET_NAME_ERROR);
            }

            if (m_Areas.Count == 0)
            {
                throw new MDBException(StringConsts.MDB_STORE_CONFIG_NO_AREAS_ERROR);
            }


            try
            {
                GDIDAuthorityService.CheckNameValidity(m_SchemaName);
                GDIDAuthorityService.CheckNameValidity(m_BankName);

                var gdidScope = GetGDIDScopePrefix(m_SchemaName, m_BankName);
                m_GDIDGenerator = new GDIDGenerator("GDIDGen({0})".Args(gdidScope), this, gdidScope, null);
                if (AgniSystem.IsMetabase)
                {
                    foreach (var ah in AgniSystem.Metabase.GDIDAuthorities)
                    {
                        m_GDIDGenerator.AuthorityHosts.Register(ah);
                        App.Log.Write(new NFX.Log.Message
                        {
                            Type  = NFX.Log.MessageType.InfoD,
                            Topic = SysConsts.LOG_TOPIC_MDB,
                            From  = GetType().FullName + ".makeGDIDGen()",
                            Text  = "Registered GDID authority host: " + ah.ToString()
                        });
                    }
                }
            }
            catch (Exception error)
            {
                throw new MDBException(StringConsts.MDB_STORE_CONFIG_GDID_ERROR + error.ToMessageWithType());
            }

            try
            {
                m_Cache      = new LocalCache("MDBDataStore::" + Name, this);
                m_Cache.Pile = new DefaultPile(m_Cache, "MDBDataStore::Pile::" + Name);
                m_Cache.Configure(null);
                m_Cache.Start();
            }
            catch
            {
                try { DisposableObject.DisposeAndNull(ref m_GDIDGenerator); } catch {}
                try { DisposableObject.DisposeAndNull(ref m_Cache); } catch {}
                throw;
            }
        }
Exemplo n.º 21
0
        public static async Task DisposeManyAsync()
        {
            var obj1 = new DisposableObject();
            var obj2 = new DisposableObject();

            False(obj1.IsDisposed);
            False(obj2.IsDisposed);
            await Disposable.DisposeAsync(obj1, obj2, null);

            True(obj1.IsDisposed);
            True(obj2.IsDisposed);
        }
Exemplo n.º 22
0
        bool IRunnableHook.Epilogue(Runner runner, FID id, Exception error)
        {
            Console.WriteLine("{0}.{1}".Args(GetType().FullName, "RigTearDown()..."));

            DoRigTearDown();

            DisposableObject.DisposeAndNull(ref m_TestApp);
            DisposableObject.DisposeAndNull(ref m_FS);
            Console.WriteLine("{0}.{1}".Args(GetType().FullName, "...RigTearDown() DONE"));

            return(false);
        }
Exemplo n.º 23
0
        public void DisposingParentDisposesChild()
        {
            UnityContainer  parent = new UnityContainer();
            IUnityContainer child  = parent.CreateChildContainer();

            DisposableObject spy = new DisposableObject();

            child.RegisterInstance <DisposableObject>(spy);

            parent.Dispose();
            Assert.True(spy.WasDisposed);
        }
Exemplo n.º 24
0
        protected override void Destructor()
        {
            lock (s_Lock)
            {
                base.Destructor();

                DisposableObject.DisposeAndNull(ref m_GraphHost);
                DisposableObject.DisposeAndNull(ref m_DataStore);

                s_Instance = null;
            }
        }
Exemplo n.º 25
0
        protected override Task OnInitializedAsync()
        {
            disposable = DisposableObject.Create(Dispose);

            BlazorDialogManager.ErrorMessages.Subscribe(errorMessage =>
            {
                Message   = errorMessage;
                ShowPopup = true;
            }).DisposeWith(disposable.CompositeDisposable);

            return(base.OnInitializedAsync());
        }
Exemplo n.º 26
0
        protected override void Destructor()
        {
            base.Destructor();

            DisposableObject.DisposeAndNull(ref m_Reader);
            DisposableObject.DisposeAndNull(ref m_Command);

            if (m_Context.Transaction == null)
            {
                m_Context.Connection.Dispose();
            }
        }
Exemplo n.º 27
0
        public void DisposingContainerDisposesSingletons()
        {
            IUnityContainer container = new UnityContainer()
                                        .RegisterType <DisposableObject>(new ContainerControlledLifetimeManager());

            DisposableObject dobj = container.Resolve <DisposableObject>();

            Assert.IsFalse(dobj.WasDisposed);
            container.Dispose();

            Assert.IsTrue(dobj.WasDisposed);
        }
Exemplo n.º 28
0
        public ObjectLifetimeMain()
        {
            UsingKeyword();

            DisposableObject item = new DisposableObject();

            new DisposableObject();

            new GarbageCollection();

            if (item is IDisposable)
                ( item as IDisposable ).Dispose();
        }
        private object GetViewModel([NotNull] Type viewModelType, IObservable <Unit> _destroyObservable = null)
        {
            Contract.Requires(viewModelType != null);
            Contract.Ensures(Contract.Result <object>() != null);

            if (viewModelType.GetInterface("IDisposable") == null)
            {
                var viewModel = _dependencyResolver.GetService(viewModelType);
                if (viewModel == null)
                {
                    throw new InvalidOperationException(
                              "(RoutableViewModelManager.Get<>) Not resolve {0}".StringFormat(viewModelType));
                }

                return(viewModel);
            }

            var     exportFactoryInstantiatorType = typeof(ExportFactoryInstantiator <>).MakeGenericType(viewModelType);
            dynamic exportFactoryInstantiator     = _dependencyResolver.GetService(exportFactoryInstantiatorType);

            if (exportFactoryInstantiator == null)
            {
                throw new InvalidOperationException(
                          "(RoutableViewModelManager.Get<>) Not resolve {0}".StringFormat(viewModelType));
            }

            var disposable = new DisposableObject();

            Action disposeAction = () =>
            {
                exportFactoryInstantiator.DisposeOnDemand();
                disposable.Dispose();
            };

            if (_destroyObservable != null)
            {
                disposable.Add(_destroyObservable.Subscribe(_ => disposeAction()));
            }
            else
            {
                disposable.Add(
                    _screen.Router.NavigationStack.ItemsRemoved.Where(
                        viewModel => object.ReferenceEquals(viewModel, exportFactoryInstantiator.Instance))
                    .Subscribe(viewModel => disposeAction()));
            }

            var resolvedViewModel = exportFactoryInstantiator.Instance;

            return(resolvedViewModel);
        }
        public void TestWeakReferenceCannotBeCreatedFromDisposedReference_NoPriorWeakReference()
        {
            var target    = new DisposableObject();
            var reference = new ReferenceCountedDisposable <DisposableObject>(target);

            var secondReference = reference.TryAddReference();

            Assert.NotNull(secondReference);

            reference.Dispose();

            var weakReference = new ReferenceCountedDisposable <DisposableObject> .WeakReference(reference);

            Assert.Null(weakReference.TryAddReference());
        }
Exemplo n.º 31
0
        public void DisposeInstances_ListWithOneItem_DisposesItem()
        {
            // Arrange
            var disposable = new DisposableObject();

            var disposables = new List <IDisposable> {
                disposable
            };

            // Act
            ScopedLifestyle.DisposeInstances(disposables);

            // Assert
            Assert.AreEqual(1, disposable.DisposeCount);
        }
Exemplo n.º 32
0
        public void ContainerEnsuresObjectsWontBeCollected()
        {
            ILifetimeContainer container = new LifetimeContainer();
            DisposableObject   mdo       = new DisposableObject();
            WeakReference      wref      = new WeakReference(mdo);

            container.Add(mdo);
            mdo = null;
            GC.Collect();

            Assert.AreEqual(1, container.Count);
            mdo = wref.Target as DisposableObject;
            Assert.IsNotNull(mdo);
            Assert.IsFalse(mdo.WasDisposed);
        }
Exemplo n.º 33
0
        public void CanRegisterDefaultInstanceWithoutLifetimeViaGenericMethod()
        {
            DisposableObject o = new DisposableObject();

            IUnityContainer container = new UnityContainer()
                                        .RegisterInstance <object>(o, new ExternallyControlledLifetimeManager());

            object result = container.Resolve <object>();

            Assert.IsNotNull(result);
            Assert.AreSame(o, result);

            container.Dispose();
            Assert.IsFalse(o.WasDisposed);
            GC.KeepAlive(o);
        }
Exemplo n.º 34
0
        public void Verify_VerifyingAScopedInstance_DisposesThatInstance()
        {
            // Arrange
            var disposable = new DisposableObject();

            var scopedLifestyle = new FakeScopedLifestyle(scope: null);

            var container = new Container();

            container.Register <IDisposable>(() => disposable, scopedLifestyle);

            // Act
            container.Verify();

            // Assert
            Assert.IsTrue(disposable.IsDisposedOnce);
        }
Exemplo n.º 35
0
        public Cursor OpenCursor(Query query)
        {
            Cursor result = null;
            var    cnn    = GetConnection();

            try
            {
                result = DoOpenCursor(cnn, null, query);
            }
            catch
            {
                DisposableObject.DisposeAndNull(ref cnn);
                throw;
            }

            return(result);
        }
		/// <summary>
		///		Determine if a <see cref="DisposableObject"/> has been disposed.
		/// </summary>
		/// <param name="disposableObject">
		///		The <see cref="DisposableObject"/> to examine.
		/// </param>
		/// <returns>
		///		<c>true</c>, if the object has been disposed; otherwise, <c>false</c>.
		/// </returns>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="disposableObject"/> is <c>null</c>.
		/// </exception>
		public static bool IsObjectDisposed(DisposableObject disposableObject)
		{
			if (disposableObject == null)
				throw new ArgumentNullException(nameof(disposableObject));

			return disposableObject.IsDisposed;
		}