public void Create(string filePath)
        {
            string tempFile1 = ExampleHelper.GetTempFilePath(filePath);
            string tempFile2 = ExampleHelper.GetTempFilePath(filePath);

            try
            {
                new UsingTables().Create(tempFile1);
                var wb = new XLWorkbook(tempFile1);

                var wsSource = wb.Worksheet(1);
                // Copy the worksheet to a new sheet in this workbook
                wsSource.CopyTo("Copy");

                // We're going to open another workbook to show that you can
                // copy a sheet from one workbook to another:
                new BasicTable().Create(tempFile2);
                var wbSource = new XLWorkbook(tempFile2);
                wbSource.Worksheet(1).CopyTo(wb, "Copy From Other");

                // Save the workbook with the 2 copies
                wb.SaveAs(filePath);
            }
            finally
            {
                if (File.Exists(tempFile1))
                {
                    File.Delete(tempFile1);
                }
                if (File.Exists(tempFile2))
                {
                    File.Delete(tempFile2);
                }
            }
        }
Example #2
0
        public void Create(string filePath)
        {
            string tempFile = ExampleHelper.GetTempFilePath(filePath);

            try
            {
                //Note: Prepare
                {
                    var workbook = new XLWorkbook();
                    workbook.Worksheets.Add("1");
                    workbook.Worksheets.Add("2");
                    workbook.Worksheets.Add("3");
                    workbook.Worksheets.Add("4");
                    workbook.SaveAs(tempFile);
                }

                //Note: Delate few worksheet
                {
                    var workbook = new XLWorkbook(tempFile);
                    workbook.Worksheets.Delete("1");
                    workbook.Worksheets.Delete("2");
                    workbook.SaveAs(filePath);
                }
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
Example #3
0
        static async Task Main()
        {
            // Sets up Miki.Logging for internal library logging. Can be removed if you do not want to
            // see internal logs.
            ExampleHelper.InitLog(LogLevel.Information);

            // Fetches your token from environment values.
            var token = ExampleHelper.GetTokenFromEnv();

            var memCache = new InMemoryCacheClient(new ProtobufSerializer());

            var apiClient = new DiscordApiClient(token, memCache);

            // Discord direct gateway implementation.
            var gateway = new GatewayCluster(
                new GatewayProperties
            {
                ShardCount = 1,
                ShardId    = 0,
                Token      = token.ToString(),
            });

            var discordClient = new DiscordClient(apiClient, gateway, memCache);

            // Subscribe to ready event.
            discordClient.Events.MessageCreate.SubscribeTask(OnMessageReceived);

            // Start the connection to the gateway.
            await gateway.StartAsync();

            // Wait, else the application will close.
            await Task.Delay(-1);
        }
        public void FinalizerCausesQueuedLogsToFlush()
        {
            // Slow log writer - starting, stopping, disposing, writing an entry, all take at least 10ms each.
            const int opDelayMs          = 5;
            var       slowLogWriter      = new SlowTestLogWriter <MessageEntry>(SetupLog, opDelayMs, false);
            const int expectedEntryCount = 25;

            // Run the test code in a delegate so that local variable references can be GCed
            Action logTestMessages = () =>
            {
                BackgroundMultiLogWriter         backgroundMultiLogWriter;
                IQueueEntryWriter <MessageEntry> queueEntryWriter;
                SetupBackgroundLogWriter(slowLogWriter, out backgroundMultiLogWriter, out queueEntryWriter);

                ExampleHelper.LogTestMessages(queueEntryWriter, expectedEntryCount);

                // Key point: The BackgroundMultiLogWriter is never disposed, and it has a number of queued
                // entries that haven't been written
            };

            logTestMessages();

            Assert.True(slowLogWriter.Count < expectedEntryCount);

            // Force a GC cyle, and wait for finalizers to complete.
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Assert.Equal(expectedEntryCount, slowLogWriter.Count);

            // When the finalizer is called, an error is logged to the SetupLog.
            Assert.True(SetupLog.Any(traceEntry => (traceEntry.TraceLevel == TraceLevel.Error) && (traceEntry.Message.StartsWith("In finalizer "))));
        }
        public ExampleStruct(int nr) : this()
        {
            this.Name   = "Element " + nr;
            this.Number = nr;

            this.Enum = (ExampleEnum)ExampleHelper.RandomInt(0, 5);
        }
        public void QueueLogWriterCanBeDisposedEarly()
        {
            var innerLogWriter = new TestLogWriter <MessageEntry>(SetupLog, false);
            BackgroundMultiLogWriter         backgroundMultiLogWriter;
            IQueueEntryWriter <MessageEntry> queueEntryWriter;

            SetupBackgroundLogWriter(innerLogWriter, out backgroundMultiLogWriter, out queueEntryWriter);

            using (backgroundMultiLogWriter)
            {
                using (queueEntryWriter as IDisposable)
                {
                    ExampleHelper.LogTestMessagesInParallel(queueEntryWriter, 8, 8, _testOutputHelper);
                }
                Assert.False(queueEntryWriter.IsEnabled);
                Assert.False(queueEntryWriter.IsStarted);
                Assert.True(backgroundMultiLogWriter.IsStarted);

                // Can't restart after Dispose()
                Assert.Throws <ObjectDisposedException>(() => queueEntryWriter.Start());

                // Logging still doesn't throw after Dispose
                var msg = new MessageEntry("Logged while Dispose()ed - never logged.");
                queueEntryWriter.Write(ref msg);
            }
            Assert.False(backgroundMultiLogWriter.IsStarted);

            Assert.False(backgroundMultiLogWriter.IsBackgroundThreadRunning);
            Assert.Equal(8 * 8, innerLogWriter.Count);
        }
Example #7
0
        static async Task RunServerAsync()
        {
            ExampleHelper.SetConsoleLogger();

            var group = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <SocketDatagramChannel>()
                .Option(ChannelOption.SoBroadcast, true)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    channel.Pipeline.AddLast("Quote", new QuoteOfTheMomentServerHandler());
                }));

                IChannel boundChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.WriteLine("Press any key to terminate the server.");
                Console.ReadLine();

                await boundChannel.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Example #8
