public void AddDirOnlyAcceptDirectoryOnce()
 {
     AssemblyContainer tested = new AssemblyContainer();
       IPluginDirectory pluginDir = new MockPluginDirectory();
       tested.AddDir(pluginDir);
       DoAssert.Throws<ArgumentException>(() => tested.AddDir(pluginDir));
 }
        private static void UnloadAssemblies(ILogger log, AssemblyContainer assemblyContainer, List <ReloadedAssembly> loadedAssemblies)
        {
            for (int index = loadedAssemblies.Count - 1; index >= 0; index--)
            {
                var loadedAssembly = loadedAssemblies[index];
                var assembly       = loadedAssembly.PackageLoadedAssembly.Assembly;

                // Already unloaded or never loaded?
                if (assembly == null)
                {
                    continue;
                }

                log?.Info($"Unloading assembly {assembly}");

                // Unregisters assemblies that have been registered in Package.Load => Package.LoadAssemblyReferencesForPackage
                AssemblyRegistry.Unregister(assembly);

                // Unload binary serialization
                DataSerializerFactory.UnregisterSerializationAssembly(assembly);

                // Unload assembly
                assemblyContainer.UnloadAssembly(assembly);

                loadedAssembly.PackageLoadedAssembly.Assembly = null;
            }
        }
        private static void LoadAssemblies(ILogger log, AssemblyContainer assemblyContainer, List <ReloadedAssembly> loadedAssemblies, bool newVersion, bool firstTime)
        {
            foreach (var loadedAssembly in loadedAssemblies)
            {
                loadedAssembly.PackageLoadedAssembly.Path = newVersion ? loadedAssembly.NewAssemblyPath : loadedAssembly.OldAssemblyPath;
                Assembly assembly = null;
                try
                {
                    // If first time, load assembly
                    if (firstTime)
                    {
                        loadedAssembly.NewAssembly = assemblyContainer.LoadAssemblyFromPath(loadedAssembly.PackageLoadedAssembly.Path);
                    }

                    // Load assembly
                    assembly = newVersion
                        ? loadedAssembly.NewAssembly
                        : loadedAssembly.OriginalAssembly;

                    log?.Info($"Loading assembly {assembly}");

                    loadedAssembly.PackageLoadedAssembly.Assembly = assembly;

                    // Unregisters assemblies that have been registered in Package.Load => Package.LoadAssemblyReferencesForPackage
                    AssemblyRegistry.Register(assembly, AssemblyCommonCategories.Assets);

                    DataSerializerFactory.RegisterSerializationAssembly(assembly);
                }
                catch (Exception e)
                {
                    log?.Error($"Error loading assembly {assembly?.ToString() ?? Path.GetFileNameWithoutExtension(loadedAssembly.PackageLoadedAssembly.Path)}: ", e);
                }
            }
        }
        public void RemoveDirShouldHandleRemovalOfKnownDirectory()
        {
            AssemblyContainer tested    = new AssemblyContainer();
            IPluginDirectory  pluginDir = new MockPluginDirectory();

            tested.AddDir(pluginDir);
            tested.RemoveDir(pluginDir);
        }
        public void AddDirOnlyAcceptDirectoryOnce()
        {
            AssemblyContainer tested    = new AssemblyContainer();
            IPluginDirectory  pluginDir = new MockPluginDirectory();

            tested.AddDir(pluginDir);
            DoAssert.Throws <ArgumentException>(() => tested.AddDir(pluginDir));
        }
        public static bool RegistrationDetailsPresent(string assemblyPath, bool isWorkflow)
        {
            var assemblyBytes = File.ReadAllBytes(assemblyPath);

            AssemblyContainer container = AssemblyContainer.LoadAssembly(assemblyBytes, isWorkflow, true);

            return(container.PluginDatas.First().CrmPluginRegistrationAttributes.Count > 0);
        }
 public MockAssemblyRepository()
 {
     var container = new AssemblyContainer();
       container.Add(typeof(MockPlugin1).Assembly.Location);
       container.Add(typeof(PluginCreator).Assembly.Location);
       this.repos = container;
       this.Fetched = new Dictionary<string, byte[]>();
 }
        public void FetchShouldReturnExistingAssembly()
        {
            AssemblyContainer tested   = new AssemblyContainer();
            Assembly          assembly = Assembly.GetAssembly(typeof(MockPlugin1));

            tested.Add(assembly.Location);
            byte[] returned = tested.Fetch(assembly.FullName);
            Assert.IsNotNull(returned);
        }
