public Type[] GetControllerTypes(IEnumerable <ServiceInfo> services)
        {
            var result = _webApiGenerator.Generate(services);

            DynamicAssembly assembly = new DynamicAssembly(_eventHub);

            assembly.AppendSourceUnits(result);
            assembly.AddWebApiReferences();

            AssemblyPurpose p = AssemblyPurpose.Handlers | AssemblyPurpose.Commands | AssemblyPurpose.Queries |
                                AssemblyPurpose.Results;

            assembly.AddReferenceFrom(_dynamicPool.Where(x => (x.Purpose & p) > 0).Select(x => x.Assembly));

            _dynamicPool.AddOrReplace(assembly);

            assembly.Compile();


            var controllerTypes = assembly.Assembly.GetTypes()
                                  .Where(x => typeof(ControllerBase).IsAssignableFrom(x))
                                  .ToArray();

            return(controllerTypes);
        }
        public Assembly BuildAssembly(string assemblyName)
        {
            _assembly = new DynamicAssembly();

            AddSchemaAttribute();

            foreach (var csdl in _csdlArtifacts)
            {
                BuildTypes(csdl);
            }

            var assemblyBuilder = _assembly.Compile(new AssemblyName(assemblyName));

            // add the assembly to the list for assembly resolution
            _createdAssemblies.Add(assemblyBuilder);

            // EdmRelationshipAttributes require real Clr types so it adds these
            // attributes using CustomAttributeBuilder on already created assembly
            foreach (var csdl in _csdlArtifacts)
            {
                AddRelationshipAttributes(csdl, (AssemblyBuilder)assemblyBuilder);
            }

            return(assemblyBuilder);
        }
Exemple #3
0
        public void Set_throws_in_EDMX_mode_only_when_used_if_type_is_POCO_but_is_in_attributed_assembly_Dev10_883031()
        {
            var assembly = new DynamicAssembly();

            assembly.HasAttribute(new EdmSchemaAttribute());
            assembly.DynamicStructuralType("PocoEntity").Property("Id").HasType(typeof(int));
            assembly.DynamicStructuralType("EocoEntity").Property("Id").HasType(typeof(int)).HasAttribute(
                new EdmEntityTypeAttribute());
            assembly.Compile(new AssemblyName("MixedPocoEocoAssembly"));

            var pocoType     = assembly.Types.Single(t => t.Name == "PocoEntity");
            var setMethod    = typeof(DbContext).GetDeclaredMethod("Set", Type.EmptyTypes).MakeGenericMethod(pocoType);
            var createMethod = typeof(DbSet <>).MakeGenericType(pocoType)
                               .GetDeclaredMethods()
                               .Single(m => m.Name == "Create" && !m.IsGenericMethodDefinition);

            var edmItemCollection   = new EdmItemCollection(new[] { XDocument.Parse(PregenContextEdmx.Csdl).CreateReader() });
            var storeItemCollection = new StoreItemCollection(new[] { XDocument.Parse(PregenContextEdmx.Ssdl).CreateReader() });

            IList <EdmSchemaError> errors;
            var storageMappingItemCollection = StorageMappingItemCollection.Create(
                edmItemCollection,
                storeItemCollection,
                new[] { XDocument.Parse(PregenContextEdmx.Msl).CreateReader() },
                null,
                out errors);

            var workspace = new MetadataWorkspace(
                () => edmItemCollection,
                () => storeItemCollection,
                () => storageMappingItemCollection);

            using (var context = new DbContext(
                       new EntityConnection(workspace, new SqlConnection(), entityConnectionOwnsStoreConnection: true),
                       contextOwnsConnection: true))
            {
                var set = setMethod.Invoke(context, null);
                Assert.Throws <InvalidOperationException>(
                    () =>
                {
                    try
                    {
                        createMethod.Invoke(set, null);
                    }
                    catch (TargetInvocationException tie)
                    {
                        throw tie.InnerException;
                    }
                }).ValidateMessage(
                    "DbSet_PocoAndNonPocoMixedInSameAssembly",
                    "PocoEntity");
            }
        }