0
        public static void Run()
        {
            string filePath         = Constants.SAMPLE_VSDX;
            string imageFilePath    = Constants.SAMPLE_EMF;
            string embeddedFilePath = Constants.SAMPLE_PPTX;
            string filePathOut      = Path.Combine(Constants.GetOutputDirectoryPath(), Constants.SAMPLE_NAME + Path.GetExtension(filePath));

            FileStream imageStream = new FileStream(imageFilePath, FileMode.Open);

            byte[] imageBytes = ExampleHelper.ToBytes(imageStream);
            imageStream.Close();

            OleDiagramOptions oleDiagramOptions = new OleDiagramOptions(embeddedFilePath, imageBytes, 2);

            oleDiagramOptions.X      = 1;
            oleDiagramOptions.Y      = 1;
            oleDiagramOptions.Width  = 2;
            oleDiagramOptions.Height = 1;

            using (Merger merger = new Merger(filePath))
            {
                merger.ImportDocument(oleDiagramOptions);
                merger.Save(filePathOut);
            }

            Console.WriteLine("Embedded object was added to the source document successfully.");
            Console.WriteLine($"Check output {filePathOut}.");
        }
        public void CheckNonEqual()
        {
            string left  = ExampleHelper.GetTempFilePath("left.xlsx");
            string right = ExampleHelper.GetTempFilePath("right.xlsx");

            try
            {
                new BasicTable().Create(left);
                new HelloWorld().Create(right);

                string message;
                Assert.IsFalse(ExcelDocsComparer.Compare(left, right, out message));
            }
            finally
            {
                if (File.Exists(left))
                {
                    File.Delete(left);
                }
                if (File.Exists(right))
                {
                    File.Delete(right);
                }
            }
        }