예제 #9
0
        public MockAssemblyRepository()
        {
            var container = new AssemblyContainer();

            container.Add(typeof(MockPlugin1).Assembly.Location);
            container.Add(typeof(PluginCreator).Assembly.Location);
            this.repos   = container;
            this.Fetched = new Dictionary <string, byte[]>();
        }
        public void ShouldLogToWarnWhenTryingToFetchUnknownAssembly()
        {
            var assemblyname         = GetType().Assembly.FullName;
            var pattern              = new Regex(@"^Unable to fetch .+, assembly not known.$");
            AssemblyContainer tested = new AssemblyContainer();
            MockLog           log    = new MockLog(tested);

            tested.Fetch(GetType().Assembly.FullName);
            Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Warn && pattern.IsMatch(x.Message) && x.Message.Contains(assemblyname)));
        }
        public void AddShouldRaiseAssemblyAddedForValidAssembly()
        {
            AssemblyContainer tested = new AssemblyContainer();
            bool raisedAssemblyAdded = false;

            tested.AssemblyAdded += (s, e) => raisedAssemblyAdded = true;
            tested.Add(GetType().Assembly.Location);

            Assert.IsTrue(raisedAssemblyAdded);
        }
예제 #12
0
 public LiveAssemblyReloader(Game game, AssemblyContainer assemblyContainer, List <Assembly> assembliesToUnregister, List <Assembly> assembliesToRegister)
 {
     if (game != null)
     {
         this.entities.AddRange(game.SceneSystem.SceneInstance);
     }
     this.game = game;
     this.assemblyContainer      = assemblyContainer;
     this.assembliesToUnregister = assembliesToUnregister;
     this.assembliesToRegister   = assembliesToRegister;
 }
예제 #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageSession"/> class.
 /// </summary>
 public PackageSession(Package package)
 {
     packages                    = new PackageCollection();
     packagesCopy                = new PackageCollection();
     assemblyContainer           = new AssemblyContainer();
     packages.CollectionChanged += PackagesCollectionChanged;
     if (package != null)
     {
         Packages.Add(package);
     }
 }
