/// <summary>
        /// 为IHttpService创建服务实现
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection BuildProxy(this IServiceCollection services, CodeGeneratorOption option = default)
        {
            var configuration = services.ServiceConfigure();
            var types         = new Collection <Type>();

            foreach (var config in configuration)
            {
                foreach (var type in config.ForTypes)
                {
                    if (!type.IsInterface)
                    {
                        continue;
                    }
                    if (typeof(IHttpService).IsAssignableFrom(type) ||
                        (type.GetCustomAttribute <HttpServiceAttribute>()?.GenerateProxy ?? false))
                    {
                        types.Add(type);
                    }
                }
            }
            var assembly = ProxyGenerator.Generate(types.ToArray(), option);

            foreach (var type in types)
            {
                var proxyType = assembly.ExportedTypes.First(x => type.IsAssignableFrom(x));
                services.AddTransient(type, proxyType);
            }
            return(services);
        }
        public void VoidIsNotAValidTypeWhenGeneratingProxy()
        {
            //Arrange
            var generator = new ProxyGenerator();

            //Act + Assert
            Expect.ArgumentOutOfRangeException(() => generator.Generate(typeof(void)));
        }
        public void TypeIsRequiredWhenGeneratingProxy()
        {
            //Arrange
            var generator = new ProxyGenerator();

            //Act + Assert
            Expect.ArgumentNullException(() => generator.Generate(null));
        }
        public void VoidIsNotAValidTypeWhenGeneratingProxy()
        {
            //Arrange
            var generator = new ProxyGenerator();

            //Act + Assert
            Expect.ArgumentOutOfRangeException(() => generator.Generate(typeof(void)));
        }
        public void TypeIsRequiredWhenGeneratingProxy()
        {
            //Arrange
            var generator = new ProxyGenerator();

            //Act + Assert
            Expect.ArgumentNullException(() => generator.Generate(null));
        }
Beispiel #6
0
        private TCurrentPageObjectType CreateOrReturnProxy <TCurrentPageObjectType>() where TCurrentPageObjectType : class
        {
            if (CurrentProxy == null || CurrentProxy.GetType().BaseType != typeof(TCurrentPageObjectType))
            {
                CurrentProxy = ProxyGenerator.Generate <TCurrentPageObjectType>(Configuration);
            }

            return((TCurrentPageObjectType)CurrentProxy);
        }
        public void ProxyImplementsIDynamicProxy()
        {
            //Arrange
            var generator = new ProxyGenerator();

            //Act
            var result = generator.Generate(typeof(ITestInterfaceExtended));

            //Assert
            Assert.IsTrue(result.Code.Contains("BaseConfiguration IHaveConfiguration.Configuration"));
        }
        public void ProxyImplementsIDynamicProxy()
        {
            //Arrange
            var generator = new ProxyGenerator();

            //Act
            var result = generator.Generate(typeof(ITestInterfaceExtended));

            //Assert
            Assert.IsTrue(result.Code.Contains("BaseConfiguration IHaveConfiguration.Configuration"));
        }
        public async Task <string> Generate(string code)
        {
            var generator = new ProxyGenerator();
            var models    = await GetModels(code);

            var syntaxTree      = models.syntaxTree;
            var semanticModel   = models.semanticModel;
            var classToDecorate = models.syntaxTree.DescendantNodes().OfType <ClassDeclarationSyntax>().ToList();

            if (classToDecorate.Count == 0)
            {
                return("No class found to decorate");
            }

            NamespaceDeclarationSyntax oldNamespace = classToDecorate[0].Parent as NamespaceDeclarationSyntax;
            NamespaceDeclarationSyntax newNamespace = oldNamespace;
            var classList = new List <MemberDeclarationSyntax>();

            foreach (var classModel in classToDecorate)
            {
                var classSemantic = semanticModel.GetDeclaredSymbol(classModel);


                if (HasBaseType(classSemantic, "DeviceActor"))
                {
                    // ExternAliasDirectiveSyntax - Represents an ExternAlias directive syntax, e.g. "extern alias MyAlias;" with specifying "/r:MyAlias=SomeAssembly.dll " on the compiler command line.

                    var proxy  = new TransformationContext(classModel, semanticModel, models.compilation, "", null, null);
                    var result = generator.Generate(proxy);

                    foreach (var res in result.Members)
                    {
                        ConsoleEx.WriteOKLine($"{classSemantic.Name}:");
                        ConsoleEx.Write($"{res.NormalizeWhitespace().ToFullString()}");

                        classList.Add(res);
                    }
                }
            }


            foreach (var proxyClass in classList)
            {
                newNamespace = newNamespace.AddMembers(proxyClass);
            }

            syntaxTree = syntaxTree.ReplaceNode(oldNamespace, newNamespace);

            Veryfy(syntaxTree);

            return(syntaxTree.NormalizeWhitespace().ToFullString());
        }
        public void MethodsFromDerivedInterfacesShouldAlsoBeProxied()
        {
            //Arrange
            var generator = new ProxyGenerator();

            //Act
            var result = generator.Generate(typeof(ITestInterfaceExtended));

            //Assert
            Assert.IsTrue(result.Code.Contains("public System.Boolean Baz()"));
            Assert.IsTrue(result.Code.Contains("public System.Int32 get_Bar()"));
            Assert.IsTrue(result.Code.Contains("public void Foo()"));
        }