Example #10
0
        static async Task Main()
        {
            ExampleHelper.InitLog(LogLevel.Debug);

            var token = ExampleHelper.GetTokenFromEnv();

            ServiceCollection collection = new ServiceCollection();

            collection.AddSingleton <ISerializer, ProtobufSerializer>();
            collection.AddSingleton <ICacheClient, InMemoryCacheClient>();
            collection.AddSingleton <IExtendedCacheClient, InMemoryCacheClient>();

            collection.UseDiscord(x =>
            {
                x.Token = token;
            });

            var serviceProvider = collection.BuildServiceProvider();

            var client = serviceProvider.GetService <IDiscordClient>();

            client.Events.MessageCreate.Subscribe(x =>
            {
                Console.WriteLine($"{x.Author.Username}: {x.Content}");
            });

            await client.StartAsync(default);
        public void StoppingQueueLogWriterHaltsWriting()
        {
            var innerLogWriter = new TestLogWriter <MessageEntry>(SetupLog, false);
            BackgroundMultiLogWriter         backgroundMultiLogWriter;
            IQueueEntryWriter <MessageEntry> queueEntryWriter;

            SetupBackgroundLogWriter(innerLogWriter, out backgroundMultiLogWriter, out queueEntryWriter);

            using (backgroundMultiLogWriter)
            {
                ExampleHelper.LogTestMessagesInParallel(queueEntryWriter, 8, 8, _testOutputHelper);
                queueEntryWriter.Stop();
                queueEntryWriter.Stop(); // Stopping twice shouldn't change things

                // These messages aren't logged
                ExampleHelper.LogTestMessagesInParallel(queueEntryWriter, 8, 8, _testOutputHelper);

                queueEntryWriter.Start();
                queueEntryWriter.Start(); // Starting twice shouldn't change things
                ExampleHelper.LogTestMessagesInParallel(queueEntryWriter, 8, 8, _testOutputHelper);
            }

            Assert.False(backgroundMultiLogWriter.IsBackgroundThreadRunning);
            Assert.Equal(2 * 8 * 8, innerLogWriter.Count);
        }
Example #12
0
        static async Task RunServerAsync()
        {
            //设置输出日志到Console
            ExampleHelper.SetConsoleLogger();

            // 主工作线程组,设置为1个线程
            var bossGroup = new MultithreadEventLoopGroup(1);
            // 工作线程组,默认为内核数*2的线程数
            var workerGroup = new MultithreadEventLoopGroup();
            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl) //如果使用加密通道
            {
                tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }
            try
            {
                //声明一个服务端Bootstrap,每个Netty服务端程序,都由ServerBootstrap控制,
                //通过链式的方式组装需要的参数

                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)           // 设置主和工作线程组
                .Channel <TcpServerSocketChannel>()      // 设置通道模式为TcpSocket
                .Option(ChannelOption.SoBacklog, 100)    // 设置网络IO参数等,这里可以设置很多参数,当然你对网络调优和参数设置非常了解的话,你可以设置,或者就用默认参数吧
                .Handler(new LoggingHandler("SRV-LSTN")) //在主线程组上设置一个打印日志的处理器
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {                                        //工作线程连接器 是设置了一个管道,服务端主线程所有接收到的信息都会通过这个管道一层层往下传输
                      //同时所有出栈的消息 也要这个管道的所有处理器进行一步步处理
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)     //Tls的加解密
                    {
                        pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                    }
                    //日志拦截器
                    pipeline.AddLast(new LoggingHandler("SRV-CONN"));
                    //出栈消息,通过这个handler 在消息顶部加上消息的长度
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    //入栈消息通过该Handler,解析消息的包长信息,并将正确的消息体发送给下一个处理Handler,该类比较常用,后面单独说明
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                    //业务handler ,这里是实际处理Echo业务的Handler
                    pipeline.AddLast("echo", new EchoServerHandler());
                }));

                // bootstrap绑定到指定端口的行为 就是服务端启动服务,同样的Serverbootstrap可以bind到多个端口
                IChannel boundChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();
                //关闭服务
                await boundChannel.CloseAsync();
            }
            finally
            {
                //释放工作组线程
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
        public ActionResult Index()
        {
            var name = ExampleHelper.CallOperation(RouteData, "GetFirstName", "");

            ViewData["FirstName"] = name ?? "No name";

            return(View());
        }
Example #14
0
        public ActionResult Create()
        {
            var atomiaAccountApiClient = AtomiaServiceChannelManager.GetAccountService();
            var account = atomiaAccountApiClient.GetAccountByName(RouteData.Values["accountId"].ToString());

            ExampleHelper.Create(RouteData, account.FirstName, account.LastName);

            return(RedirectToAction("Index", new { area = "Example", controller = "Example" }));
        }
Example #15
0
        ///<summary>Main for ExampleListener.</summary>
        ///<param name="args">Command Line Arguments</param>
        public static void Main(String[] args)
        {
            // TODO: Change to correct URI
            string uri = "tcp://127.0.0.1:4001";

            ServerFactory listener = ExampleHelper.NewListener(uri, null, new MainExampleListener());

            // Start the Listener
            listener.TransportControl(TransportConsts.START_AND_WAIT_UP, 4000);
        }
Example #16
0
        public void MakeConnection()
        {
            String uri = "tcp://127.0.0.1:4010";

            MainExampleClient client = new MainExampleClient();

            server = ExampleHelper.NewServer(uri, null, client);

            server._StartAndWaitUp(4000);
        }
Example #17
0
        static async Task RunClientAsync()
        {
            ExampleHelper.SetConsoleLogger();

            var group = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(
                    new ActionChannelInitializer <ISocketChannel>(
                        channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new LoggingHandler());
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoClientHandler());
                }));

                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));

                // 建立死循环,类同于While(true)
                for (; ;)  // (4)
                {
                    Console.WriteLine("input you data:");
                    // 根据设置建立缓存区大小
                    IByteBuffer initialMessage = Unpooled.Buffer(ClientSettings.Size); // (1)
                    string      r = Console.ReadLine();
                    // 将数据流写入缓冲区
                    initialMessage.WriteBytes(Encoding.UTF8.GetBytes(r ?? throw new InvalidOperationException())); // (2)
                    // 将缓冲区数据流写入到管道中
                    await clientChannel.WriteAndFlushAsync(initialMessage);                                        // (3)

                    if (r.Contains("bye"))
                    {
                        break;
                    }
                }

                Console.WriteLine("byebye");


                await clientChannel.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Example #18
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            var group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (Examples.Common.ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (cert != null)
                    {
                        pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }

                    pipeline.AddLast(new LoggingHandler("CONN"));
                    pipeline.AddLast(new BigIntegerDecoder());
                    pipeline.AddLast(new NumberEncoder());
                    pipeline.AddLast(new FactorialClientHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(Examples.Common.ClientSettings.Host, Examples.Common.ClientSettings.Port));

                // Get the handler instance to retrieve the answer.
                var handler = (FactorialClientHandler)bootstrapChannel.Pipeline.Last();

                // Print out the answer.
                Console.WriteLine($"Factorial of {ClientSettings.Count} is: {handler.GetFactorial()}");

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
            }
        }