예제 #14
0
		public void DoWork()
        {
            WorkerTaskInfo objThreadTaskInfo = new WorkerTaskInfo();
			AssemblyContainer objExecutor = null;
            int intBatchCounter = 0;

            // Create TaskInfo instance for use by each individual Batch
            objThreadTaskInfo = new WorkerTaskInfo();
            // Common to all Batches
            objThreadTaskInfo.MethodInformation = mobjTaskInfo.MethodInformation;
            // Starting Range and per Batch ItemCount
			objThreadTaskInfo.BatchSize = mobjTaskInfo.BatchSize;
			objThreadTaskInfo.BatchInformation.StartOfRange = mobjTaskInfo.BatchInformation.StartOfRange;
            objThreadTaskInfo.BatchInformation.EndOfRange = mobjTaskInfo.BatchInformation.StartOfRange + mobjTaskInfo.BatchSize;

            while (intBatchCounter < mobjTaskInfo.NoOfBatchesRequired)
            {
				// Perform Work
				if (HasStopWorkRequestBeenReceived == true)
				{
					IsBusy = false;
					OnCallback(this, "Thread received Stop request (BatchCounter=" + intBatchCounter.ToString() + ")");
					return;
				}
				// Logging (Optional)
				if (ConfigurationManager.AppSettings.Get("LoggingMode") == "verbose")
				{
					Logging.WriteToLog(this, "Commencing Batch {" + intBatchCounter.ToString() + "}" + " " + "Start of Range = " + mobjTaskInfo.BatchInformation.StartOfRange.ToString());
				}
				try
				{
					// Dynamically Invoke Method for current Batch
					objExecutor = new AssemblyContainer();
                    objExecutor.ExecuteMethod(objThreadTaskInfo);
                    // Prepare to Invoke Method for next Batch
                    objThreadTaskInfo.BatchInformation.StartOfRange += (objThreadTaskInfo.BatchSize + 1); // + 1 assumes a BETWEEN query in SQL
                    objThreadTaskInfo.BatchInformation.EndOfRange = objThreadTaskInfo.BatchInformation.StartOfRange + objThreadTaskInfo.BatchSize;
                    intBatchCounter += 1; // Increment Batch Counter
				}
				catch (Exception excE)
				{
					OnException(this, excE);
					return;
				}
				finally
				{
					//System.Threading.Monitor.Exit(objExecutor);
				}
			}

			// End Work
			IsBusy = false;
			OnCallback(this, "Thread completed its work (BatchCounter=" + intBatchCounter.ToString() + ")");
		}
        public void ShouldLogToInfoWhenAddingAssembly()
        {
            var path = GetType().Assembly.Location;

            AssemblyContainer tested = new AssemblyContainer();
            MockLog           log    = new MockLog(tested);

            tested.Add(path);

            Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Info && x.Message.Contains("Assembly added ") && x.Message.Contains(path)));
        }
        public void ShouldLogToDebugWhenAssemblyIsFetched()
        {
            var assemblyname         = GetType().Assembly.FullName;
            var path                 = GetType().Assembly.Location;
            var pattern              = new Regex(@"^Assembly fetched .+ \(\d+ bytes read from .*\)$");
            AssemblyContainer tested = new AssemblyContainer();
            MockLog           log    = new MockLog(tested);

            tested.Add(path);
            tested.Fetch(assemblyname);
            Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Debug && pattern.IsMatch(x.Message) && x.Message.Contains(path) && x.Message.Contains(assemblyname)));
        }
 public void RemoveHandlesUnknownAssembly()
 {
     try
     {
         AssemblyContainer tested = new AssemblyContainer();
         tested.Remove(GetType().Assembly.Location);
     }
     catch
     {
         Assert.Fail();
     }
 }
예제 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PackageSession"/> class.
        /// </summary>
        public PackageSession(Package package)
        {
            constraintProvider.AddConstraint(PackageStore.Instance.DefaultPackageName, new VersionSpec(PackageStore.Instance.DefaultPackageVersion.ToSemanticVersion()));

            packages                    = new PackageCollection();
            packagesCopy                = new PackageCollection();
            assemblyContainer           = new AssemblyContainer();
            packages.CollectionChanged += PackagesCollectionChanged;
            if (package != null)
            {
                Packages.Add(package);
            }
        }
        public void RemoveShouldRaiseAssemblyRemovedForKnownAssembly()
        {
            AssemblyContainer tested = new AssemblyContainer();

            tested.Add(GetType().Assembly.Location);

            bool raisedAssemblyRemoved = false;

            tested.AssemblyRemoved += (s, e) => raisedAssemblyRemoved = true;
            tested.Remove(GetType().Assembly.Location);

            Assert.IsTrue(raisedAssemblyRemoved);
        }