Exemple #4
0
        public async Task WhenACommandhandlerIsGenerated(string handlerName)
        {
            var result = await this._applicationExecutor.ExecuteAsync <ISqlCqrsGenerator, SourceUnitCollection>(x => x.Generate(0));

            DynamicAssembly assembly = new DynamicAssembly(NSubstitute.Substitute.For <IEventHub>());

            assembly.AppendSourceUnits(result);
            assembly.AddDefaultReferences();

            TypeCompiler compiler = new TypeCompiler();

            _context["assembly"] = assembly.Compile(compiler);

            assembly.Assembly.GetTypes().Should().Contain(x => x.Name == handlerName);
        }
        private static Type CreateWeakProviderType()
        {
            var assembly = new DynamicAssembly();
            var dynamicType = assembly.DynamicType("WeakProviderFactory").HasBaseClass(typeof(DbProviderFactory));
            dynamicType.CtorAccess = MemberAccess.Public;
            dynamicType.Field("Instance").HasType(dynamicType).IsStatic().IsInstance();
            var compiledAssembly = assembly.Compile(new AssemblyName("ProviderAssembly"));

            // We need this so that Type.GetType() used in DbProviderFactories.GetFactory will work for
            // the dynamic assembly. In other words, this is only needed for the test code to work.
            AppDomain.CurrentDomain.AssemblyResolve +=
                (sender, args) => args.Name.StartsWith("ProviderAssembly") ? compiledAssembly : null;

            return assembly.GetType("WeakProviderFactory");
        }
        public async Task WhenIInvokeWithMethodAndArgument(string controllerTypeName, string methodName, string requestType, Table table)
        {
            var json = string.Join(Environment.NewLine, table.CreateSet <JsonScript>().Select(x => x.Json));

            DynamicAssembly assembly = null;

            ServiceInfo[] services = this._applicationExecutor.Execute <IServiceMetadataProvider, IEnumerable <ServiceInfo> >(x => x.GetServices()).ToArray();
            var           result   = await this._applicationExecutor.ExecuteAsync <IWebApiGenerator, SourceUnitCollection>(async x => x.Generate(services));

            this._applicationExecutor.Execute <IDynamicTypePool>(pool =>
            {
                if (pool.CanMerge)
                {
                    assembly = pool.Merge(result);
                }
                else
                {
                    assembly = new DynamicAssembly(NSubstitute.Substitute.For <IEventHub>());
                    pool.AddOrReplace(assembly);
                    assembly.AppendSourceUnits(result);
                    assembly.AddWebApiReferences();
                    assembly.AddReferenceFromTypes(_data.Types.Values);
                    assembly.Compile();
                }
            });


            var controllerType = assembly.Load(assembly.SourceUnits.Single(x => x.FullName.Contains("Controller")).FullName);

            _applicationExecutor.Execute(controllerType, controller =>
            {
                var createUserObj = JsonConvert.DeserializeObject(json, assembly.Load("Test.WebApi", requestType));
                var parameters    = new List <object>()
                {
                    createUserObj
                };
                if (_data.Id != Guid.Empty)
                {
                    parameters.Insert(0, _data.Id);
                }
                Task task = (Task)controllerType.GetMethod(methodName).Invoke(controller, parameters.ToArray());
                task.GetAwaiter().GetResult();
                dynamic dTask      = task;
                var response       = dTask.Result;
                _data.ActualResult = response;
            });
        }
        protected static Type CreateWeakProviderType(Type baseProviderType, string assemblyName)
        {
            var assembly    = new DynamicAssembly();
            var dynamicType =
                assembly.DynamicStructuralType("WeakProviderFactory").HasBaseClass(baseProviderType);

            dynamicType.CtorAccess = MemberAccess.Public;
            dynamicType.Field("Instance").HasType(dynamicType).IsStatic().IsInstance();
            var compiledAssembly = assembly.Compile(new AssemblyName(assemblyName));

            // We need this so that Type.GetType() used in DbProviderFactories.GetFactory will work for
            // the dynamic assembly. In other words, this is only needed for the test code to work.
            AppDomain.CurrentDomain.AssemblyResolve +=
                (sender, args) => args.Name.StartsWith(assemblyName) ? compiledAssembly : null;

            return(assembly.GetType("WeakProviderFactory"));
        }