Example #19
0
 private IEnumerator TPAudioPoolRepeatPlaying(int repeat)
 {
     while (repeat >= 0)
     {
         AudioSystem.Play("MyBundle", "Door", () => {
             ExampleHelper.MessageWithLines("TPAudioPool Sound 'Door' was played by MyBundle");
         });
         repeat--;
         yield return(ExampleHelper.WaitSecond);
     }
 }
Example #20
0
 private void Save()
 {
     PersistPrefs.Save(this);
     ExampleHelper.DrawLine();
     Debug.Log("Values Saved");
     someString.ToLog("SomeString: ");
     someBool.ToLog("SomeBool: ");
     someInt.ToLog("SomeInt: ");
     someFloat.ToLog("SomeFloat: ");
     ExampleHelper.DrawLine();
 }
Example #21
0
        public void ExampleHelper_ConvertIDtoString_InValid_Bogus_Should_Fail()
        {
            // Arrange

            // Act
            var result = ExampleHelper.ConvertIDtoString("bogus");

            // Reset

            // Assert
            Assert.AreEqual(string.Empty, result);
        }
Example #22
0
        public void StartListener()
        {
            String uri = "tcp://127.0.0.1:4010";

            MainExampleListener implFactory = new MainExampleListener();

            listener = ExampleHelper.NewListener(uri, null, implFactory);

            listener.TransportControl(TransportConsts.START_AND_WAIT_UP, 4000);

            Console.WriteLine("Listener Started");
        }
    // Use this for initialization
    private void Start()
    {
        object goldenArmor = new object(); // some Item

        healthIncreaser.Source = goldenArmor;
        ExampleHelper.DrawLine();
        Debug.Log("TPAttribute Health Base value: " + health.BaseValue);
        Debug.Log("TPAttribute Health Value before armor equip(healthIncreaser): " + health.Value);
        health.Modifiers.Add(healthIncreaser);
        Debug.Log("TPAttribute Health Value after armor equip(healthIncreaser): " + health.Value);
        ExampleHelper.DrawLine();
    }
        public void ExceedingQueueSizeBlocksLogging()
        {
            // Slow log writer - starting, stopping, disposing, writing an entry, all take at least 10ms each.
            const int opDelayMs           = 50;
            const int maxQueueLength      = 10;
            const int countBlockingWrites = 4;
            var       slowLogWriter       = new SlowTestLogWriter <MessageEntry>(SetupLog, opDelayMs, false);

            BackgroundMultiLogWriter         backgroundMultiLogWriter;
            IQueueEntryWriter <MessageEntry> queueEntryWriter;

            SetupBackgroundLogWriter(slowLogWriter, out backgroundMultiLogWriter, out queueEntryWriter, maxQueueLength);

            var stopwatch = Stopwatch.StartNew();

            using (backgroundMultiLogWriter)
            {
                // First 10 messages log fast, then the queue is exactly full
                ExampleHelper.LogTestMessages(queueEntryWriter, maxQueueLength);
                stopwatch.Stop();
                _testOutputHelper.WriteLine("First {0} writes took: {1}ms", maxQueueLength, stopwatch.ElapsedMilliseconds);
                Assert.True(_inDebugger || (stopwatch.ElapsedMilliseconds <= opDelayMs), "Log writing should be fast, until the queue is filled.");

                // Next writes block, since we've filled the queue
                for (int i = 0; i < countBlockingWrites; ++i)
                {
                    stopwatch.Restart();
                    ExampleHelper.LogTestMessages(queueEntryWriter, 1);
                    stopwatch.Stop();
                    long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                    _testOutputHelper.WriteLine("Blocking write #{0}: {1}ms", i, elapsedMilliseconds);
                    Assert.True((elapsedMilliseconds >= (opDelayMs * 0.5)) || (i == 0) || _inDebugger,
                                "Expect blocking until 1 element is written - elapsed: " + elapsedMilliseconds);
                    // This assert is not passing on hqs01 - re-check another time.
                    // Timing-sensitive tests are always a bit delicate
                    //Assert.True((i == 0) || (elapsedMilliseconds < 2 * opDelayMs) || _inDebugger, "First write may be delayed; after that blocking should only occur for the duration of writing 1 entry.  i=" + i + " Elapsed: " + elapsedMilliseconds);
                }

                stopwatch.Restart();
            }
            stopwatch.Stop();
            _testOutputHelper.WriteLine("Stop + dispose took {0}", stopwatch.Elapsed);

            // At this point, everything should have been logged
            Assert.Equal(maxQueueLength + countBlockingWrites, slowLogWriter.Count);
            Assert.True(stopwatch.ElapsedMilliseconds > maxQueueLength * opDelayMs, "Dispose writes all queued entries");

            // maxQueueLength+2 is the number of sleeps to wait for - the queue is full, +2 is for Stop() + Dispose() sleeps
            // 2.0 is just a tolerance for thread-related delays
            Assert.True((stopwatch.ElapsedMilliseconds < (maxQueueLength + 2) * opDelayMs * 2.0) || _inDebugger, "Took longer than expected: " + stopwatch.ElapsedMilliseconds);
        }
