/// <summary> /// This method will return the data type descriptor for the given data type id. /// If the data type descriptor has not yet been created (file not existing) and /// the <paramref name="allowDataTypeCreation"/> is set to true, /// this method will try getting it through the <see cref="Composite.Data.DynamicTypes.Foundation.ReflectionBasedDescriptorBuilder"/> /// that will try locating the type from the data type id using refelction /// going through know assemblies. /// </summary> /// <param name="dataTypeId">The id of the data type.</param> /// <param name="allowDataTypeCreation"> /// If this is true and the data type descriptor does not exists, it will try to /// be created. /// </param> /// <returns></returns> public static DataTypeDescriptor GetDataTypeDescriptor(Guid dataTypeId, bool allowDataTypeCreation = false) { Initialize(); DataTypeDescriptor dataTypeDescriptor; _dataTypeDescriptorCache.TryGetValue(dataTypeId, out dataTypeDescriptor); if (dataTypeDescriptor != null) { return(dataTypeDescriptor); } if (!allowDataTypeCreation) { return(null); } foreach (Assembly assembly in AssemblyFacade.GetLoadedAssembliesFromBin()) { if (!AssemblyFacade.AssemblyPotentiallyUsesType(assembly, typeof(IData))) { // Ignoring assemblies that aren't referencing Composite.dll continue; } Type[] types; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { throw new InvalidOperationException($"Failed to get types from assembly '{assembly.FullName}'", ex); } foreach (Type type in types) { if (type.GetInterfaces().Contains(typeof(IData))) { ImmutableTypeIdAttribute attribute = type.GetCustomAttributes(false).OfType <ImmutableTypeIdAttribute>().SingleOrDefault(); if (attribute == null || attribute.ImmutableTypeId != dataTypeId) { continue; } DataTypeDescriptor newDataTypeDescriptor = ReflectionBasedDescriptorBuilder.Build(type); PersistMetaData(newDataTypeDescriptor); return(newDataTypeDescriptor); } } } Log.LogError(LogTitle, $"No data type found with the given data type id '{dataTypeId}'"); return(null); }
public OperatingSystemFacade() { Assembly = new AssemblyFacade(); Dialog = new DialogFacade(); Environment = new Environment(); File = new FileFacade(); MemoryMappedFiles = new MemoryMappedFileFactory(); ProcessLocator = new ProcessLocator(); ProcessStarter = new ProcessStarter(); Registry = new Registry(); }
public OperatingSystemFacade() { Assembly = new AssemblyFacade(); Dialog = new DialogFacade(); Directory = new DirectoryFacade(); Environment = new Environment(); File = new FileFacade(); MemoryMappedFiles = new MemoryMappedFileFactory(); ProcessLocator = new ProcessLocator(); ProcessStarter = new ProcessStarter(); Registry = new Registry(); }
private string GetSikuliPath() { var assemblyPath = new AssemblyFacade().GetAssemblyDirectory(); string sikulixDir = Path.Combine(assemblyPath, "sikulix"); if (Directory.Exists(sikulixDir)) { return(Path.Combine(sikulixDir, "sikulix.jar")); } throw new FileNotFoundException("sikulix.jar not found in the solution. Please install the Bellatrix.ImageRecognition.SikuliX NuGet package."); }
/// <exclude /> public static IEnumerable <string> GetReferencableAssemblies() { string path = Path.GetDirectoryName(typeof(String).Assembly.Location); foreach (string file in Directory.GetFiles(path, "System*.dll")) { yield return(file); } foreach (string file in AssemblyFacade.GetAssembliesFromBin(true)) { yield return(file); } }
public void TrackTestExecution(string projectTrackInfo) { bool isDebug = IsDebugRun(); try { if (!isDebug) { projectTrackInfo = $"{projectTrackInfo} Framework"; var assemblyFacade = new AssemblyFacade(); var callingAssemblies = assemblyFacade.GetAssembliesCallChain(); var testProjectAssembly = callingAssemblies[3]; if (callingAssemblies.Any(x => x.FullName.Contains("SpecFlow"))) { projectTrackInfo = $"{projectTrackInfo} SpecFlow"; } if (testProjectAssembly.FullName.Contains("GettingStarted")) { projectTrackInfo = $"{projectTrackInfo} GettingStarted"; } var testInfoProvider = new TestInfoProvider(); EventTelemetry eventTelemetry = default; int mstestTestsCount = testInfoProvider.CountBellatrixTests(testProjectAssembly, _msTestClassAttributeName, _msTestTestAttributeName); int nunitTestsCount = testInfoProvider.CountBellatrixTests(testProjectAssembly, _nunitTestFixtureAttributeName, _nunitTestAttributeName); if (mstestTestsCount > 0) { eventTelemetry = new EventTelemetry(); eventTelemetry.Name = "MSTest Test Run"; eventTelemetry.Metrics.Add(projectTrackInfo, mstestTestsCount); } if (nunitTestsCount > 0) { eventTelemetry = new EventTelemetry(); eventTelemetry.Name = "NUnit Test Run"; eventTelemetry.Metrics.Add(projectTrackInfo, nunitTestsCount); } TelemetryService.TrackEvent(eventTelemetry, isDebug); } } catch (Exception ex) { TelemetryService.TrackException(ex, isDebug); } }
protected void Page_Load(object sender, EventArgs e) { if (this.Request.QueryString["Type"] != null) { Type type = TypeManager.GetType(this.Request.QueryString["Type"]); FlushAttribute flushAttribute = type.GetCustomAttributes(false).Where(f => f.GetType() == typeof(FlushAttribute)).Single() as FlushAttribute; MethodInfo methodInfo = (from m in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) where m.Name == flushAttribute.MethodName select m).SingleOrDefault(); methodInfo.Invoke(null, null); FlushAdminPlaceHolder.Controls.Add(new LiteralControl(string.Format(@"<b>{0} flushed</b>", this.Request.QueryString["Type"]))); FlushAdminPlaceHolder.Controls.Add(new LiteralControl("<br /><br /><br />")); } FlushAdminPlaceHolder.Controls.Add(new LiteralControl(@"<table border=""0"">")); foreach (Type type in AssemblyFacade.GetAllAssemblies().GetTypes()) { FlushAttribute flushAttribute = type.GetCustomAttributes(false).Where(f => f.GetType() == typeof(FlushAttribute)).SingleOrDefault() as FlushAttribute; if (flushAttribute == null) { continue; } MethodInfo methodInfo = (from m in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) where m.Name == flushAttribute.MethodName select m).SingleOrDefault(); if (methodInfo == null) { continue; } FlushAdminPlaceHolder.Controls.Add(new LiteralControl("<tr>")); FlushAdminPlaceHolder.Controls.Add(new LiteralControl("<td>" + type.FullName + "</td>")); FlushAdminPlaceHolder.Controls.Add(new LiteralControl(string.Format(@"<td><a href=""{0}?Type={1}"">Flush</a></td>", this.Request.CurrentExecutionFilePath, HttpUtility.UrlEncode(type.GetVersionNeutralName())))); FlushAdminPlaceHolder.Controls.Add(new LiteralControl("</tr>")); } FlushAdminPlaceHolder.Controls.Add(new LiteralControl("</table>")); }
/// <summary> /// Call this method whan a new assembly is load/added into the app domain. /// </summary> /// <param name="assembly"></param> /// <param name="logTypeLoadErrors"></param> public static void AddNewAssembly(Assembly assembly, bool logTypeLoadErrors) { if (!AssemblyFacade.AssemblyPotentiallyUsesType(assembly, typeof(IData))) { return; } try { var types = assembly.GetTypes(); _LoadedDataTypes.AddRange(types.Where(typeof(IData).IsAssignableFrom)); } catch (ReflectionTypeLoadException exception) { if (logTypeLoadErrors) { var exceptionToLog = exception.LoaderExceptions != null?exception.LoaderExceptions.First() : exception; Log.LogError(LogTitle, new Exception($"Failed to load assembly '{assembly.FullName}'", exceptionToLog)); } } }
/// <exclude /> public AttributeBasedApplicationStartupHandler() { List <AssemblyInfo> cachedTypesInfo = GetCachedAssemblyInfo(); bool cacheHasBeenUpdated = false; foreach (string filePath in AssemblyFacade.GetAssembliesFromBin()) { StartupHandlerInfo[] types = null; try { types = GetSubscribedTypes(filePath, cachedTypesInfo, ref cacheHasBeenUpdated); } catch (Exception e) { LogAssemblyLoadException(filePath, e); } if (types != null) { Subscribe(types); } } Assembly appCodeAsm = AssemblyFacade.GetAppCodeAssembly(); if (appCodeAsm != null) { Subscribe(GetSubscribedTypes(appCodeAsm.GetTypes())); } if (cacheHasBeenUpdated) { SaveTypesCache(cachedTypesInfo); } }
private void InitializeExistingStores() { _compositeGeneratedAssembly = _compositeGeneratedAssembly ?? AssemblyFacade.GetGeneratedAssemblyFromBin(); _sqlDataTypeStoresContainer = new SqlDataTypeStoresContainer(_dataProviderContext.ProviderName, _connectionString, _sqlLoggingContext); Dictionary <DataTypeDescriptor, IEnumerable <SqlDataTypeStoreDataScope> > allSqlDataTypeStoreDataScopes = BuildAllExistingDataTypeStoreDataScopes(); var initializedStores = new List <InterfaceGeneratedClassesInfo>(); bool dataContextRecompilationNeeded = false; Type dataContextClass = TryLoadDataContext(ref dataContextRecompilationNeeded); var dataTypes = LoadDataTypes(_interfaceConfigurationElements); var compilationData = new List <HelperClassesGenerationInfo>(); foreach (InterfaceConfigurationElement element in _interfaceConfigurationElements) { HelperClassesGenerationInfo toCompile = null; var generatedClassesInfo = InitializeStoreTypes(element, allSqlDataTypeStoreDataScopes, dataContextClass, dataTypes, false, ref dataContextRecompilationNeeded, ref toCompile); if (generatedClassesInfo == null) { continue; } if (toCompile != null) { compilationData.Add(toCompile); } initializedStores.Add(generatedClassesInfo); } if (compilationData.Any()) { var codeGenerationBuilder = new CodeGenerationBuilder(_dataProviderContext.ProviderName + " : compiling missing classes"); foreach (var toCompile in compilationData) { toCompile.GenerateCodeAction(codeGenerationBuilder); } // Precompiling DataWrapper classes as well to improve loading time foreach (var interfaceType in dataTypes.Values) { if (DataWrapperTypeManager.TryGetWrapperType(interfaceType.FullName) == null) { DataWrapperCodeGenerator.AddDataWrapperClassCode(codeGenerationBuilder, interfaceType); } } var types = CodeGenerationManager.CompileRuntimeTempTypes(codeGenerationBuilder, false).ToArray(); foreach (var toCompile in compilationData) { toCompile.PopulateFieldsAction(types); } } if (dataContextRecompilationNeeded) { dataContextClass = DataContextAssembler.EmitDataContextClass( initializedStores .Where(s => s.Fields != null) .SelectMany(s => s.Fields.Values).Evaluate()); } _sqlDataTypeStoresContainer.DataContextClass = dataContextClass; foreach (var typeInfo in initializedStores) { var store = EmbedDataContextInfo(typeInfo, dataContextClass); AddDataTypeStore(store, true, true); } }
/// <exclude /> public static MethodInfo Create(IInlineFunction function, string code = null, InlineFunctionCreateMethodErrorHandler createMethodErrorHandler = null, List <string> selectedAssemblies = null) { if (string.IsNullOrWhiteSpace(code)) { try { code = GetFunctionCode(function); } catch (ThreadAbortException) { } catch (Exception ex) { if (createMethodErrorHandler != null) { createMethodErrorHandler.OnLoadSourceError(ex); } else { LogMessageIfNotShuttingDown(function, ex.Message); } return(null); } } CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; if (selectedAssemblies == null) { IEnumerable <IInlineFunctionAssemblyReference> assemblyReferences = DataFacade.GetData <IInlineFunctionAssemblyReference>(f => f.Function == function.Id).Evaluate(); foreach (IInlineFunctionAssemblyReference assemblyReference in assemblyReferences) { string assemblyPath = GetAssemblyFullPath(assemblyReference.Name, assemblyReference.Location); compilerParameters.ReferencedAssemblies.Add(assemblyPath); } } else { foreach (string reference in selectedAssemblies) { compilerParameters.ReferencedAssemblies.Add(reference); } } Assembly appCodeAssembly = AssemblyFacade.GetAppCodeAssembly(); if (appCodeAssembly != null) { compilerParameters.ReferencedAssemblies.Add(appCodeAssembly.Location); } CSharpCodeProvider compiler = new CSharpCodeProvider(); CompilerResults results = compiler.CompileAssemblyFromSource(compilerParameters, code); if (results.Errors.HasErrors) { foreach (CompilerError error in results.Errors) { if (createMethodErrorHandler != null) { createMethodErrorHandler.OnCompileError(error.Line, error.ErrorNumber, error.ErrorText); } else { LogMessageIfNotShuttingDown(function, error.ErrorText); } } return(null); } Type type = results.CompiledAssembly.GetTypes().SingleOrDefault(f => f.Name == MethodClassContainerName); if (type == null) { string message = Texts.CSharpInlineFunction_OnMissingContainerType(MethodClassContainerName); if (createMethodErrorHandler != null) { createMethodErrorHandler.OnMissingContainerType(message); } else { LogMessageIfNotShuttingDown(function, message); } return(null); } if (type.Namespace != function.Namespace) { string message = Texts.CSharpInlineFunction_OnNamespaceMismatch(type.Namespace, function.Namespace); if (createMethodErrorHandler != null) { createMethodErrorHandler.OnNamespaceMismatch(message); } else { LogMessageIfNotShuttingDown(function, message); } return(null); } MethodInfo methodInfo = type.GetMethods(BindingFlags.Public | BindingFlags.Static).SingleOrDefault(f => f.Name == function.Name); if (methodInfo == null) { string message = Texts.CSharpInlineFunction_OnMissionMethod(function.Name, MethodClassContainerName); if (createMethodErrorHandler != null) { createMethodErrorHandler.OnMissionMethod(message); } else { LogMessageIfNotShuttingDown(function, message); } return(null); } return(methodInfo); }
public static bool IsAppCodeDll(Assembly assembly) { return(AssemblyFacade.IsAppCodeDll(assembly)); }
private static StartupHandlerInfo[] GetSubscribedTypes( string filePath, List <AssemblyInfo> cachedTypesInfo, ref bool cacheHasBeenUpdated) { string assemblyName = Path.GetFileNameWithoutExtension(filePath); foreach (string assemblyToIgnore in AssembliesToIgnore) { if (assemblyName == assemblyToIgnore || assemblyName.StartsWith(assemblyToIgnore + ",") || (assemblyToIgnore.EndsWith(".") && assemblyName.StartsWith(assemblyToIgnore))) { return(null); } } DateTime modificationDate = C1File.GetLastWriteTime(filePath); var cachedInfo = cachedTypesInfo.FirstOrDefault(asm => asm.AssemblyName == assemblyName); if (cachedInfo != null) { if (cachedInfo.LastModified == modificationDate) { string[] subscribedTypesNames = cachedInfo.SubscribedTypes; if (subscribedTypesNames.Length == 0) { return(new StartupHandlerInfo[0]); } var asm = Assembly.LoadFrom(filePath); return((from typeName in subscribedTypesNames let type = asm.GetType(typeName) where type != null let attribute = type.GetCustomAttributes(false) .OfType <ApplicationStartupAttribute>() .FirstOrDefault() where attribute != null select new StartupHandlerInfo(type, attribute)).ToArray()); } // Removing cache entry if it is obsolete cachedTypesInfo.Remove(cachedInfo); } Assembly assembly; try { assembly = Assembly.LoadFrom(filePath); } catch (ReflectionTypeLoadException ex) { Log.LogWarning(LogTitle, "Failed to load assembly '{0}'".FormatWith(filePath)); if (ex.LoaderExceptions != null && ex.LoaderExceptions.Length > 0) { Log.LogError(LogTitle, ex.LoaderExceptions[0]); } return(null); } if (!AssemblyFacade.AssemblyPotentiallyUsesType(assembly, typeof(ApplicationStartupAttribute))) { return(null); } Type[] types; if (!TryGetTypes(assembly, out types)) { return(new StartupHandlerInfo[0]); } var result = GetSubscribedTypes(types); var newCacheEntry = new AssemblyInfo { AssemblyName = assembly.GetName().Name, LastModified = modificationDate, SubscribedTypes = result.Select(sh => sh.Type.FullName).ToArray() }; cachedTypesInfo.Add(newCacheEntry); cacheHasBeenUpdated = true; return(result); }
public EmbeddedResourcesService() { _assemblyFacade = new AssemblyFacade(); }