public ScheduleManager(IJobManager jobManager, IScheduler scheduler, IEventReporter eventReporter, TypeLoader typeLoader) { this.JobManager = jobManager; this.Scheduler = scheduler; this.EventReporter = eventReporter; this.TypeLoader = typeLoader; }
private static TypeLoader<NonTerminalNode, int> LoadImplTypes() { TypeLoader<NonTerminalNode, int> loader = new TypeLoader<NonTerminalNode, int>(); loader.SearchDirectories = false; loader.LoadMany(t => t.GetCustomAttributes(typeof(SyntaxNodeAttribute), false).Select(attr => (int)((SyntaxNodeAttribute)attr).RuleConstant)); return loader; }
public static ContractDescription GetContract(Type contractType) { if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); } TypeLoader loader = new TypeLoader(); return loader.LoadContractDescription(contractType); }
static OperationFormatter GetOperationFormatter(Type t, Attribute formatAttribute, string defaultNS, string action) { bool isXmlSerializer = (formatAttribute is XmlSerializerFormatAttribute); TypeLoader typeLoader = new TypeLoader(); MessageDescription message = typeLoader.CreateTypedMessageDescription(t, null, null, defaultNS, action, MessageDirection.Output); ContractDescription contract = new ContractDescription("dummy_contract", defaultNS); OperationDescription operation = new OperationDescription(NamingHelper.XmlName(t.Name), contract, false); operation.Messages.Add(message); if (isXmlSerializer) return XmlSerializerOperationBehavior.CreateOperationFormatter(operation, (XmlSerializerFormatAttribute)formatAttribute); else return new DataContractSerializerOperationFormatter(operation, (DataContractFormatAttribute)formatAttribute, null); }
private static OperationFormatter GetOperationFormatter(System.Type t, Attribute formatAttribute, string defaultNS, string action) { bool flag = formatAttribute is XmlSerializerFormatAttribute; MessageDescription description = new TypeLoader().CreateTypedMessageDescription(t, null, null, defaultNS, action, MessageDirection.Output); ContractDescription declaringContract = new ContractDescription("dummy_contract", defaultNS); OperationDescription operation = new OperationDescription(NamingHelper.XmlName(t.Name), declaringContract, false) { Messages = { description } }; if (flag) { return XmlSerializerOperationBehavior.CreateOperationFormatter(operation, (XmlSerializerFormatAttribute) formatAttribute); } return new DataContractSerializerOperationFormatter(operation, (DataContractFormatAttribute) formatAttribute, null); }
public void PackageActionCollectionBuilderWorks() { var container = RegisterFactory.Create(); var composition = new Composition(container, new TypeLoader(), Mock.Of <IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run)); composition.WithCollectionBuilder <PackageActionCollectionBuilder>() .Add(() => TypeLoader.GetPackageActions()); Current.Factory = composition.CreateFactory(); var actions = Current.PackageActions; Assert.AreEqual(2, actions.Count()); // order is unspecified, but both must be there var hasAction1 = actions.ElementAt(0) is PackageAction1 || actions.ElementAt(1) is PackageAction1; var hasAction2 = actions.ElementAt(0) is PackageAction2 || actions.ElementAt(1) is PackageAction2; Assert.IsTrue(hasAction1); Assert.IsTrue(hasAction2); }
public void FactoryIsResolvable() { Func <IFactory, IFactory> factoryFactory = null; var mockedRegister = Mock.Of <IRegister>(); var mockedFactory = Mock.Of <IFactory>(); // the mocked register creates the mocked factory Mock.Get(mockedRegister) .Setup(x => x.CreateFactory()) .Returns(mockedFactory); // the mocked register can register a factory factory Mock.Get(mockedRegister) .Setup(x => x.Register(It.IsAny <Func <IFactory, IFactory> >(), Lifetime.Singleton)) .Callback <Func <IFactory, IFactory>, Lifetime>((ff, lt) => factoryFactory = ff); // the mocked factory can invoke the factory factory Mock.Get(mockedFactory) .Setup(x => x.GetInstance(typeof(IFactory))) .Returns(() => factoryFactory?.Invoke(mockedFactory)); var logger = new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()); var typeLoader = new TypeLoader(Mock.Of <IAppPolicyCache>(), IOHelper.MapPath("~/App_Data/TEMP"), logger); var composition = new Composition(mockedRegister, typeLoader, logger, Mock.Of <IRuntimeState>()); // create the factory, ensure it is the mocked factory var factory = composition.CreateFactory(); Assert.AreSame(mockedFactory, factory); // ensure we can get an IFactory instance, // meaning that it has been properly registered var resolved = factory.GetInstance <IFactory>(); Assert.IsNotNull(resolved); Assert.AreSame(factory, resolved); }
public void AllComposers() { var ioHelper = IOHelper.Default; var typeFinder = new TypeFinder(Mock.Of <ILogger>()); var typeLoader = new TypeLoader(ioHelper, typeFinder, AppCaches.Disabled.RuntimeCache, new DirectoryInfo(ioHelper.MapPath("~/App_Data/TEMP")), Mock.Of <IProfilingLogger>()); var register = MockRegister(); var composition = new Composition(register, typeLoader, Mock.Of <IProfilingLogger>(), MockRuntimeState(RuntimeLevel.Run)); var types = typeLoader.GetTypes <IComposer>().Where(x => x.FullName.StartsWith("Umbraco.Core.") || x.FullName.StartsWith("Umbraco.Web")); var composers = new Composers(composition, types, Mock.Of <IProfilingLogger>()); var requirements = composers.GetRequirements(); var report = Composers.GetComposersReport(requirements); Console.WriteLine(report); var composerTypes = composers.SortComposers(requirements); foreach (var type in composerTypes) { Console.WriteLine(type); } }
/// <summary> /// Registers essential services. /// </summary> public static void RegisterEssentials(this Composition composition, ILogger logger, IProfiler profiler, IProfilingLogger profilingLogger, IMainDom mainDom, AppCaches appCaches, IUmbracoDatabaseFactory databaseFactory, TypeLoader typeLoader, IRuntimeState state, ITypeFinder typeFinder, IIOHelper ioHelper) { composition.RegisterUnique(logger); composition.RegisterUnique(profiler); composition.RegisterUnique(profilingLogger); composition.RegisterUnique(mainDom); composition.RegisterUnique(appCaches); composition.RegisterUnique(databaseFactory); composition.RegisterUnique(factory => factory.GetInstance <IUmbracoDatabaseFactory>().SqlContext); composition.RegisterUnique(typeLoader); composition.RegisterUnique(state); composition.RegisterUnique(typeFinder); composition.RegisterUnique(ioHelper); }
public void AllComposers() { ITypeFinder typeFinder = TestHelper.GetTypeFinder(); var typeLoader = new TypeLoader(typeFinder, new VaryingRuntimeHash(), AppCaches.Disabled.RuntimeCache, new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of <ILogger <TypeLoader> >(), Mock.Of <IProfiler>()); IServiceCollection register = MockRegister(); var builder = new UmbracoBuilder(register, Mock.Of <IConfiguration>(), TestHelper.GetMockedTypeLoader()); var allComposers = typeLoader.GetTypes <IComposer>().ToList(); var types = allComposers.Where(x => x.FullName.StartsWith("Umbraco.Core.") || x.FullName.StartsWith("Umbraco.Web")).ToList(); var composers = new ComposerGraph(builder, types, Enumerable.Empty <Attribute>(), Mock.Of <ILogger <ComposerGraph> >()); Dictionary <Type, List <Type> > requirements = composers.GetRequirements(); string report = ComposerGraph.GetComposersReport(requirements); Console.WriteLine(report); IEnumerable <Type> composerTypes = composers.SortComposers(requirements); foreach (Type type in composerTypes) { Console.WriteLine(type); } }
public void Requires2B() { IServiceCollection register = MockRegister(); TypeLoader typeLoader = MockTypeLoader(); IServiceProvider factory = MockFactory(); var composition = new UmbracoBuilder(register, Mock.Of <IConfiguration>(), TestHelper.GetMockedTypeLoader()); Type[] types = new[] { typeof(Composer9), typeof(Composer2), typeof(Composer4) }; var composers = new ComposerGraph(composition, types, Enumerable.Empty <Attribute>(), Mock.Of <ILogger <ComposerGraph> >()); Composed.Clear(); composers.Compose(); ComponentCollectionBuilder builder = composition.WithCollectionBuilder <ComponentCollectionBuilder>(); builder.RegisterWith(register); ComponentCollection components = builder.CreateCollection(factory); Assert.AreEqual(3, Composed.Count); Assert.AreEqual(typeof(Composer4), Composed[0]); Assert.AreEqual(typeof(Composer2), Composed[1]); Assert.AreEqual(typeof(Composer9), Composed[2]); }
public void Initialize() { // this ensures it's reset _typeLoader = new TypeLoader(NoAppCache.Instance, IOHelper.MapPath("~/App_Data/TEMP"), new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()), false); // for testing, we'll specify which assemblies are scanned for the PluginTypeResolver // TODO: Should probably update this so it only searches this assembly and add custom types to be found _typeLoader.AssembliesToScan = new[] { this.GetType().Assembly, typeof(System.Guid).Assembly, typeof(NUnit.Framework.Assert).Assembly, typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly, typeof(System.Xml.NameTable).Assembly, typeof(System.Configuration.GenericEnumConverter).Assembly, typeof(System.Web.SiteMap).Assembly, //typeof(TabPage).Assembly, typeof(System.Web.Mvc.ActionResult).Assembly, typeof(TypeFinder).Assembly, typeof(UmbracoContext).Assembly }; }
public object CreateInstance(Type type, IEnumerable <Tag> metaInfo) { IEnumerator <Tag> it = metaInfo.GetEnumerator(); try { it.MoveNext(); } catch (InvalidOperationException e) { throw new PersistenceException("Insufficient meta information to instantiate Type object", e); } try { return(TypeLoader.Load((string)it.Current.Value)); } catch (InvalidCastException e) { throw new PersistenceException("Invalid meta information during reconstruction of Type object", e); } catch (TypeLoadException e) { throw new PersistenceException(String.Format( "Cannot load Type {0}, make sure all required assemblies are available.", (string)it.Current.Value), e); } }
private void WriteDataContext(CodeWriter writer, Database schema, GenerationContext context) { if (schema.Tables.Count == 0) { writer.WriteCommentLine("L69 no tables found"); return; } string contextBase = schema.BaseType; var contextBaseType = string.IsNullOrEmpty(contextBase) ? typeof(DataContext) : TypeLoader.Load(contextBase); // in all cases, get the literal type name from loaded type contextBase = writer.GetLiteralType(contextBaseType); var specifications = SpecificationDefinition.Partial; if (schema.AccessModifierSpecified) { specifications |= GetSpecificationDefinition(schema.AccessModifier); } else { specifications |= SpecificationDefinition.Public; } if (schema.ModifierSpecified) { specifications |= GetSpecificationDefinition(schema.Modifier); } using (writer.WriteClass(specifications, schema.Class, contextBase)) { WriteDataContextExtensibilityDeclarations(writer, schema, context); WriteDataContextCtors(writer, schema, contextBaseType, context); WriteDataContextTables(writer, schema, context); WriteDataContextProcedures(writer, schema, context); } }
public static void LoadMultiModuleFromDisk_GetModuleCaseInsensitive() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("bOB.nEtmODule"); Assert.Equal(a, m.Assembly); Assert.Equal(bobNetModulePath, m.FullyQualifiedName); Assert.Equal(Path.GetFileName(bobNetModulePath), m.Name); Assert.Equal(TestData.s_JoeScopeName, m.ScopeName); Assert.Equal(TestData.s_JoeNetModuleMvid, m.ModuleVersionId); } } }
public static void ResolveEventReturnsNull() { using (TypeLoader tl = new TypeLoader()) { bool resolveHandlerCalled = false; tl.Resolving += delegate(TypeLoader sender, AssemblyName name) { Assert.Same(tl, sender); Assert.Equal(name.Name, "Foo"); resolveHandlerCalled = true; return(null); }; Assembly derived = tl.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage); Type t = derived.GetType("Derived1", throwOnError: true); Assert.Throws <FileNotFoundException>(() => t.BaseType); Assert.True(resolveHandlerCalled); } }
public static void MultiModule_GetModules(bool getResourceModules) { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module[] ms = a.GetModules(getResourceModules: getResourceModules); Assert.Equal(2, ms.Length); Module bob = a.GetModule("Bob.netmodule"); Assert.NotNull(bob); Assert.Contains <Module>(a.ManifestModule, ms); Assert.Contains <Module>(bob, ms); } } }
public void Get_Plugins_Hash() { //Arrange var dir = PrepareFolder(); var d1 = dir.CreateSubdirectory("1"); var d2 = dir.CreateSubdirectory("2"); var d3 = dir.CreateSubdirectory("3"); var d4 = dir.CreateSubdirectory("4"); var f1 = new FileInfo(Path.Combine(d1.FullName, "test1.dll")); var f2 = new FileInfo(Path.Combine(d1.FullName, "test2.dll")); var f3 = new FileInfo(Path.Combine(d2.FullName, "test1.dll")); var f4 = new FileInfo(Path.Combine(d2.FullName, "test2.dll")); var f5 = new FileInfo(Path.Combine(d3.FullName, "test1.dll")); var f6 = new FileInfo(Path.Combine(d3.FullName, "test2.dll")); var f7 = new FileInfo(Path.Combine(d4.FullName, "test1.dll")); f1.CreateText().Close(); f2.CreateText().Close(); f3.CreateText().Close(); f4.CreateText().Close(); f5.CreateText().Close(); f6.CreateText().Close(); f7.CreateText().Close(); var list1 = new[] { f1, f2, f3, f4, f5, f6 }; var list2 = new[] { f1, f3, f5 }; var list3 = new[] { f1, f3, f5, f7 }; //Act var hash1 = TypeLoader.GetFileHash(list1, new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>())); var hash2 = TypeLoader.GetFileHash(list2, new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>())); var hash3 = TypeLoader.GetFileHash(list3, new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>())); //Assert Assert.AreNotEqual(hash1, hash2); Assert.AreNotEqual(hash1, hash3); Assert.AreNotEqual(hash2, hash3); Assert.AreEqual(hash1, TypeLoader.GetFileHash(list1, new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()))); }
public virtual void Initialize() { Current.Reset(); var container = RegisterFactory.Create(); var ioHelper = IOHelper.Default; var logger = new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()); var typeFinder = new TypeFinder(Mock.Of <ILogger>()); var typeLoader = new TypeLoader(ioHelper, typeFinder, NoAppCache.Instance, new DirectoryInfo(ioHelper.MapPath("~/App_Data/TEMP")), logger, false); var composition = new Composition(container, typeLoader, Mock.Of <IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run)); composition.RegisterUnique <ILogger>(_ => Mock.Of <ILogger>()); composition.RegisterUnique <IProfiler>(_ => Mock.Of <IProfiler>()); composition.RegisterUnique(typeLoader); composition.WithCollectionBuilder <MapperCollectionBuilder>() .AddCoreMappers(); composition.RegisterUnique <ISqlContext>(_ => SqlContext); var factory = Current.Factory = composition.CreateFactory(); var pocoMappers = new NPoco.MapperCollection { new PocoMapper() }; var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init()); var sqlSyntax = new SqlCeSyntaxProvider(); SqlContext = new SqlContext(sqlSyntax, DatabaseType.SQLCe, pocoDataFactory, new Lazy <IMapperCollection>(() => factory.GetInstance <IMapperCollection>())); Mappers = factory.GetInstance <IMapperCollection>(); SetUp(); }
private static TypeCollection LoadAll(Options options) { TypeCollection totalTypeCollection = new TypeCollection(); options.Log("Loading input files."); foreach (string filename in options.Filenames) { if (filename.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) { options.Log("Loading XML \"{0}\".", filename); TypeCollection typeCollection = new XmlLoader().Load(filename); totalTypeCollection = totalTypeCollection.AddTypeRange(typeCollection); } else if (filename.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || filename.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) { options.Log("Loading assembly \"{0}\".", filename); Assembly assembly = Assembly.LoadFrom(filename); options.Log("Loading XML for assembly."); TypeCollection xmlCollection = new XmlLoader().Load(assembly); options.Log("Reflecting on assembly."); TypeCollection reflectedCollection = new TypeLoader().ReflectOnAssembly(assembly, options.IncludeKind); options.Log("Combining reflected data with XML."); TypeCollection typeCollection = reflectedCollection.MergeInDocumentation(xmlCollection); totalTypeCollection = totalTypeCollection.AddTypeRange(typeCollection); } } options.Log("All input files loaded."); return(totalTypeCollection); }
internal void EnsureMessageInfos() { if (_request == null) { foreach (Type knownType in Operation.KnownTypes) { if (knownType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxKnownTypeNull, Operation.Name))); } _parent._importer.IncludeType(knownType); } _request = CreateMessageInfo(this.Operation.Messages[0], ":Request"); // We don't do the following check at Net Native runtime because XmlMapping.XsdElementName // is not available at that time. bool skipVerifyXsdElementName = false; #if FEATURE_NETNATIVE skipVerifyXsdElementName = GeneratedXmlSerializers.IsInitialized; #endif if (_request != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _request.BodyMapping.XsdElementName != this.Operation.Name) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[0].MessageName, _request.BodyMapping.XsdElementName, this.Operation.Name))); } if (!this.IsOneWay) { _reply = CreateMessageInfo(this.Operation.Messages[1], ":Response"); XmlName responseName = TypeLoader.GetBodyWrapperResponseName(this.Operation.Name); if (_reply != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _reply.BodyMapping.XsdElementName != responseName.EncodedName) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[1].MessageName, _reply.BodyMapping.XsdElementName, responseName.EncodedName))); } } if (this.Attribute.SupportFaults) { GenerateXmlSerializerFaultContractInfos(); } } }
public static void Load(List <TextNode> nodes) { foreach (var node in nodes) { var name = node.Key; var parts = new PartInfo[node.Children.Count]; var currentPartCounts = new Dictionary <string, int>(); for (int i = 0; i < parts.Length; i++) { var child = node.Children[i]; if (!currentPartCounts.ContainsKey(child.Key)) { currentPartCounts[child.Key] = 0; } parts[i] = TypeLoader.GetPart(currentPartCounts[child.Key]++, child); } Types.Add(name, new ActorType(parts)); } }
public ILoader GetLoader(string path, TypeLoader typeLoader) { try { switch (typeLoader) { case TypeLoader.Xml: return(new LoaderXml(path)); case TypeLoader.Xlsx: return(new LoaderXlsx(path)); default: throw new Exception("Ошибка с TypeLoader"); } } catch (Exception exception) { Logger.Logger.Error(exception, nameof(CoreLoader), nameof(GetLoader)); throw; } }
public static void InsertPackage(Putki.Package package, TypeLoader ldr) { foreach (Package.Slot s in package.m_slots) { if (s.path.Length > 0 && s.inst != null) { // someone loaded this before, point them to this new version. if (m_currentMapping.ContainsKey(s.path)) { if (m_currentMapping[s.path] != s.inst) { m_globalReplace[m_currentMapping[s.path]] = s.inst; } } // update current mapping. m_currentMapping[s.path] = s.inst; } } m_patchOrder.Insert(0, package); m_old.Add(package); }
public static void LoadFromDifferentLocations() { using (TempFile tf1 = TempFile.Create(TestData.s_SimpleAssemblyImage)) using (TempFile tf2 = TempFile.Create(TestData.s_SimpleAssemblyImage)) using (TypeLoader tl = new TypeLoader()) { // As long as the MVID matches, you can load the same assembly from multiple locations. Assembly a = tl.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.NotNull(a); Assembly a1 = tl.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.Equal(a, a1); Assembly a2 = tl.LoadFromAssemblyName(new AssemblyName(TestData.s_SimpleAssemblyName)); Assert.Equal(a, a2); Assembly a3 = tl.LoadFromAssemblyPath(tf1.Path); Assert.Equal(a, a3); Assembly a4 = tl.LoadFromAssemblyPath(tf2.Path); Assert.Equal(a, a4); } }
public PartialityWrapper() { foreach (Type t in TypeLoader.LoadTypes <PartialityMod>(Paths.PluginPath)) { //Don't try to load the base class if (t.Name != "PartialityMod") { Logger.LogInfo("Partiality Wrapper - instantiating " + t.Name); var mod = Activator.CreateInstance(t) as PartialityMod; try { Logger.LogInfo("Initializing and Loading " + mod.ModID); mod.Init(); mod.OnLoad(); mod.OnEnable(); } catch (Exception e) { Logger.LogError("Could not load Partiality Mod: " + mod.ModID + "\r\n" + e); } } } }
public virtual void Setup() { IServiceCollection container = TestHelper.GetServiceCollection(); TypeLoader typeLoader = TestHelper.GetMockedTypeLoader(); var composition = new UmbracoBuilder(container, Mock.Of <IConfiguration>(), TestHelper.GetMockedTypeLoader()); composition.WithCollectionBuilder <MapperCollectionBuilder>() .AddCoreMappers(); composition.Services.AddUnique(_ => SqlContext); IServiceProvider factory = composition.CreateServiceProvider(); var pocoMappers = new NPoco.MapperCollection { new NullableDateMapper() }; var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init()); var sqlSyntax = new SqlServerSyntaxProvider(Options.Create(new GlobalSettings())); SqlContext = new SqlContext(sqlSyntax, DatabaseType.SqlServer2012, pocoDataFactory, factory.GetRequiredService <IMapperCollection>()); Mappers = factory.GetRequiredService <IMapperCollection>(); }
public static void CoreAssemblyCanBeAFacade() { using (TypeLoader tl = new TypeLoader(coreAssemblyName: TestData.s_PhonyCoreAssemblyName)) { Assembly actualCoreAssembly = null; tl.Resolving += delegate(TypeLoader sender, AssemblyName refName) { if (refName.Name.Equals("mscorlib", StringComparison.OrdinalIgnoreCase)) { return(actualCoreAssembly = sender.LoadFromStream(TestUtils.CreateStreamForCoreAssembly())); } return(null); }; Assembly a = tl.LoadFromByteArray(TestData.s_PhonyCoreAssemblyImage); // This is a sanity check to ensure that "TestData.s_PhonyCoreAssemblyName" is actually the def-name of this // assembly. It better be since we told our TypeLoader to use it as our core assembly. Assembly aAgain = tl.LoadFromAssemblyName(TestData.s_PhonyCoreAssemblyName); Type derived = a.GetType("Derived", throwOnError: true, ignoreCase: false); // Calling BaseType causes the TypeLoader to parse the typespec "Base<object>". Since "object" is a primitive // type, it should be encoded using the short-form "ELEMENT_TYPE_OBJECT." Hence, the TypeLoader is forced // to look up "System.Object" in the core assembly we assigned to it, which in this case is "PhonyCoreAssembly" // which type-forwards System.Object to "mscorlib". Type baseType = derived.BaseType; Assert.NotNull(actualCoreAssembly); // Ensure our resolve handler actually ran. Assert.NotEqual(a, actualCoreAssembly); Assert.True(baseType.IsConstructedGenericType); Type retrievedObjectType = baseType.GenericTypeArguments[0]; Assert.Equal("System.Object", retrievedObjectType.FullName); Assert.Equal(actualCoreAssembly, retrievedObjectType.Assembly); } }
public Schema Generate(string url = "", Dictionary <string, string> headers = null) { var schema = new Schema { Headers = headers, Url = url }; var controllers = TypeLoader.Get(_assemblies, x => x.FullName.EndsWith("Controller")); foreach (var ctrl in controllers) { var controllerUrl = $"{url}/{ctrl.Name.Replace("Controller", "")}"; var schCtrl = new Controller { Url = controllerUrl }; var methods = MethodLoader.Get(ctrl, x => !x.IsSpecialName && x.DeclaringType?.FullName == ctrl.FullName); foreach (var method in methods) { var methodUrl = $"{controllerUrl}/{method.Name}"; var endp = new Endpoint { Url = methodUrl, Verb = VerbLoader.Get(method) }; foreach (var p in ParamLoader.Get(method)) { endp.Input.Add(p.Name, p.ParameterType.IsPrimitive || p.ParameterType == typeof(string) ? p.ParameterType.FullName : GetBody(p)); } schCtrl.Endpoints.Add(endp); } schema.Controllers.Add(schCtrl); } return(schema); }
public virtual void Initialize() { Current.Reset(); var sqlSyntax = new SqlCeSyntaxProvider(); var container = RegisterFactory.Create(); var logger = new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()); var typeLoader = new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, logger, false); var composition = new Composition(container, typeLoader, Mock.Of <IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run)); composition.RegisterUnique <ILogger>(_ => Mock.Of <ILogger>()); composition.RegisterUnique <IProfiler>(_ => Mock.Of <IProfiler>()); composition.RegisterUnique(typeLoader); composition.WithCollectionBuilder <MapperCollectionBuilder>() .Add(() => composition.TypeLoader.GetAssignedMapperTypes()); var factory = Current.Factory = composition.CreateFactory(); Mappers = factory.GetInstance <IMapperCollection>(); var pocoMappers = new NPoco.MapperCollection { new PocoMapper() }; var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init()); SqlContext = new SqlContext(sqlSyntax, DatabaseType.SQLCe, pocoDataFactory, Mappers); SetUp(); }
public TerrainType(ushort id, List <TextNode> nodes, bool documentation = false) { ID = id; TypeLoader.SetValues(this, nodes); Overlaps = EdgeSprite != null; if (documentation) { return; } if (Sprite == null || Sprite == string.Empty) { throw new MissingNodeException(ID.ToString(), "Image"); } baseTextureInfo = new TextureInfo(Sprite, TextureType.RANDOM, MasterRenderer.PixelSize, MasterRenderer.PixelSize); if (Overlaps) { if (EdgeSprite != null) { edgeTextureInfo = new TextureInfo(EdgeSprite, TextureType.RANDOM, EdgeSpriteBounds); } if (CornerSprite != null) { cornerTextureInfo = new TextureInfo(CornerSprite, TextureType.RANDOM, CornerSpriteBounds); } if (VerticalEdgeSprite != null) { verticalTextureInfo = new TextureInfo(VerticalEdgeSprite, TextureType.RANDOM, VerticalEdgeSpriteBounds); } } }
private static TypeloaderCache GetPluginCache() { LoadQMMAssemblyCache(); if (QMMAssemblyCache == null) { ClearBepInExCache(); QMMAssemblyCache = GetNewQMMAssemblyCache(); SaveQMMAssemblyCache(); } else { var qmmAssemblyCache = GetNewQMMAssemblyCache(); if (!qmmAssemblyCache.Keys.SequenceEqual(QMMAssemblyCache.Keys) || qmmAssemblyCache.Any(x => x.Value != QMMAssemblyCache[x.Key])) { ClearBepInExCache(); QMMAssemblyCache = qmmAssemblyCache; SaveQMMAssemblyCache(); } } return(TypeLoader.LoadAssemblyCache <PluginInfo>(GeneratedPluginCache)); }
public InitialSessionStateManager(string pssessionConfigurationAssembly, string pssessionConfigurationTypeName) { try { Type type = TypeLoader.LoadType(pssessionConfigurationAssembly, pssessionConfigurationTypeName); if (type != null) { this.sessionConfiguration = type.Assembly.CreateInstance(type.FullName) as PSSessionConfiguration; if (this.sessionConfiguration == null) { throw new ArgumentException(ExceptionHelpers.GetExceptionMessage(Resources.PSSessionConfigurationCreationFailed, new object[0])); } } else { object[] objArray = new object[2]; objArray[0] = pssessionConfigurationTypeName; objArray[1] = pssessionConfigurationAssembly; throw new ArgumentException(ExceptionHelpers.GetExceptionMessage(Resources.TypeLoadFromAssebmlyFailed, objArray), "pssessionConfigurationTypeName"); } } catch (Exception exception1) { Exception exception = exception1; TraceHelper.Current.PSSessionConfigurationLoadingFailed(pssessionConfigurationAssembly, exception.ToTraceMessage("Exception")); if (!exception.IsSevereException()) { throw new TypeLoadException(pssessionConfigurationTypeName, pssessionConfigurationAssembly, Utils.GetBaseBinDirectory(pssessionConfigurationAssembly), exception); } else { throw; } } TraceHelper.Current.PSSessionConfigurationLoadedSuccessfully(pssessionConfigurationTypeName); }
public IslandActor(Configuration.Implementation.PeaSettings settings, int seed) { var actorPathName = Self.Path.ToString(); Engine = IslandEngineFactory.Create(actorPathName, settings, seed); IslandKey = CreateIslandKey(settings); Engine.Algorithm.SetEvaluationCallback(Evaluate); var evaluatorsCount = Engine.Parameters.GetInt(ParameterNames.EvaluatorsCount); if (evaluatorsCount > 4) { Evaluator = Context.ActorOf(EvaluationSupervisorActor.CreateProps(IslandKey, settings.Evaluation, Engine.Parameters)); } else { LocalEvaluator = (EvaluationBase)TypeLoader.CreateInstance(settings.Evaluation, Engine.Parameters); } Receive <InitEvaluator>(m => InitEvaluator(m)); Receive <Continue>(m => RunOneStep()); Receive <Travel>(m => TravelersArrived(m)); Receive <End>(m => End()); }
public static void LoadFromDifferentLocationsMvidMismatch() { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.Equal(TestData.s_SimpleAssemblyName, a.GetName().FullName); Guid mvid = a.ManifestModule.ModuleVersionId; Assert.Equal(TestData.s_SimpleAssemblyMvid, mvid); } using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_SimpleAssemblyRecompiledImage); Assert.Equal(TestData.s_SimpleAssemblyName, a.GetName().FullName); Guid mvid = a.ManifestModule.ModuleVersionId; Assert.Equal(TestData.s_SimpleAssemblyRecompiledMvid, mvid); } using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assert.Throws <FileLoadException>(() => tl.LoadFromByteArray(TestData.s_SimpleAssemblyRecompiledImage)); } }
/// <summary> /// Main entry point for the compiler. /// </summary> /// <param name="args">The command line arguments.</param> internal static void Main(string[] args) { Console.Write("Initializing loader tool runtime..."); var runtime = new LoaderToolRuntime(); Console.WriteLine(" done."); Console.Write("Loading mscorlib.dll..."); IMetadataModule module = runtime.AssemblyLoader.Load(@"/Library/Frameworks/Mono.framework/Versions/2.6.1/lib/mono/2.0/mscorlib.dll"); Console.WriteLine(" done."); Console.WriteLine("Running new TypeLoader..."); TypeLoader loader = new TypeLoader(module); foreach (RuntimeType type in loader.LoadTypes()) { try { Console.WriteLine("\t{0}", type.FullName); } catch (Exception e) { Console.Write("\tException processing "); try { Console.Write(type.FullName); } catch { Console.WriteLine("(unknown)"); } Console.WriteLine(e); break; } } Console.WriteLine("Done."); }
using System.Text;
private ContractDescription ResolveIMetadataExchangeToContract() { TypeLoader loader = new TypeLoader(); return loader.LoadContractDescription(typeof(IMetadataExchange)); }
private static ITypeLoader CreateDefaultTypeLoader() { var typeLoader = new TypeLoader(); typeLoader.AddTypes(() => new[] { typeof(FakePart) }); return typeLoader; }
public void Ctor_injection_test() { var loader = new TypeLoader(); loader.AddTypes(() => Assembly.GetExecutingAssembly().GetExportedTypes()); var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new ConventionCatalog(new[] { new CtorRegistry() }, loader)); var instance = new ConventionPart<InjectedHost>(); var batch = new CompositionBatch(); batch.AddPart(instance); var container = new CompositionContainer(catalog); container.Compose(batch); instance.Imports[0].Widgets.Count().ShouldEqual(2); }
public void TargetName_should_TestExpectation() { var loader = new TypeLoader(); loader.AddTypes(() => Assembly.GetExecutingAssembly().GetExportedTypes()); var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); catalog.Catalogs.Add(new ConventionCatalog(new[] { new MyRegistry() }, loader)); var instance = new Host(); var batch = new CompositionBatch(); batch.AddPart(instance); var container = new CompositionContainer(catalog); container.Compose(batch); instance.Widgets.Count().ShouldEqual(2); }
public static ContractDescription GetContract(Type contractType, object serviceImplementation) { if (contractType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); if (serviceImplementation == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceImplementation"); TypeLoader typeLoader = new TypeLoader(); Type serviceType = serviceImplementation.GetType(); ContractDescription description = typeLoader.LoadContractDescription(contractType, serviceType, serviceImplementation); return description; }
public static MessageDescription CreateFromMessageContract(OperationDescription operation, bool isResponse, MessageDirection direction, string overridingAction, Type messageContractType) { string action = overridingAction ?? NamingHelper.GetMessageAction(operation, isResponse); TypeLoader loader = new TypeLoader(); return loader.CreateTypedMessageDescription(messageContractType, null, null, operation.DeclaringContract.Namespace, action, direction); }
private ServiceEndpoint CreateServiceEndpoint() { TypeLoader loader = new TypeLoader(); ContractDescription contractDescription = loader.LoadContractDescription(contractType); ServiceEndpoint endpoint = new ServiceEndpoint(contractDescription); if (address != null) endpoint.Address = new EndpointAddress(new Uri(address), identity); if (binding != null) endpoint.Binding = binding; if (configurationName != null) { ConfigLoader configLoader = new ConfigLoader(); configLoader.LoadChannelBehaviors(endpoint, configurationName); } ComPlusTypedChannelBuilderTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationTypedChannelBuilderLoaded, SR.TraceCodeComIntegrationTypedChannelBuilderLoaded, contractType, binding); return endpoint; }
ContractDescription ResolveIMetadataExchangeToContract() { // Use ServiceModel's TypeLoader to load the IMetadataExchange contract TypeLoader typeLoader = new TypeLoader(); return typeLoader.LoadContractDescription(typeof(IMetadataExchange)); }