Example #25
0
        static async Task RunClientAsync()
        {
            ExampleHelper.SetConsoleLogger();

            var group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (cert != null)
                    {
                        //Netty支持Tls加密传输,TlsHandler类可以在开发人员无须关心加密传输时字节码的变化,只关心自己的业务代码即可。在管道处理的第一个配置该类即可
                        pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }
                    pipeline.AddLast(new LoggingHandler());
                    //LengthFieldPrepender 会在实际发送前在将数据的长度放置在数据前,本例中使用2个字节来存储数据的长度。
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    //LengthFieldBasedFrameDecoder 比较常用,会在解码前用于解析数据,用于读取数据包的头信息,特别是包长,并等待数据达到包长后再交由下一个handler处理。 参数说明 以下是Amp协议的参数值,并注释了意义
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoClientHandler());
                }));

                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));

                Console.ReadLine();

                await clientChannel.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Example #26
0
        static async Task RunServerAsync()
        {
            ExampleHelper.SetConsoleLogger();

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                //tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.Option(ChannelOption.SoBacklog, 100);
                bootstrap.Handler(new LoggingHandler("SRV-LSTN"));
                bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                    }
                    //pipeline.AddLast(new LoggingHandler("SRV-CONN"));
                    // pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    // pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoServerHandler());
                    pipeline.AddLast("User", new UserHandler());

                    // Action<string> messageTarget = ShowMessage;
                }));


                IChannel boundChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();

                await boundChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