Beispiel #11
0
        private static ProxyInstantiator BuildInstantiator(Type type)
        {
            var proxyGenerator       = new ProxyGenerator();
            var generatedClassResult = proxyGenerator.Generate(type);

            var hostingContainer = new HostingContainer();
            var scriptEngine     = new ScriptEngine(GetRequiredAssemblies(type));
            var scriptSession    = Session.Create(hostingContainer);

            scriptEngine.Execute(generatedClassResult.Code, scriptSession);
            scriptEngine.Execute(@"ProxyInstantiator = new ProxyInstantiator((innerTarget,configuration) => new " + generatedClassResult.GeneratedClassName + "((" + type.GetFullName() + ")innerTarget, configuration));", scriptSession);
            return(hostingContainer.ProxyInstantiator);
        }
        public void GeneratorTest()
        {
            var types    = new Type[] { typeof(IGenericService <,>), typeof(ITestService), typeof(ITokenService), typeof(IUserService) };
            var watch    = Stopwatch.StartNew();
            var assembly = ProxyGenerator.Generate(types);

            watch.Stop();

            Trace.TraceInformation("动态生成用时:{0}ms", watch.ElapsedMilliseconds);
            var generateTypes = assembly.ExportedTypes;

            Assert.Equal(types.Length, generateTypes.Count());
        }
        public void MethodsFromDerivedInterfacesShouldAlsoBeProxied()
        {
            //Arrange
            var generator = new ProxyGenerator();

            //Act
            var result = generator.Generate(typeof(ITestInterfaceExtended));

            //Assert
            Assert.IsTrue(result.Code.Contains("public System.Boolean Baz()"));
            Assert.IsTrue(result.Code.Contains("public System.Int32 get_Bar()"));
            Assert.IsTrue(result.Code.Contains("public void Foo()"));
        }
Beispiel #14
0
        private static object CreateWrappedOrProxiedItem(object sourceItem, Type ofType, PassengerConfiguration configuration)
        {
            var itemToAdd = sourceItem;

            if (ofType.IsAPassengerElement())
            {
                itemToAdd = WrapIntoPassengerElement(sourceItem, ofType);
            }

            if (ofType.IsPageComponent())
            {
                itemToAdd = ProxyGenerator.Generate(ofType, configuration);
            }

            return(itemToAdd);
        }