예제 #20
0
    static void Main(string[] args)
    {
        var assemblyBytes = File.ReadAllBytes(@"C:\dev\Newtonsoft.Json.dll");

        // load an unload the same assembly 5 times
        for (int i = 0; i < 5; i++)
        {
            var assemblyContainer = AssemblyContainer.LoadAssembly(assemblyBytes, true);
            var assemblyName      = assemblyContainer.AssemblyName;
            assemblyContainer.Unload();
        }

        Console.ReadKey();
    }
        public void ShouldLogToInfoWhenAddingDirectory()
        {
            var path          = "mockDir";
            var mockPluginDir = new Mock <IPluginDirectory>();

            mockPluginDir.Setup(x => x.Path).Returns(path);

            AssemblyContainer tested = new AssemblyContainer();
            MockLog           log    = new MockLog(tested);

            tested.AddDir(mockPluginDir.Object);

            Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Info && x.Message.Contains("Added plugin directory ") && x.Message.Contains(path)));
        }
        public void ShouldRaiseAssemblyAddedOnFileFound()
        {
            AssemblyContainer   tested    = new AssemblyContainer();
            MockPluginDirectory pluginDir = new MockPluginDirectory();

            tested.AddDir(pluginDir);

            bool assemblyAddedRaised = false;

            tested.AssemblyAdded += (s, e) => assemblyAddedRaised = true;

            pluginDir.RaiseFileFound(GetType().Assembly.Location);

            Assert.IsTrue(assemblyAddedRaised);
        }
        public void ShouldNotRaiseAssemblyRemovedOnUnknownFileLost()
        {
            AssemblyContainer   tested    = new AssemblyContainer();
            MockPluginDirectory pluginDir = new MockPluginDirectory();

            tested.AddDir(pluginDir);

            bool assemblyRemovedRaised = false;

            tested.AssemblyRemoved += (s, e) => assemblyRemovedRaised = true;

            pluginDir.RaiseFileLost(GetType().Assembly.Location);

            Assert.IsFalse(assemblyRemovedRaised);
        }
예제 #24
0
        private void Init()
        {
            AppDomain.CurrentDomain.AssemblyLoad += (s, e) => Console.WriteLine("{0} loaded {1}", AppDomain.CurrentDomain.FriendlyName, e.LoadedAssembly.FullName);

            Console.WriteLine("Creating plugin repository");
            this.pluginRepository  = new PluginRepository();
            this.assemblyContainer = new AssemblyContainer();
            this.pluginRepository.AddPluginSource(new PluginExtractor(this.assemblyContainer));

            DirectoryInfo pluginDir = new DirectoryInfo(@"..\..\..\Plugin\Bin");

            Console.WriteLine(@"Adding plugins from {0}", pluginDir.FullName);

            directoryWatcher = new PluginDirectory(pluginDir.FullName, true);
            this.assemblyContainer.AddDir(directoryWatcher);
        }
예제 #25
0
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //检查文件是否有变动
            var dt = Directory.GetLastWriteTime(ConfigurationManager.AppSettings["App_Data_Dir"]);

            if (!_lastWriteTime.HasValue)
            {//第一次
                AssemblyContainer.SetInstanceNull();
                CommentsDocContainer.SetInstanceNull();
                WorkingCopy.CopySourceToTarget();
                _lastWriteTime = dt;
            }
            else if (dt > _lastWriteTime.Value)
            {//后续 需要重启website
                File.SetLastWriteTimeUtc(Server.MapPath("~/Global.asax"), DateTime.UtcNow);
            }
        }
        public void AddShouldHandleInvalidFile()
        {
            AssemblyContainer tested = new AssemblyContainer();
              string filename = Guid.NewGuid().ToString() + ".dll";
              using (var output = File.CreateText(filename))
            output.WriteLine("Invalid assembly data");

              try
              {
            var returned = tested.Add(filename);
            Assert.IsFalse(returned);
              }
              finally
              {
            File.Delete(filename);
              }
        }
        public void ShouldForgetLostFile()
        {
            AssemblyContainer   tested    = new AssemblyContainer();
            MockPluginDirectory pluginDir = new MockPluginDirectory();

            tested.AddDir(pluginDir);

            int assemblyRemovedRaised = 0;

            tested.AssemblyRemoved += (s, e) => assemblyRemovedRaised++;

            pluginDir.RaiseFileFound(GetType().Assembly.Location);
            pluginDir.RaiseFileLost(GetType().Assembly.Location);
            pluginDir.RaiseFileLost(GetType().Assembly.Location);

            Assert.AreEqual(1, assemblyRemovedRaised);
        }