Exemple #8
0
        private async Task CompileAndLoad(Workspace[] workspaces)
        {
            var myWorksSpace = await FindOrCreate(workspaces);

            try
            {
                var result = await _sqlCqrsGenerator.Generate(0);

                if (result.Any())
                {
                    if (_dynamicPool.All(x => x.SourceUnits.SrcHash != result.SrcHash))
                    {
                        _logger.Info("New metadata model loaded from database with {hash} hash.", result.SrcHash);

                        DynamicAssembly assembly = new DynamicAssembly(_eventHub);
                        assembly.AddDefaultReferences();
                        assembly.AppendSourceUnits(result);
                        assembly.Compile();

                        _dynamicPool.AddOrReplace(assembly);
                        _metadataProvider.Clear();
                        _metadataProvider.Discover(assembly.Assembly);

                        // TODO: Refactor this and from Load
                        await _eventHub.Publish(new AssemblyLoadedEvent()
                        {
                            Assembly = assembly.Assembly, Purpose = assembly.Purpose
                        });

                        var c = await _repo.Query <Model.Compilation>()
                                .FirstAsync(x => x.Hash == assembly.SrcHash);

                        c.Workspace         = myWorksSpace;
                        myWorksSpace.Status = WorkspaceStatus.Running;
                        c.LoadedAt          = DateTimeOffset.Now;
                        await _repo.CommitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                myWorksSpace.Status = WorkspaceStatus.Error;
                myWorksSpace.Error  = ex.Message;
                await _repo.CommitChanges();
            }
        }
            public void ImplicitLoadAssemblyForType_checks_calling_schema_assembly_and_references_for_views_if_type_assembly_filtered()
            {
                var assembly = new DynamicAssembly();

                assembly.HasAttribute(new EdmSchemaAttribute());
                var callingAssembly = assembly.Compile(new AssemblyName("WithEdmSchemaAttribute"));

                var mockCache = new Mock <IViewAssemblyCache>();
                var workspace = new MetadataWorkspace(
                    () => new EdmItemCollection(Enumerable.Empty <XmlReader>()),
                    () => null,
                    () => null,
                    () => new ObjectItemCollection(mockCache.Object));

                workspace.ImplicitLoadAssemblyForType(typeof(object), callingAssembly);

                mockCache.Verify(m => m.CheckAssembly(typeof(object).Assembly, It.IsAny <bool>()), Times.Never());
                mockCache.Verify(m => m.CheckAssembly(callingAssembly, true), Times.Once());
            }
            public void ImplicitLoadAssemblyForType_checks_calling_schema_assembly_and_references_for_views_if_type_assembly_filtered()
            {
                var assembly = new DynamicAssembly();
                assembly.HasAttribute(new EdmSchemaAttribute());
                var callingAssembly = assembly.Compile(new AssemblyName("WithEdmSchemaAttribute"));

                var mockCache = new Mock<IViewAssemblyCache>();
                var workspace = new MetadataWorkspace(
                    () => new EdmItemCollection(Enumerable.Empty<XmlReader>()),
                    () => null,
                    () => null,
                    () => new ObjectItemCollection(mockCache.Object));

                workspace.ImplicitLoadAssemblyForType(typeof(object), callingAssembly);

                mockCache.Verify(m => m.CheckAssembly(typeof(object).Assembly, It.IsAny<bool>()), Times.Never());
                mockCache.Verify(m => m.CheckAssembly(callingAssembly, true), Times.Once());
            }