Beispiel #15
0
        static void Run(string[] args)
        {
            if (args.Length != 2)
            {
                throw new PrettyException(@"Please call the tool like this:

    Cirqus.TypeScript <path-to-DLL> <output-file>

where <path-to-DLL> should point to an assembly containing all of your commands,
and <output-file> should be the directory in which you want the generated
'api.ts' to be put.");
            }

            var sourceDll           = args[0];
            var destinationFilePath = args[1];

            if (!File.Exists(sourceDll))
            {
                throw new FileNotFoundException(string.Format("Could not find source DLL {0}", sourceDll));
            }

            var destinationDirectory = Path.GetDirectoryName(destinationFilePath);

            if (destinationDirectory != null &&
                !Directory.Exists(destinationDirectory))
            {
                Console.WriteLine("Creating directory {0}", destinationDirectory);
                Directory.CreateDirectory(destinationDirectory);
            }

            var proxyGenerator = new ProxyGenerator();

            var results = proxyGenerator.Generate(sourceDll).ToList();

            Console.WriteLine("Writing files");
            foreach (var result in results)
            {
                result.WriteTo(destinationFilePath);
            }
        }
Beispiel #16
0
        private void btGenerator_Click(object sender, EventArgs e)
        {
            ProxyGenerator <ITestContract> g1 = new ProxyGenerator <ITestContract>();

            g1.Generate("ITestContractDir");
            File.Copy("ITestContractDir\\TestContractAbstractClientProxy.cs", "..\\..\\RemotingClient\\TestContractAbstractClientProxy.cs", true);
            File.Copy("ITestContractDir\\TestContractAbstractServiceProxy.cs", "..\\..\\RemotingService\\TestContractAbstractServiceProxy.cs", true);
            File.Copy("ITestContractDir\\TestContractClientImpl.cs", "..\\..\\RemotingClient\\TestContractClientImpl.cs", true);
            File.Copy("ITestContractDir\\TestContractServiceImpl.cs", "..\\..\\RemotingService\\TestContractServiceImpl.cs", true);

            ProxyGenerator <ITestContractSimple> g2 = new ProxyGenerator <ITestContractSimple>();

            g2.Generate("ITestContractSimpleDir");
            File.Copy("ITestContractSimpleDir\\TestContractSimpleAbstractClientProxy.cs", "..\\..\\RemotingClient\\TestContractSimpleAbstractClientProxy.cs", true);
            File.Copy("ITestContractSimpleDir\\TestContractSimpleAbstractServiceProxy.cs", "..\\..\\RemotingService\\TestContractSimpleAbstractServiceProxy.cs", true);
            File.Copy("ITestContractSimpleDir\\TestContractSimpleClientImpl.cs", "..\\..\\RemotingClient\\TestContractSimpleClientImpl.cs", true);
            File.Copy("ITestContractSimpleDir\\TestContractSimpleServiceImpl.cs", "..\\..\\RemotingService\\TestContractSimpleServiceImpl.cs", true);

            ProxyGenerator <ITestContractStream> g3 = new ProxyGenerator <ITestContractStream>();

            g3.Generate("ITestContractStreamDir");
            File.Copy("ITestContractStreamDir\\TestContractStreamAbstractClientProxy.cs", "..\\..\\RemotingClient\\TestContractStreamAbstractClientProxy.cs", true);
            File.Copy("ITestContractStreamDir\\TestContractStreamAbstractServiceProxy.cs", "..\\..\\RemotingService\\TestContractStreamAbstractServiceProxy.cs", true);
            File.Copy("ITestContractStreamDir\\TestContractStreamClientImpl.cs", "..\\..\\RemotingClient\\TestContractStreamClientImpl.cs", true);
            File.Copy("ITestContractStreamDir\\TestContractStreamServiceImpl.cs", "..\\..\\RemotingService\\TestContractStreamServiceImpl.cs", true);

            ProxyGenerator <ITestSingleCall> g4 = new ProxyGenerator <ITestSingleCall>();

            g4.Generate("ITestSingleCallDir");
            File.Copy("ITestSingleCallDir\\TestSingleCallClientImpl.cs", "..\\..\\RemotingClient\\TestSingleCallClientImpl.cs", true);
            File.Copy("ITestSingleCallDir\\TestSingleCallServiceImpl.cs", "..\\..\\RemotingService\\TestSingleCallServiceImpl.cs", true);

            ProxyGenerator <ITestSingleton> g5 = new ProxyGenerator <ITestSingleton>();

            g5.Generate("ITestSingletonDir");
            File.Copy("ITestSingletonDir\\TestSingletonClientImpl.cs", "..\\..\\RemotingClient\\TestSingletonClientImpl.cs", true);
            File.Copy("ITestSingletonDir\\TestSingletonServiceImpl.cs", "..\\..\\RemotingService\\TestSingletonServiceImpl.cs", true);
        }
Beispiel #17
0
        public void Setup()
        {
            // It's hard to hand construct a proxy - so we'll go via the proxy generator.
            _fakeDriver = new Mock <IDriverBindings>();
            _fakeDriver.Setup(x => x.Substitutes).Returns(new List <DriverBindings.TypeSubstitution>
            {
                new DriverBindings.TypeSubstitution(typeof(InterceptedType.SubbedType),
                                                    () => new InterceptedType.SubbedType {
                    Val = "Hi"
                })
            });
            _fakeDriver.Setup(x => x.NavigationHandlers).Returns(new List <DriverBindings.IHandle>
            {
                new DriverBindings.Handle <IdAttribute>((s, d) => "an id string"),
                new DriverBindings.Handle <LinkTextAttribute>((s, d) => "a text string"),
                new DriverBindings.Handle <CssSelectorAttribute>((s, d) => new FakeWebElement(s))
            });

            _cfg = new PassengerConfiguration {
                Driver = _fakeDriver.Object
            };
            _proxy = ProxyGenerator.Generate <InterceptedType>(_cfg);
        }
Beispiel #18
0
        static void Run(string[] args)
        {
            if (args.Length != 2)
            {
                throw new PrettyException(@"Please call the tool like this:

    d60.Cirqus.TsClient <path-to-DLL> <output-directory>

where <path-to-DLL> should point to an assembly containing all of your commands,
and <output-directory> should be the directory in which you want the generated
'commands.ts' and 'commandProcessor.ts' to be put.");
            }

            var sourceDll            = args[0];
            var destinationDirectory = args[1];

            if (!File.Exists(sourceDll))
            {
                throw new FileNotFoundException(string.Format("Could not find source DLL {0}", sourceDll));
            }

            if (!Directory.Exists(destinationDirectory))
            {
                Writer.Print("Creating directory {0}", destinationDirectory);
                Directory.CreateDirectory(destinationDirectory);
            }

            var proxyGenerator = new ProxyGenerator(sourceDll, Writer);

            var results = proxyGenerator.Generate().ToList();

            Writer.Print("Writing files");
            foreach (var result in results)
            {
                result.WriteTo(destinationDirectory);
            }
        }