예제 #28
0
        public Guid RegisterWorkflowActivities(string file, string solutionName)
        {
            SolutionUniqueName = solutionName;
            var assemblyFilePath = new FileInfo(file);

            if (_ignoredAssemblies.Contains(assemblyFilePath.Name))
            {
                return(Guid.Empty);
            }

            AssemblyContainer assemblyContainer = null;

            try
            {
                //Load the assembly in its own AppDomain to prevent load errors & file locking
                var assemblyBytes = File.ReadAllBytes(file);
                assemblyContainer = AssemblyContainer.LoadAssembly(assemblyBytes, true, true);
                List <PluginData> pluginDatas = assemblyContainer.PluginDatas;

                if (pluginDatas.Count <= 0)
                {
                    return(Guid.Empty);
                }

                var plugin = RegisterAssembly(assemblyFilePath, pluginDatas.First().AssemblyName, pluginDatas.First().CrmPluginRegistrationAttributes);

                if (plugin == null)
                {
                    return(plugin.Id);
                }

                foreach (PluginData pluginData in pluginDatas)
                {
                    RegisterActivities(pluginData.CrmPluginRegistrationAttributes, plugin, pluginData.AssemblyFullName);
                }

                _ctx.SaveChanges();

                return(plugin.Id);
            }
            finally
            {
                assemblyContainer?.Unload();
            }
        }
        public void AddShouldHandleInvalidFile()
        {
            AssemblyContainer tested   = new AssemblyContainer();
            string            filename = Guid.NewGuid().ToString() + ".dll";

            using (var output = File.CreateText(filename))
                output.WriteLine("Invalid assembly data");

            try
            {
                var returned = tested.Add(filename);
                Assert.IsFalse(returned);
            }
            finally
            {
                File.Delete(filename);
            }
        }
        public void AddShouldHandleLockedFile()
        {
            AssemblyContainer tested   = new AssemblyContainer();
            string            filename = Guid.NewGuid().ToString() + ".dll";

            try
            {
                using (var output = File.CreateText(filename))
                {
                    var returned = tested.Add(filename);
                    Assert.IsFalse(returned);
                }
            }
            finally
            {
                File.Delete(filename);
            }
        }
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            AssemblyContainer assemblyContainer = new AssemblyContainer();

              PluginRepository pluginRepository = new PluginRepository();
              pluginRepository.AddPluginSource(new PluginExtractor(assemblyContainer));

              System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
              string pluginDir = settingsReader.GetValue("PluginPath", typeof(string)) as string;
              PluginDirectory pluginDirectory = new PluginDirectory(pluginDir, true);
              assemblyContainer.AddDir(pluginDirectory);

              container.Register(
            Component.For<IPluginRepository>().LifestyleSingleton().Instance(pluginRepository),

            Component.For<IAssemblyRepository>().LifestyleSingleton().Instance(assemblyContainer)
            .OnDestroy(kernel => { assemblyContainer.RemoveDir(pluginDirectory); pluginDirectory.Dispose(); })
              );
        }
예제 #32
0
        public static string AssemblyFullName(string assemblyPath, bool isWorkflow)
        {
            AssemblyContainer assemblyContainer = null;

            try
            {
                string assemblyFolderPath = Path.GetDirectoryName(assemblyPath);

                assemblyContainer = AssemblyContainer.LoadAssembly(File.ReadAllBytes(assemblyPath), isWorkflow, assemblyFolderPath, true);

                List <PluginData> pluginDatas = assemblyContainer.PluginDatas;

                return(pluginDatas.First().AssemblyFullName);
            }
            finally
            {
                assemblyContainer?.Unload();
            }
        }
