public static byte[] ToBytes(string filePath) { var directory = AssemblyHelpers.GetDirectoryForAssembyl(Assembly.GetExecutingAssembly()); var file = File.ReadAllBytes(directory + filePath); return(file); }
/// <summary> /// Gets the type of the email view model by. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public BaseEmailServiceModel GetEmailViewModelByType(string type) { var typeName = type + "EmailServiceModel"; var concreteObject = AssemblyHelpers.GetInstanceOf <BaseEmailServiceModel>(typeName); return(concreteObject); }
private static async Task Main() { var commandFactory = new DbCommandFactory($"\"Npgsql-Test-{Guid.NewGuid():N}\""); var commandExecutor = new NpgsqlCommandExecutor(); var cts = new CancellationTokenSource(); // Use the connection type that is loaded by the runtime through the typical loading algorithm using (var connection = OpenConnection(typeof(NpgsqlConnection))) { await RelationalDatabaseTestHarness.RunAllAsync <NpgsqlCommand>(connection, commandFactory, commandExecutor, cts.Token); } // Test the result when the ADO.NET provider assembly is loaded through Assembly.LoadFile // On .NET Core this results in a new assembly being loaded whose types are not considered the same // as the types loaded through the default loading mechanism, potentially causing type casting issues in CallSite instrumentation var loadFileType = AssemblyHelpers.LoadFileAndRetrieveType(typeof(NpgsqlConnection)); using (var connection = OpenConnection(loadFileType)) { // Do not use the strongly typed SqlCommandExecutor because the type casts will fail await RelationalDatabaseTestHarness.RunBaseClassesAsync(connection, commandFactory, cts.Token); } // allow time to flush await Task.Delay(2000, cts.Token); }
private List <Image> GetSampleImage() { List <Image> images = new List <Image>(); string directory = AssemblyHelpers.GetDirectoryFoeAssembly(Assembly.GetExecutingAssembly()); var fileCat = File.ReadAllBytes(directory + "/Content/images/crazyCat.jpg"); var fileHedgehog = File.ReadAllBytes(directory + "/Content/images/hedgehog.jpg"); Image catImg = new Image { Content = fileCat, FileExtension = "jpg" }; Image HedgehogImg = new Image { Content = fileHedgehog, FileExtension = "jpg" }; images.Add(catImg); images.Add(HedgehogImg); return(images); }
/// <summary> /// Initializes an instance of the starter form. /// The starter form shows a splashscreen and initializes the plugin infrastructure. /// </summary> public StarterForm() : base() { InitializeComponent(); largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap()); largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap()); smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap()); smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap()); Text = "HeuristicLab " + AssemblyHelpers.GetFileVersion(GetType().Assembly); string pluginPath = Path.GetFullPath(Application.StartupPath); pluginManager = new PluginManager(pluginPath); splashScreen = new SplashScreen(pluginManager, 1000); splashScreen.VisibleChanged += new EventHandler(splashScreen_VisibleChanged); splashScreen.Show(this, "Loading HeuristicLab..."); if (CheckSavedStarterFormSettings()) { Location = Settings.Default.StarterFormLocation; Size = Settings.Default.StarterFormSize; WindowState = Settings.Default.StarterFormWindowState; } pluginManager.DiscoverAndCheckPlugins(); UpdateApplicationsList(); CheckUpdatesAvailableAsync(); }
/// <summary> /// Loads the test suite for this run from a pre-constructed TestSuite. /// </summary> /// <param name="suite">The test suite to finish loading</param> /// <param name="continuation">The function to call after the suite is loaded</param> /// <param name="assemblyDirectory">The folder containing the test assemblies</param> public virtual void LoadTestSuite(TestSuite suite, Action <TestSuite, TestModuleData> continuation, string assemblyDirectory) { #if !WIN8 // Copy the parameters from the suite into our current cache of parameters. // This is useful for parameters that are used much earlier than normal // in the pipeline, like TestExplorationSeed. foreach (var kvp in suite.Parameters) { this.Parameters[kvp.Key] = kvp.Value; } List <Assembly> assemblies = new List <Assembly>(); foreach (string asm in suite.Assemblies) { string fullPath = Path.Combine(assemblyDirectory, asm + ".dll"); #if !SILVERLIGHT var assembly = AssemblyHelpers.LoadAssembly(fullPath, assemblyDirectory); assemblies.Add(assembly); #endif } var module = this.FindTestModule(assemblies); continuation(suite, module); #else throw new NotImplementedException("TODO: Win8 version needs to work without loading assemblies"); #endif }
private static IEnumerable <Type> GetImportableTypes(string[] assemblyNames, Predicate <Type> filter) { var assemblies = assemblyNames.Select(assemblyName => Assembly.Load(AssemblyHelpers.GetFullAssemblyName(assemblyName))); var activeFilter = filter ?? defaultFilter; return(assemblies.SelectMany(assembly => assembly.GetTypes().Where(type => type.IsImportable() && activeFilter(type)))); }
public void ServerWrapperConstructorTest() { Console.WriteLine(Directory.GetCurrentDirectory()); FileInfo _defaultConfig = new FileInfo(@"Plugin\DemoConfiguration\DefaultConfig.xml"); Assert.IsTrue(_defaultConfig.Exists); FileInfo _oses = new FileInfo(@"Plugin\DemoConfiguration\BoilerExample.oses"); Assert.IsTrue(_oses.Exists); FileInfo _uasconfig = new FileInfo(@"Plugin\DemoConfiguration\BoilerExample.uasconfig"); Assert.IsTrue(_uasconfig.Exists); Assembly _pluginAssembly; IConfiguration _serverConfiguration; AssemblyHelpers.CreateInstance(@"CAS.CommServer.UA.ConfigurationEditor.ServerConfiguration.dll", out _pluginAssembly, out _serverConfiguration); Assert.AreEqual <string>("CAS.UAServer.Configuration.uasconfig", _serverConfiguration.DefaultFileName); bool _configurationChanged = false; _serverConfiguration.OnModified += (x, y) => _configurationChanged = y.ConfigurationFileChanged; _serverConfiguration.CreateDefaultConfiguration(); Assert.IsTrue(_configurationChanged); _configurationChanged = false; Mock <ISolutionDirectoryPathManagement> _directory = new Mock <ISolutionDirectoryPathManagement>(); _directory.SetupGet(x => x.BaseDirectory).Returns(Directory.GetCurrentDirectory()); ServerWrapper _sw = new ServerWrapper(_serverConfiguration, _pluginAssembly, new GraphicalUserInterface(), _directory.Object, @"Plugin\DemoConfiguration\BoilerExample.uasconfig"); Assert.IsNotNull(_sw); Assert.IsTrue(_configurationChanged); }
private byte[] ConvertImageToBytes(string filePath) { var directory = AssemblyHelpers.GetDirectoryForAssembyl(Assembly.GetExecutingAssembly()); var file = File.ReadAllBytes(directory + filePath); return(file); }
/// <summary> /// Generates an assembly that contains the object layer types for the given EntityModelSchema /// </summary> /// <param name="workspace">test workspace under construction</param> /// <param name="schema">The schema under test</param> /// <returns>An assembly that contains the object layer types for the given EntityModelSchema</returns> private Assembly GenerateObjectLayer(ODataTestWorkspace workspace, EntityModelSchema schema) { CodeCompileUnit objectLayerCompileUnit = new CodeCompileUnit(); this.ObjectLayerCodeGenerator.GenerateObjectLayer(objectLayerCompileUnit, schema); string objectLayerCode; using (var writer = new StringWriter(CultureInfo.InvariantCulture)) { this.Language.CreateCodeGenerator().GenerateCodeFromCompileUnit(objectLayerCompileUnit, writer, null); objectLayerCode = writer.ToString(); } string outputFilePath = Guid.NewGuid().ToString(); #if SILVERLIGHT outputFilePath = String.Format("{0}Assembly.dll", outputFilePath); return(typeof(DefaultNamespace.Phone).Assembly); #else outputFilePath = outputFilePath + ".dll"; this.Language.CompileAssemblyFromSource(outputFilePath, new[] { objectLayerCode }, referenceAssemblies); var assembly = AssemblyHelpers.LoadAssembly(outputFilePath, referenceAssemblies); return(assembly); #endif }
public void WriteResourceToFile_ExecutionTest() { //arrange string testFilename = $"{Environment.CurrentDirectory}\\WriteResourceToFile_ExecutionTest.txt"; string assemblyName = Assembly.GetExecutingAssembly().GetName().Name; string resourceName = $"{assemblyName}.Resources.TextFileTest.txt"; int fileLen = 0; bool isFileCreated = false; if (File.Exists(testFilename)) { File.Delete(testFilename); } //act AssemblyHelpers.WriteResourceToFile(resourceName, testFilename); isFileCreated = File.Exists(testFilename); if (isFileCreated) { fileLen = File.ReadAllText(testFilename).Length; } //assert Assert.AreEqual(true, (isFileCreated && fileLen > 0)); }
public void GetResourceStream_ExecutionTest() { //arrange string assemblyName = Assembly.GetExecutingAssembly().GetName().Name; string resourceName = $"{assemblyName}.Resources.TextFileTest.txt"; string result = ""; //bool isStreamNull; Stream resourceStream; //act resourceStream = AssemblyHelpers.GetResourceStream(resourceName); //if (resourceStream == null) isStreamNull = true; using (StreamReader reader = new StreamReader(resourceStream)) { result = reader.ReadToEnd(); } string expectedText = ""; using (StreamReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))) { expectedText = reader.ReadToEnd(); } //assert Assert.AreEqual(expectedText, result); }
public ExportedTypeObject(FileStream fs, PEReader pe, MetadataReader mr, ExportedType exportedType, ResolveAssemblyDelegate resolveAssembly) : base(fs, pe, mr, resolveAssembly) { _exportedType = exportedType; AssemblyForwardedTo = _resolveAssembly(ToAssemblyName(AssemblyHelpers.GetAssemblyReferenceForExportedType(_metaReader, exportedType))); }
public void Container_should_ignore_specified_assemblies() { // Given var syntaxTree = CSharpSyntaxTree.ParseText( "public interface IWillNotBeResolved { int i { get; set; } }" + "public class WillNotBeResolved : IWillNotBeResolved { public int i { get; set; } }"); var mscorlib = MetadataReference.CreateFromFile(typeof(object).GetAssembly().Location); var compilation = CSharpCompilation.Create("MyCompilation", new[] { syntaxTree }, new[] { mscorlib }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); Assembly ass; using (var memoryStream = new MemoryStream()) { var emitResult = compilation.Emit(memoryStream); Assert.True(emitResult.Success, "Compilation failed:" + Environment.NewLine + " " + string.Join(Environment.NewLine + " ", emitResult.Diagnostics)); ass = AssemblyHelpers.Load(memoryStream); } // When this.bootstrapper.Initialise(); // Then Assert.Throws <TinyIoCResolutionException>( () => this.bootstrapper.Container.Resolve(ass.GetType("IWillNotBeResolved"))); }
public void KeyExistsAppConfiguration() { // key exists Assert.IsTrue(AssemblyHelpers.KeyExists("SortDirection")); // key does not exists Assert.IsFalse(AssemblyHelpers.KeyExists("SortDire")); }
private void SeedCountries(FootballDbContext context) { if (context.Countries.Any()) { return; } var directory = AssemblyHelpers.GetDirectoryForAssembly(Assembly.GetExecutingAssembly()); var file = directory + "/Files/countries.txt"; using (var reader = new StreamReader(file)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); var countryAndCode = line.Split(';'); var country = countryAndCode[0]; context.Countries.Add(new Country() { Name = country }); } } context.SaveChanges(); }
protected JObject GetTemplateResponse(IDataLakeConnectionConfig dataLakeConnectionConfig, object parameters, Microsoft.Azure.WebJobs.ExecutionContext context) { var assemblyInfo = AssemblyHelpers.GetAssemblyVersionInfoJson(); var responseJson = new JObject(); responseJson.Add("invocationId", context.InvocationId); if (assemblyInfo.HasValues) { responseJson.Add("debugInfo", assemblyInfo); } if (dataLakeConnectionConfig.BaseUrl != null) { responseJson.Add("storageContainerUrl", dataLakeConnectionConfig.BaseUrl); } if (dataLakeConnectionConfig is DataLakeUserServicePrincipalConnectionConfig config) { responseJson.Add("clientId", config.ServicePrincipalClientId); } responseJson.Add("authType", dataLakeConnectionConfig.AuthType.ToString()); var parametersJson = JObject.FromObject(parameters); responseJson.Add("parameters", parametersJson); return(responseJson); }
private static string?GetFileName(IAssemblyReference reference, IModule parent, InputAssembliesGroup input, NuGetFramework framework) { var extensions = reference.IsWindowsRuntime ? new[] { ".winmd", ".dll" } : new[] { ".exe", ".dll" }; if (reference.IsWindowsRuntime) { return(AssemblyHelpers.FindWindowsMetadataFile(reference.Name, reference.Version)); } string?file; if (reference.Name == "mscorlib") { file = GetCorlib(reference); if (!string.IsNullOrWhiteSpace(file)) { return(file); } } file = FindInParentDirectory(reference, parent, extensions); if (!string.IsNullOrWhiteSpace(file)) { return(file); } file = SearchDirectories(reference, input, extensions); return(!string.IsNullOrWhiteSpace(file) ? file : SearchNugetFrameworkDirectories(reference, extensions, framework)); }
protected void Application_Start() { LogProvider.LogFactory = new NLogFactory(); Logger.Log = LogProvider.LogFactory.GetLogger(AssemblyHelpers.GetAssemblyName()); ModelBinders.Binders.DefaultBinder = new QpModelBinder(); RegisterRoutes(RouteTable.Routes); }
public void Should_ReturnCorrectProtocolStartupOptions_When_OptionsAreSet() { var factory = new StartupOptionsFactory(Guid.NewGuid(), null, null); var options = factory.CreateStartupOptions(new ProtocolOptions().SetNoCompact(true).SetCompression(CompressionType.Snappy)); Assert.AreEqual(6, options.Count); Assert.AreEqual("snappy", options["COMPRESSION"]); Assert.AreEqual("true", options["NO_COMPACT"]); var driverName = options["DRIVER_NAME"]; Assert.True(driverName.Contains("DataStax") && driverName.Contains("C# Driver"), driverName); Assert.AreEqual("3.0.0", options["CQL_VERSION"]); var assemblyVersion = AssemblyHelpers.GetAssembly(typeof(Cluster)).GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion; Assert.AreEqual(assemblyVersion, options["DRIVER_VERSION"]); var indexOfVersionSuffix = assemblyVersion.IndexOf('-'); var versionPrefix = indexOfVersionSuffix == -1 ? assemblyVersion : assemblyVersion.Substring(0, indexOfVersionSuffix); var version = Version.Parse(versionPrefix); Assert.Greater(version, new Version(1, 0)); //// commented this so it doesn't break when version is bumped, tested this with and without suffix //// with suffix //Assert.AreEqual("3.8.0", versionPrefix); //Assert.AreEqual("3.8.0-alpha2", assemblyVersion); //// //// without suffix // Assert.AreEqual("3.8.0", versionPrefix); // Assert.AreEqual("3.8.0", assemblyVersion); }
public void Should_ReturnCorrectDseSpecificStartupOptions_When_OptionsAreSet() { var clusterId = Guid.NewGuid(); var appName = "app123"; var appVersion = "1.2.0"; var factory = new StartupOptionsFactory(clusterId, appVersion, appName); var options = factory.CreateStartupOptions(new ProtocolOptions().SetNoCompact(true).SetCompression(CompressionType.Snappy)); Assert.AreEqual(8, options.Count); Assert.AreEqual("snappy", options["COMPRESSION"]); Assert.AreEqual("true", options["NO_COMPACT"]); var driverName = options["DRIVER_NAME"]; Assert.True(driverName.Contains("DataStax") && driverName.Contains("C# Driver"), driverName); Assert.AreEqual("3.0.0", options["CQL_VERSION"]); var assemblyVersion = AssemblyHelpers.GetAssembly(typeof(Cluster)).GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion; Assert.AreEqual(assemblyVersion, options["DRIVER_VERSION"]); var indexOfVersionSuffix = assemblyVersion.IndexOf('-'); var versionPrefix = indexOfVersionSuffix == -1 ? assemblyVersion : assemblyVersion.Substring(0, indexOfVersionSuffix); var version = Version.Parse(versionPrefix); Assert.Greater(version, new Version(1, 0)); Assert.AreEqual(appName, options["APPLICATION_NAME"]); Assert.AreEqual(appVersion, options["APPLICATION_VERSION"]); Assert.AreEqual(clusterId.ToString(), options["CLIENT_ID"]); }
/// <summary> /// Registers NLog extensions from the assembly type name /// </summary> public static ISetupExtensionsBuilder RegisterAssembly(this ISetupExtensionsBuilder setupBuilder, string assemblyName) { Assembly assembly = AssemblyHelpers.LoadFromName(assemblyName); ConfigurationItemFactory.Default.RegisterItemsFromAssembly(assembly); return(setupBuilder); }
public PluginUpdaterForm(PluginManager pluginManager) : base() { InitializeComponent(); Text = "HeuristicLab Plugin Manager " + AssemblyHelpers.GetFileVersion(GetType().Assembly); pluginManager.PluginLoaded += pluginManager_PluginLoaded; pluginManager.PluginUnloaded += pluginManager_PluginUnloaded; pluginManager.Initializing += pluginManager_Initializing; pluginManager.Initialized += pluginManager_Initialized; pluginDir = Application.StartupPath; installationManager = new InstallationManager(pluginDir); installationManager.PluginInstalled += new EventHandler <PluginInfrastructureEventArgs>(installationManager_PluginInstalled); installationManager.PluginRemoved += new EventHandler <PluginInfrastructureEventArgs>(installationManager_PluginRemoved); installationManager.PluginUpdated += new EventHandler <PluginInfrastructureEventArgs>(installationManager_PluginUpdated); installationManager.PreInstallPlugin += new EventHandler <PluginInfrastructureCancelEventArgs>(installationManager_PreInstallPlugin); installationManager.PreRemovePlugin += new EventHandler <PluginInfrastructureCancelEventArgs>(installationManager_PreRemovePlugin); installationManager.PreUpdatePlugin += new EventHandler <PluginInfrastructureCancelEventArgs>(installationManager_PreUpdatePlugin); this.pluginManager = pluginManager; updatePluginsBackgroundWorker = new BackgroundWorker(); updatePluginsBackgroundWorker.DoWork += new DoWorkEventHandler(updatePluginsBackgroundWorker_DoWork); updatePluginsBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(updatePluginsBackgroundWorker_RunWorkerCompleted); }
private static async Task Main() { var commandFactory = new DbCommandFactory($"[Microsoft-Data-SqlClient-Test-{Guid.NewGuid():N}]"); var commandExecutor = new MicrosoftSqlCommandExecutor(); var cts = new CancellationTokenSource(); using (var connection = OpenConnection(typeof(SqlConnection))) { await RelationalDatabaseTestHarness.RunAllAsync <SqlCommand>(connection, commandFactory, commandExecutor, cts.Token); } // Version 4.0.0 causes a hard crash #if !SQLCLIENT_4 // Test the result when the ADO.NET provider assembly is loaded through Assembly.LoadFile // On .NET Core this results in a new assembly being loaded whose types are not considered the same // as the types loaded through the default loading mechanism, potentially causing type casting issues in CallSite instrumentation var loadFileType = AssemblyHelpers.LoadFileAndRetrieveType(typeof(SqlConnection)); using (var connection = OpenConnection(loadFileType)) { // Do not use the strongly typed SqlCommandExecutor because the type casts will fail await RelationalDatabaseTestHarness.RunBaseClassesAsync(connection, commandFactory, cts.Token); } #endif // allow time to flush await Task.Delay(2000, cts.Token); }
/// <summary> /// External modules (found in external DLL assembies) can provide a class that inherits from CmsModuleInfo to provide information on /// the module. /// </summary> /// <returns></returns> public static CmsModuleInfo[] getAllModuleInfos() { string cacheKey = "CmsModuleUtils.getAllModuleInfos()"; if (PerRequestCache.CacheContains(cacheKey)) { return((CmsModuleInfo[])PerRequestCache.GetFromCache(cacheKey, new CmsModuleInfo[0])); } List <CmsModuleInfo> ret = new List <CmsModuleInfo>(); Type[] moduleInfoTypes = AssemblyHelpers.LoadAllAssembliesAndGetAllSubclassesOf(typeof(CmsModuleInfo)); foreach (Type modInfoType in moduleInfoTypes) { try { CmsModuleInfo info = (CmsModuleInfo)modInfoType.Assembly.CreateInstance(modInfoType.FullName); ret.Add(info); } catch { Console.Write("Error: could not load module info " + modInfoType.FullName); } } // foreach CmsModuleInfo[] arr = ret.ToArray(); PerRequestCache.AddToCache(cacheKey, arr); return(arr); }
public void MTConnectDevices_Data_HasCorrectNumberOfDevices() { var responseFilePath = AssemblyHelpers.AssemblyDirectory(Assembly.GetExecutingAssembly(), "TestData", "MTConnectDevices.xml"); var response = XDocument.Load(responseFilePath); var devices = new MTConnectDevices(response); Assert.AreEqual(8, devices.Data.Devices.Length); }
public void MTConnectDevices_Data_HasCorrectHeaderVersion() { var responseFilePath = AssemblyHelpers.AssemblyDirectory(Assembly.GetExecutingAssembly(), "TestData", "MTConnectDevices.xml"); var response = XDocument.Load(responseFilePath); var devices = new MTConnectDevices(response); Assert.AreEqual("1.4.0.10", devices.Data.Header.version); }
public DriverInfo GetInformation(IInternalCluster cluster, IInternalSession session) { return(new DriverInfo { DriverName = AssemblyHelpers.GetAssemblyTitle(typeof(DriverInfoProvider)), DriverVersion = AssemblyHelpers.GetAssemblyInformationalVersion(typeof(DriverInfoProvider)) }); }
public DeclaredTypeObject(FileStream fs, PEReader pe, MetadataReader mr, TypeDefinition typeDef) : base(fs, pe, mr, null) { _typeDef = typeDef; Name = AssemblyHelpers.GetTypeName(_metaReader, typeDef); IsPublic = AssemblyHelpers.IsVisible(_metaReader, typeDef); }
public static List <Contact> GetContacts() { DataTable dt = ContactRepository.GetContactsFromDatabase(); List <Contact> contacts = new List <Contact>(); contacts = AssemblyHelpers.ConvertDataTable <Contact>(dt); return(contacts); }