Exemplo n.º 1
0
        private static async Task MainAsync(string[] args)
        {
            try
            {
                IpcServiceClient <IComputingService> computingClient = new IpcServiceClientBuilder <IComputingService>()
                                                                       .UseNamedPipe("pipeName")
                                                                       .Build();

                IpcServiceClient <ISystemService> systemClient = new IpcServiceClientBuilder <ISystemService>()
                                                                 .UseTcp(IPAddress.Loopback, 45684)
                                                                 .Build();

                // test 1: call IPC service method with primitive types
                float result1 = await computingClient.InvokeAsync(x => x.AddFloat(1.23f, 4.56f));

                Console.WriteLine($"[TEST 1] sum of 2 floating number is: {result1}");

                // test 2: call IPC service method with complex types
                ComplexNumber result2 = await computingClient.InvokeAsync(x => x.AddComplexNumber(
                                                                              new ComplexNumber(0.1f, 0.3f),
                                                                              new ComplexNumber(0.2f, 0.6f)));

                Console.WriteLine($"[TEST 2] sum of 2 complexe number is: {result2.A}+{result2.B}i");

                // test 3: call IPC service method with an array of complex types
                ComplexNumber result3 = await computingClient.InvokeAsync(x => x.AddComplexNumbers(new[]
                {
                    new ComplexNumber(0.5f, 0.4f),
                    new ComplexNumber(0.2f, 0.1f),
                    new ComplexNumber(0.3f, 0.5f),
                }));

                Console.WriteLine($"[TEST 3] sum of 3 complexe number is: {result3.A}+{result3.B}i");

                // test 4: call IPC service method without parameter or return
                await systemClient.InvokeAsync(x => x.DoNothing());

                Console.WriteLine($"[TEST 4] invoked DoNothing()");

                // test 5: call IPC service method with enum parameter
                string text = await systemClient.InvokeAsync(x => x.ConvertText("hEllO woRd!", TextStyle.Upper));

                Console.WriteLine($"[TEST 5] {text}");

                // test 6: call IPC service method returning GUID
                Guid generatedId = await systemClient.InvokeAsync(x => x.GenerateId());

                Console.WriteLine($"[TEST 6] generated ID is: {generatedId}");

                // test 7: call IPC service method with byte array
                byte[] input    = Encoding.UTF8.GetBytes("Test");
                byte[] reversed = await systemClient.InvokeAsync(x => x.ReverseBytes(input));

                Console.WriteLine($"[TEST 7] reversed bytes are: {Convert.ToBase64String(reversed)}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 2
0
        public static async Task Main(string[] args)
        {
            var pipeClient = new IpcServiceClientBuilder <ICalculatorService>()
                             .UseNamedPipe("pipeName") // or .UseTcp(IPAddress.Loopback, 45684) to invoke using TCP
                             .Build();

            var result = await pipeClient.InvokeAsync(x => x.Execute(new Calculation()
            {
                Operand1 = 1,
                Operand2 = 2,
                Opertor  = "+"
            }));

            Console.WriteLine(result.Result);

            var tcpClient = new IpcServiceClientBuilder <ICalculatorService>()
                            .UseTcp(IPAddress.Loopback, 45684)
                            .Build();

            result = await tcpClient.InvokeAsync(x => x.Execute(new Calculation()
            {
                Operand1 = 1,
                Operand2 = 2,
                Opertor  = "+"
            }));

            Console.WriteLine(result.Result);
        }
Exemplo n.º 3
0
        public static void Main()
        {
            var client = new IpcServiceClientBuilder <IBmsService>()
                         .UseNamedPipe("pipeName") // or .UseTcp(IPAddress.Loopback, 45684) to invoke using TCP
                         .Build();

            GoAsync(client).Wait();
        }
Exemplo n.º 4
0
        static async Task <int> Main()
        {
            try
            {
                var config = new ConfigurationBuilder()
                             .AddJsonFile("appsettings.json")
                             .AddJsonFile("appsettings.Development.json", true)
                             .Build();

                var client = new IpcServiceClientBuilder <Api.IFtpServerHost>()
                             .UseNamedPipe("ftpserver")
                             .Build();

                var simpleModuleInfoNames = await client.InvokeAsync(host => host.GetSimpleModules())
                                            .ConfigureAwait(false);

                var extendedModuleInfoName = await client.InvokeAsync(host => host.GetExtendedModules())
                                             .ConfigureAwait(false);

                var services = new ServiceCollection()
                               .AddLogging(builder => builder.AddConfiguration(config.GetSection("Logging")).AddConsole())
                               .AddSingleton(client)
                               .AddSingleton <IShellStatus>(new ShellStatus(simpleModuleInfoNames, extendedModuleInfoName))
                               .Scan(
                    ts => ts
                    .FromAssemblyOf <FtpShellCommandAutoCompletion>()
                    .AddClasses(itf => itf.AssignableTo <ICommandInfo>(), true).As <ICommandInfo>()
                    .WithSingletonLifetime())
                               .AddSingleton <FtpShellCommandAutoCompletion>()
                               .AddSingleton <ServerShell>();

                var serviceProvider = services.BuildServiceProvider(true);

                var shell = serviceProvider.GetRequiredService <ServerShell>();
                await shell.RunAsync(CancellationToken.None)
                .ConfigureAwait(false);

                return(0);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return(1);
            }
        }
Exemplo n.º 5
0
        static async Task Main(string[] args)
        {
            // starting a server
            new Thread(StartServer).Start();

            // sending requests to the server
            IpcServiceClient <IComputingService> client = new IpcServiceClientBuilder <IComputingService>()
                                                          .UseTcp(IPAddress.Loopback, 45684)
                                                          .Build();

            float result = await client.InvokeAsync(x => x.AddFloat(1.23f, 4.56f));

            Console.WriteLine($"AddFloat result is {result}");

            var stream = await client.InvokeAsync(x => x.GetMemoryStream());

            Console.WriteLine($"Length of stream is {stream.Length}");

            Console.ReadKey();
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Report(int?id)
        {
            if (id == null)
            {
                return(View("Index"));
            }

            var place = await _context.Places
                        .FirstOrDefaultAsync(m => m.ID == id);

            if (place != null)
            {
                // AwesomePDF.PDFGenerator generator = new AwesomePDF.PDFGenerator("PDF");
                // var result = generator.GeneratePDF(place.Name, place.Image, place.Text);
                // return new FileContentResult(System.IO.File.ReadAllBytes(result), "application/pdf");

                IpcServiceClient <IPDFService> client = new IpcServiceClientBuilder <IPDFService>().UseNamedPipe("generatePDF").Build();
                var result = await client.InvokeAsync(x => x.GeneratePDF(place.Name, place.Image, place.Text));

                return(new FileContentResult(System.IO.File.ReadAllBytes(result), "application/pdf"));
            }

            return(View("Index"));
        }
Exemplo n.º 7
0
        private static async Task RunTestsAsync(CancellationToken cancellationToken)
        {
            IpcServiceClient <IComputingService> computingClient = new IpcServiceClientBuilder <IComputingService>()
                                                                   .UseNamedPipe("pipeName")
                                                                   .Build();

            IpcServiceClient <ISystemService> systemClient = new IpcServiceClientBuilder <ISystemService>()
                                                             .UseTcp(IPAddress.Loopback, 45684)
                                                             .Build();

            // test 1: call IPC service method with primitive types
            float result1 = await computingClient.InvokeAsync(x => x.AddFloat(1.23f, 4.56f), cancellationToken);

            Console.WriteLine($"[TEST 1] sum of 2 floating number is: {result1}");

            // test 2: call IPC service method with complex types
            ComplexNumber result2 = await computingClient.InvokeAsync(x => x.AddComplexNumber(
                                                                          new ComplexNumber(0.1f, 0.3f),
                                                                          new ComplexNumber(0.2f, 0.6f)), cancellationToken);

            Console.WriteLine($"[TEST 2] sum of 2 complexe number is: {result2.A}+{result2.B}i");

            // test 3: call IPC service method with an array of complex types
            ComplexNumber result3 = await computingClient.InvokeAsync(x => x.AddComplexNumbers(new[]
            {
                new ComplexNumber(0.5f, 0.4f),
                new ComplexNumber(0.2f, 0.1f),
                new ComplexNumber(0.3f, 0.5f),
            }), cancellationToken);

            Console.WriteLine($"[TEST 3] sum of 3 complexe number is: {result3.A}+{result3.B}i", cancellationToken);

            // test 4: call IPC service method without parameter or return
            await systemClient.InvokeAsync(x => x.DoNothing(), cancellationToken);

            Console.WriteLine($"[TEST 4] invoked DoNothing()");

            // test 5: call IPC service method with enum parameter
            string text = await systemClient.InvokeAsync(x => x.ConvertText("hEllO woRd!", TextStyle.Upper), cancellationToken);

            Console.WriteLine($"[TEST 5] {text}");

            // test 6: call IPC service method returning GUID
            Guid generatedId = await systemClient.InvokeAsync(x => x.GenerateId(), cancellationToken);

            Console.WriteLine($"[TEST 6] generated ID is: {generatedId}");

            // test 7: call IPC service method with byte array
            byte[] input    = Encoding.UTF8.GetBytes("Test");
            byte[] reversed = await systemClient.InvokeAsync(x => x.ReverseBytes(input), cancellationToken);

            Console.WriteLine($"[TEST 7] reversed bytes are: {Convert.ToBase64String(reversed)}");

            // test 8: call IPC service method with generic parameter
            string print = await systemClient.InvokeAsync(x => x.Printout(DateTime.UtcNow), cancellationToken);

            Console.WriteLine($"[TEST 8] print out value: {print}");

            // test 9: call slow IPC service method
            await systemClient.InvokeAsync(x => x.SlowOperation(), cancellationToken);

            Console.WriteLine($"[TEST 9] Called slow operation");
        }
Exemplo n.º 8
0
        public static async Task Main(string[] args)
        {
            var host = new HostBuilder()
                       .ConfigureHostConfiguration(configHost =>
            {
                #region Host环境设置
                configHost.SetBasePath(Directory.GetCurrentDirectory());
                configHost.AddJsonFile("hostsettings.json", optional: true);
                configHost.AddEnvironmentVariables(prefix: "PREFIX_");
                configHost.AddCommandLine(args);
                #endregion
            })
                       .ConfigureAppConfiguration((hostContext, configApp) =>
            {
                #region  序配置
                configApp.AddJsonFile("appsettings.json", optional: true);
                configApp.AddJsonFile(
                    $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json",
                    optional: true);
                configApp.AddEnvironmentVariables(prefix: "PREFIX_");
                configApp.AddCommandLine(args);
                #endregion
            })
                       .ConfigureServices((hostContext, services) =>
            {
                //程序都在这里注入

                #region IRepository
                var infrastructureAssembly = Assembly.Load("ManjuuInfrastructure");
                var repositoryTypes        = infrastructureAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(IRepository).IsAssignableFrom(p));
                foreach (var item in repositoryTypes)
                {
                    foreach (var itemIntface in item.GetInterfaces())
                    {
                        if (typeof(IRepository) == itemIntface)
                        {
                            continue;
                        }
                        services.AddSingleton(itemIntface, item);
                    }
                }
                #endregion

                #region ICustomLog
                var commonAssembly = Assembly.Load("ManjuuCommon");
                var customLogTypes = commonAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(ICustomLog <NLog.ILogger>).IsAssignableFrom(p));
                foreach (var item in customLogTypes)
                {
                    foreach (var itemIntface in item.GetInterfaces())
                    {
                        if (typeof(ICustomLog <NLog.ILogger>) == itemIntface)
                        {
                            continue;
                        }
                        services.AddSingleton(itemIntface, item);
                    }
                }
                #endregion

                #region IApplication
                var applicationAssembly = Assembly.Load("ManjuuApplications");
                var applicationTypes    = applicationAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(IApplication).IsAssignableFrom(p));
                foreach (var item in applicationTypes)
                {
                    foreach (var itemIntface in item.GetInterfaces())
                    {
                        if (typeof(IApplication) == itemIntface)
                        {
                            continue;
                        }
                        //同一个请求下单例
                        services.AddScoped(itemIntface, item);
                    }
                }

                #endregion

                #region Quartz.Net
                services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>();   //注册ISchedulerFactory的实例。
                #endregion

                #region Ipc
                services.AddLogging(l =>
                {
                    l.AddConsole();
                    l.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
                })
                .AddIpc(action =>
                {
                    action.AddNamedPipe(pipeOpt =>
                    {
                        pipeOpt.ThreadCount = 2;
                    }).AddService <IDemoServiceContract, DemoServiceContract>()
                    .AddService <ICheckConfigServiceContract, PingServiceContract>()
                    .AddService <ICheckTargetServiceContract, PingServiceContract>();
                });


                #region Server
                var ipcServerHost = new IpcServiceHostBuilder(services.BuildServiceProvider())
                                    //.AddNamedPipeEndpoint<IDemoServiceContract>("demoEnpoint", "pipeName")
                                    .AddNamedPipeEndpoint <ICheckConfigServiceContract>("ConfigServiceEnpoint", "configPipe")
                                    .AddNamedPipeEndpoint <ICheckTargetServiceContract>("TargetServiceEnpoint", "targetPipe")
                                    //.AddTcpEndpoint<IDemoServiceContract>("demoTcpEndpoiint", IPAddress.Loopback, 2324)
                                    .Build();

                services.AddSingleton <IIpcServiceHost>(ipcServerHost);
                #endregion

                #region Client
                IpcServiceClient <ICheckConfigServiceContract> configClient = new IpcServiceClientBuilder <ICheckConfigServiceContract>()
                                                                              .UseNamedPipe("configPipe") // or .UseTcp(IPAddress.Loopback, 45684) to invoke using TCP
                                                                              .Build();
                IpcServiceClient <ICheckTargetServiceContract> targetJobClient = new IpcServiceClientBuilder <ICheckTargetServiceContract>()
                                                                                 .UseNamedPipe("targetPipe")
                                                                                 .Build();

                services.AddSingleton <IpcServiceClient <ICheckConfigServiceContract> >(configClient);

                services.AddSingleton <IpcServiceClient <ICheckTargetServiceContract> >(targetJobClient);
                #endregion

                #endregion

                NLogMgr.SetVariable(NLogMgr.ConfigurationVariables.Terrace, "检测工具");

                services.AddHostedService <PingHostedService>();
            })
                       .ConfigureLogging((hostContext, configLogging) =>
            {
                //日志中间件
                //configLogging.AddConsole();
                //configLogging.AddDebug();
            })
                       .UseConsoleLifetime()
                       .Build();

            await host.RunAsync();
        }
Exemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });



            //配置IOC
            //Assembly.Load("ManjuuDomain");
            #region IRepository
            var infrastructureAssembly = Assembly.Load("ManjuuInfrastructure");
            var repositoryTypes        = infrastructureAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(IRepository).IsAssignableFrom(p));
            foreach (var item in repositoryTypes)
            {
                foreach (var itemIntface in item.GetInterfaces())
                {
                    if (typeof(IRepository) == itemIntface)
                    {
                        continue;
                    }
                    services.AddSingleton(itemIntface, item);
                }
            }
            #endregion

            #region ICustomLog
            var commonAssembly = Assembly.Load("ManjuuCommon");
            var customLogTypes = commonAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(ICustomLog <ILogger>).IsAssignableFrom(p));
            foreach (var item in customLogTypes)
            {
                foreach (var itemIntface in item.GetInterfaces())
                {
                    if (typeof(ICustomLog <ILogger>) == itemIntface)
                    {
                        continue;
                    }
                    services.AddSingleton(itemIntface, item);
                }
            }
            #endregion

            #region IApplication
            var applicationAssembly = Assembly.Load("ManjuuApplications");
            var applicationTypes    = applicationAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(IApplication).IsAssignableFrom(p));
            foreach (var item in applicationTypes)
            {
                foreach (var itemIntface in item.GetInterfaces())
                {
                    if (typeof(IApplication) == itemIntface)
                    {
                        continue;
                    }
                    //同一个请求下单例
                    services.AddScoped(itemIntface, item);
                }
            }
            #endregion

            #region Ipc
            //services.AddIpc(action =>
            //{
            //    action.AddNamedPipe(pipeOpt =>
            //    {
            //        pipeOpt.ThreadCount = 2;
            //    }).AddService<IDemoServiceContract, DemoServiceContract>();

            //});
            #endregion

            #region Ipc client
            //IpcServiceClient<IDemoServiceContract> client = new IpcServiceClientBuilder<IDemoServiceContract>()
            //.UseNamedPipe("pipeName") // or .UseTcp(IPAddress.Loopback, 45684) to invoke using TCP
            //.Build();
            IpcServiceClient <ICheckConfigServiceContract> configClient = new IpcServiceClientBuilder <ICheckConfigServiceContract>()
                                                                          .UseNamedPipe("configPipe")
                                                                          .Build();

            IpcServiceClient <ICheckTargetServiceContract> targetJobClient = new IpcServiceClientBuilder <ICheckTargetServiceContract>()
                                                                             .UseNamedPipe("targetPipe")
                                                                             .Build();

            services.AddSingleton <IpcServiceClient <ICheckConfigServiceContract> >(configClient);
            services.AddSingleton <IpcServiceClient <ICheckTargetServiceContract> >(targetJobClient);
            #endregion

            //让ioc自动帮我注入Filter
            services.AddSingleton <ManjuuExceptionFilter>();


            //services.AddDbContext<ManjuuInfrastructure.Repository.Context.HealthManjuuCoreContext>(
            //    opt =>
            //    opt.UseSqlite(Configuration.GetConnectionString("HealthManjuuCore")));



            services.AddMvc(option =>
            {
                var serviceProvider = services.BuildServiceProvider();
                option.Filters.Add(serviceProvider.GetService <ManjuuExceptionFilter>());
                option.ModelBinderProviders.Insert(0, new StringTrimModelBinderProvider(option.InputFormatters));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            //var ipcServerHostBuilder = new IpcServiceHostBuilder(serviceProvider)
            //    .AddNamedPipeEndpoint<IDemoServiceContract>("demoEnpoint", "pipeName")
            //    .AddTcpEndpoint<IDemoServiceContract>("demoTcpEndpoiint",IPAddress.Loopback,2324)
            //    .Build()
            //    .RunAsync();
        }