예제 #33
0
        private static bool RegistrationDetailsPresent(string assemblyPath, bool isWorkflow)
        {
            AssemblyContainer container = null;

            try
            {
                var assemblyBytes = File.ReadAllBytes(assemblyPath);

                string assemblyFolderPath = Path.GetDirectoryName(assemblyPath);

                container = AssemblyContainer.LoadAssembly(assemblyBytes, isWorkflow, assemblyFolderPath, true);

                return(container.PluginDatas.First().CrmPluginRegistrationAttributes.Count > 0);
            }
            finally
            {
                container?.Unload();
            }
        }
        public void RemovedDirDoesNotRaiseEvents()
        {
            AssemblyContainer   tested    = new AssemblyContainer();
            MockPluginDirectory pluginDir = new MockPluginDirectory();

            tested.AddDir(pluginDir);

            int assemblyAddedRaised   = 0;
            int assemblyRemovedRaised = 0;

            tested.AssemblyAdded   += (s, e) => assemblyAddedRaised++;
            tested.AssemblyRemoved += (s, e) => assemblyRemovedRaised++;

            tested.RemoveDir(pluginDir);
            pluginDir.RaiseFileFound(GetType().Assembly.Location);
            pluginDir.RaiseFileLost(GetType().Assembly.Location);

            Assert.AreEqual(0, assemblyAddedRaised);
            Assert.AreEqual(0, assemblyRemovedRaised);
        }
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            AssemblyContainer assemblyContainer = new AssemblyContainer();

            PluginRepository pluginRepository = new PluginRepository();

            pluginRepository.AddPluginSource(new PluginExtractor(assemblyContainer));

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            string          pluginDir       = settingsReader.GetValue("PluginPath", typeof(string)) as string;
            PluginDirectory pluginDirectory = new PluginDirectory(pluginDir, true);

            assemblyContainer.AddDir(pluginDirectory);

            container.Register(
                Component.For <IPluginRepository>().LifestyleSingleton().Instance(pluginRepository),

                Component.For <IAssemblyRepository>().LifestyleSingleton().Instance(assemblyContainer)
                .OnDestroy(kernel => { assemblyContainer.RemoveDir(pluginDirectory); pluginDirectory.Dispose(); })
                );
        }
 public void RemoveDirShouldHandleRemovalOfKnownDirectory()
 {
     AssemblyContainer tested = new AssemblyContainer();
       IPluginDirectory pluginDir = new MockPluginDirectory();
       tested.AddDir(pluginDir);
       tested.RemoveDir(pluginDir);
 }
 public void RemoveHandlesUnknownAssembly()
 {
     try
       {
     AssemblyContainer tested = new AssemblyContainer();
     tested.Remove(GetType().Assembly.Location);
       }
       catch
       {
     Assert.Fail();
       }
 }
 public void AddRequiresArgument()
 {
     AssemblyContainer tested = new AssemblyContainer();
       DoAssert.Throws<ArgumentNullException>(() => tested.Add(null));
 }
 public void ConstructorShouldInitLog()
 {
     ILogWriter tested = new AssemblyContainer();
       Assert.IsNotNull(tested.Log);
 }
 public void FetchShouldReturnExistingAssembly()
 {
     AssemblyContainer tested = new AssemblyContainer();
       Assembly assembly = Assembly.GetAssembly(typeof(MockPlugin1));
       tested.Add(assembly.Location);
       byte[] returned = tested.Fetch(assembly.FullName);
       Assert.IsNotNull(returned);
 }
 public void FetchShuldReturnNullForUnknownAssembly()
 {
     AssemblyContainer tested = new AssemblyContainer();
       byte[] returned = tested.Fetch(Assembly.GetAssembly(typeof(MockPlugin1)).FullName);
       Assert.IsNull(returned);
 }
 public void ShouldLogToDebugWhenAssemblyIsFetched()
 {
     var assemblyname = GetType().Assembly.FullName;
       var path = GetType().Assembly.Location;
       var pattern = new Regex(@"^Assembly fetched .+ \(\d+ bytes read from .*\)$");
       AssemblyContainer tested = new AssemblyContainer();
       MockLog log = new MockLog(tested);
       tested.Add(path);
       tested.Fetch(assemblyname);
       Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Debug && pattern.IsMatch(x.Message) && x.Message.Contains(path) && x.Message.Contains(assemblyname)));
 }
 public void ShouldLogToErrorWhenAllKnownPathsToAssemblyDoesNotExist()
 {
     var assemblyname = GetType().Assembly.FullName;
       var path = Guid.NewGuid().ToString() + ".dll";
       var pattern = new Regex(@"^Unable to fetch .+, file not found in these locations:$");
       try
       {
     File.Copy(GetType().Assembly.Location, path);
     AssemblyContainer tested = new AssemblyContainer();
     MockLog log = new MockLog(tested);
     tested.Add(path);
     File.Delete(path);
     tested.Fetch(assemblyname);
     Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Error && pattern.IsMatch(x.Message) && x.Message.Contains(assemblyname)));
     Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Error && x.Message.StartsWith("  --> ") && x.Message.EndsWith(path)));
       }
       finally
       {
     File.Delete(path);
       }
 }
        public void ShouldLogToInfoWhenRemovingDirectory()
        {
            var path = "mockDir";
              var mockPluginDir = new Mock<IPluginDirectory>();
              mockPluginDir.Setup(x => x.Path).Returns(path);

              AssemblyContainer tested = new AssemblyContainer();
              MockLog log = new MockLog(tested);
              tested.AddDir(mockPluginDir.Object);
              tested.RemoveDir(mockPluginDir.Object);

              Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Info && x.Message.Contains("Removed plugin directory ") && x.Message.Contains(path)));
        }
 public void ShouldLogToWarnWhenTryingToFetchUnknownAssembly()
 {
     var assemblyname = GetType().Assembly.FullName;
       var pattern = new Regex(@"^Unable to fetch .+, assembly not known.$");
       AssemblyContainer tested = new AssemblyContainer();
       MockLog log = new MockLog(tested);
       tested.Fetch(GetType().Assembly.FullName);
       Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Warn && pattern.IsMatch(x.Message) && x.Message.Contains(assemblyname)));
 }
 public void AddShouldHandleLockedFile()
 {
     AssemblyContainer tested = new AssemblyContainer();
       string filename = Guid.NewGuid().ToString() + ".dll";
       try
       {
     using (var output = File.CreateText(filename))
     {
       var returned = tested.Add(filename);
       Assert.IsFalse(returned);
     }
       }
       finally
       {
     File.Delete(filename);
       }
 }
        public void ShouldRaiseAssemblyRemovedOnKnownFileLost()
        {
            AssemblyContainer tested = new AssemblyContainer();
              MockPluginDirectory pluginDir = new MockPluginDirectory();
              tested.AddDir(pluginDir);

              bool assemblyRemovedRaised = false;
              tested.AssemblyRemoved += (s, e) => assemblyRemovedRaised = true;

              pluginDir.RaiseFileFound(GetType().Assembly.Location);
              pluginDir.RaiseFileLost(GetType().Assembly.Location);

              Assert.IsTrue(assemblyRemovedRaised);
        }
 public void AddRequiresExistingFile()
 {
     AssemblyContainer tested = new AssemblyContainer();
       DoAssert.Throws<FileNotFoundException>(() => tested.Add(@"c:\" + Guid.NewGuid().ToString()));
 }
 public void RemoveDirRequiresKnownDirectory()
 {
     AssemblyContainer tested = new AssemblyContainer();
       IPluginDirectory pluginDir = new MockPluginDirectory();
       DoAssert.Throws<ArgumentException>(() => tested.RemoveDir(pluginDir));
 }
        public void RemovedDirDoesNotRaiseEvents()
        {
            AssemblyContainer tested = new AssemblyContainer();
              MockPluginDirectory pluginDir = new MockPluginDirectory();
              tested.AddDir(pluginDir);

              int assemblyAddedRaised = 0;
              int assemblyRemovedRaised = 0;
              tested.AssemblyAdded += (s, e) => assemblyAddedRaised++;
              tested.AssemblyRemoved += (s, e) => assemblyRemovedRaised++;

              tested.RemoveDir(pluginDir);
              pluginDir.RaiseFileFound(GetType().Assembly.Location);
              pluginDir.RaiseFileLost(GetType().Assembly.Location);

              Assert.AreEqual(0, assemblyAddedRaised);
              Assert.AreEqual(0, assemblyRemovedRaised);
        }
 public void ShouldImplementILogWriter()
 {
     AssemblyContainer tested = new AssemblyContainer();
       Assert.IsInstanceOfType(tested, typeof(ILogWriter));
 }
        public void FetchShouldReturnNullForUnreadableAssembly()
        {
            AssemblyContainer tested = new AssemblyContainer();
              Assembly assembly = Assembly.GetAssembly(typeof(MockPlugin1));

              string location = assembly.Location.Replace(".dll", ".mock.dll");
              File.Copy(assembly.Location, location, true);

              try
              {
            tested.Add(location);

            using (Stream locking = FileExtension.WaitAndOpen(location, FileMode.Open, FileAccess.Read, FileShare.None, TimeSpan.FromSeconds(5)))
            {
              byte[] returned = tested.Fetch(Assembly.GetAssembly(typeof(MockPlugin1)).FullName);
              Assert.IsNull(returned);
            }
              }
              finally
              {
            File.Delete(location);
              }
        }
        public void ShouldForgetLostFile()
        {
            AssemblyContainer tested = new AssemblyContainer();
              MockPluginDirectory pluginDir = new MockPluginDirectory();
              tested.AddDir(pluginDir);

              int assemblyRemovedRaised = 0;
              tested.AssemblyRemoved += (s, e) => assemblyRemovedRaised++;

              pluginDir.RaiseFileFound(GetType().Assembly.Location);
              pluginDir.RaiseFileLost(GetType().Assembly.Location);
              pluginDir.RaiseFileLost(GetType().Assembly.Location);

              Assert.AreEqual(1, assemblyRemovedRaised);
        }
 public void FetchShouldLogExceptionsAsErrors()
 {
     var assemblyname = GetType().Assembly.FullName;
       var path = Guid.NewGuid().ToString() + ".dll";
       var pattern = new Regex(@"^Exception while fetching .+ (.+) .*$");
       try
       {
     File.Copy(GetType().Assembly.Location, path);
     AssemblyContainer tested = new AssemblyContainer();
     MockLog log = new MockLog(tested);
     tested.Add(path);
     using (var file = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None))
     {
       tested.Fetch(assemblyname);
       Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Error && pattern.IsMatch(x.Message) && x.Message.Contains(assemblyname) && x.Message.Contains(path)));
     }
       }
       finally
       {
     File.Delete(path);
       }
 }
        public void RemoveShouldRaiseAssemblyRemovedForKnownAssembly()
        {
            AssemblyContainer tested = new AssemblyContainer();
              tested.Add(GetType().Assembly.Location);

              bool raisedAssemblyRemoved = false;
              tested.AssemblyRemoved += (s, e) => raisedAssemblyRemoved = true;
              tested.Remove(GetType().Assembly.Location);

              Assert.IsTrue(raisedAssemblyRemoved);
        }
        public void AddShouldRaiseAssemblyAddedForValidAssembly()
        {
            AssemblyContainer tested = new AssemblyContainer();
              bool raisedAssemblyAdded = false;

              tested.AssemblyAdded += (s, e) => raisedAssemblyAdded = true;
              tested.Add(GetType().Assembly.Location);

              Assert.IsTrue(raisedAssemblyAdded);
        }
 public void AddDirAcceptsValidArgument()
 {
     AssemblyContainer tested = new AssemblyContainer();
       IPluginDirectory pluginDir = new MockPluginDirectory();
       tested.AddDir(pluginDir);
 }
        public void ShouldLogToInfoWhenRemovingAssembly()
        {
            var path = GetType().Assembly.Location;

              AssemblyContainer tested = new AssemblyContainer();
              MockLog log = new MockLog(tested);
              tested.Add(path);
              tested.Remove(path);

              Assert.IsTrue(log.Any(x => x.Level == MockLog.Level.Info && x.Message.Contains("Assembly removed ") && x.Message.Contains(path)));
        }
 public void AddFailsIfAddingSameAssemblyTwice()
 {
     AssemblyContainer tested = new AssemblyContainer();
       tested.Add(GetType().Assembly.Location);
       DoAssert.Throws<ArgumentException>(() => tested.Add(GetType().Assembly.Location));
 }