Example #27
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            var stringEncoder = new StringEncoder();
            var stringDecoder = new StringDecoder();
            var serverHandler = new SecureChatServerHandler();

            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }

                    pipeline.AddLast(new LoggingHandler("CONN"));
                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(stringEncoder, stringDecoder, serverHandler);
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Example #28
0
        ///<summary>Main for ExampleClient</summary>
        ///<param name="args">Command Line Arguments</param>
        public static void Main(String[] args)
        {
            // TODO: Change to correct URI
            string uri = "tcp://localhost:4002";

            RemoteExampleServer server = ExampleHelper.NewServer(uri, null, new MainExampleClient());

            // Connect to the service
            server._StartAndWaitUp(4000);

            // TODO: Insert Your Code Here

            // Disconnect from the service
            server._StopAndWaitDown(4000);
        }
Example #29
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            var group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2("dotnetty.com.pfx", "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (cert != null)
                    {
                        pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }
                    pipeline.AddLast(new LoggingHandler());
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender2(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder2(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoClientHandler());
                }));

                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));

                Console.ReadLine();

                await clientChannel.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Example #30
0
        public ActionResult Index()
        {
            var service = ExampleHelper.GetServiceModel(RouteData);

            ViewData["CanAdd"] = ExampleHelper.CanAdd(RouteData) ? "1" : "0";
            ViewData["Exists"] = null == service ? "0" : "1";

            if (null != service)
            {
                ViewData["FirstName"] = service.FirstName ?? "No name";
                ViewData["LastName"]  = service.LastName ?? "No name";
                ViewData["Number"]    = service.Number ?? "0";
            }

            return(View());
        }