当前位置: 首页>>代码示例>>C#>>正文


C# CommandProcessorContext.Success方法代码示例

本文整理汇总了C#中CommandProcessorContext.Success方法的典型用法代码示例。如果您正苦于以下问题:C# CommandProcessorContext.Success方法的具体用法?C# CommandProcessorContext.Success怎么用?C# CommandProcessorContext.Success使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在CommandProcessorContext的用法示例。


在下文中一共展示了CommandProcessorContext.Success方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
            context.Log.Info("[{0}:{1}]: PING...", context.Client.Options.Ip, context.Client.Options.TcpPort);

            var connection = context.Client.CreateTcpConnection(
                context,
                (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.Pong)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }
                    context.Log.Info("[{0}:{1}]: PONG!", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    conn.Close();
                    context.Success();
                },
                null,
                (typedConnection, error) =>
                    {
                        if (error == SocketError.Success)
                            context.Success();
                        else
                            context.Fail();
                    });
            connection.EnqueueSend(package.AsByteArray());
            context.WaitForCompletion();
            return true;
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:32,代码来源:PingProcessor.cs

示例2: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                    context.Log.Info("[{0}:{1}]: PING...", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.Pong)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }
                    context.Log.Info("[{0}:{1}]: PONG!", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    context.Success();
                    conn.Close();
                },
                connectionClosed: (typedConnection, error) => context.Fail(reason: "Connection was closed prematurely."));
            context.WaitForCompletion();
            return true;
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:27,代码来源:PingProcessor.cs

示例3: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;
            string metadata = "{'user' : 'test'}";
            var requireMaster = false;
            var data = "{'a' : 3 }";
            if (args.Length > 0)
            {
                if (args.Length != 5)
                    return false;
                eventStreamId = args[0];
                expectedVersion = args[1].ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
                data = args[2];
                metadata = args[3];
                requireMaster = bool.Parse(args[4]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var url = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", eventStreamId);
            context.Log.Info("Writing to {0}...", url);
            var msg = "[{'eventType': 'fooevent', 'eventId' : '" + Guid.NewGuid() + "'" + ",'data' : " + data + ", 'metadata' : " + metadata + "}]";

            var sw = Stopwatch.StartNew();
            client.Post(
                url,
                msg,
                Codec.Json.ContentType,
                new Dictionary<string, string>
                {
                        {SystemHeaders.ExpectedVersion, expectedVersion.ToString()},
                        {SystemHeaders.RequireMaster, requireMaster ? "True" : "False"}
                },
                TimeSpan.FromMilliseconds(10000),
                response =>
                {
                    sw.Stop();
                    if (response.HttpStatusCode == HttpStatusCode.Created)
                        context.Log.Info("Successfully written");
                    else
                    {
                        context.Log.Info("Error while writing: [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);
                        context.Log.Info("Response:\n{0}\n\n{1}\n",
                                         string.Join("\n", response.Headers.AllKeys.Select(x => string.Format("{0,-20}: {1}", x, response.Headers[x]))),
                                         response.Body);
                    }

                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    context.Success();
                },
                e =>
                {
                    context.Log.ErrorException(e, "Error during POST");
                    context.Fail(e, "Error during POST.");
                });

            return true;
        }
开发者ID:kijanawoodard,项目名称:EventStore,代码行数:60,代码来源:WriteHttpProcessor.cs

示例4: PingFloodWaiting

        private void PingFloodWaiting(CommandProcessorContext context, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var clients = new List<TcpTypedConnection<byte[]>>();
            var threads = new List<Thread>();
            var doneEvent = new ManualResetEventSlim(false);
            var clientsDone = 0;
            long all = 0;
            for (int i = 0; i < clientsCnt; i++)
            {
                var autoResetEvent = new AutoResetEvent(false);
                var client = context.Client.CreateTcpConnection(
                    context,
                    (_, __) =>
                    {
                        Interlocked.Increment(ref all);
                        autoResetEvent.Set();
                    },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                        client.EnqueueSend(package.AsByteArray());
                        autoResetEvent.WaitOne();
                    }
                    if (Interlocked.Increment(ref clientsDone) == clientsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                }) { IsBackground = true });
            }

            var sw = Stopwatch.StartNew();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(x => x.Close());

            var reqPerSec = (all + 0.0)/sw.ElapsedMilliseconds*1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int) reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int) Math.Round(sw.Elapsed.TotalMilliseconds/all));

            if (Interlocked.Read(ref all) == requestsCnt)
                context.Success();
            else
                context.Fail();
        }
开发者ID:czcz1024,项目名称:EventStore,代码行数:59,代码来源:PingFloodWaitingProcessor.cs

示例5: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;
                eventStreamId = args[0];
                if (args.Length == 2)
                    expectedVersion = args[1].Trim().ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
            }

            context.IsAsync();
            var sw = new Stopwatch();
            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}, L{1}]: Trying to delete event stream '{2}'...", conn.RemoteEndPoint, conn.LocalEndPoint, eventStreamId);
                    var corrid = Guid.NewGuid();
                    var deleteDto = new TcpClientMessageDto.DeleteStream(eventStreamId, expectedVersion, false);
                    var package = new TcpPackage(TcpCommand.DeleteStream, corrid, deleteDto.Serialize()).AsByteArray();
                    sw.Start();
                    conn.EnqueueSend(package);
                },
                handlePackage: (conn, pkg) =>
                {
                    sw.Stop();
                    context.Log.Info("Delete request took: {0}.", sw.Elapsed);

                    if (pkg.Command != TcpCommand.DeleteStreamCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize<TcpClientMessageDto.DeleteStreamCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        context.Log.Info("DELETED event stream {0}.", eventStreamId);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);
                        context.Success();
                    }
                    else
                    {
                        context.Log.Info("DELETION FAILED for event stream {0}: {1} ({2}).", eventStreamId, dto.Message, dto.Result);
                        context.Fail();
                    }
                    conn.Close();
                },
                connectionClosed:(connection, error) => context.Fail(reason: "Connection was closed prematurely."));

            context.WaitForCompletion();
            return true;
        }
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:57,代码来源:DeleteProcessor.cs

示例6: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var eventNumber = 0;
            var resolveLinkTos = false;
            var requireMaster = false;

            if (args.Length > 0)
            {
                if (args.Length > 3)
                    return false;
                eventStreamId = args[0];
                if (args.Length >= 2)
                    eventNumber = int.Parse(args[1]);
                if (args.Length >= 3)
                    requireMaster = bool.Parse(args[2]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var readUrl = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}/{1}?format=json", eventStreamId,
                                                                eventNumber == -1 ? "head" : eventNumber.ToString());

            context.Log.Info("[{0}]: Reading...", context.Client.HttpEndpoint);

            var sw = Stopwatch.StartNew();
            client.Get(readUrl,
                       new Dictionary<string, string>
                       {
                            {SystemHeaders.ResolveLinkTos, resolveLinkTos ? "True" : "False"},
                            {SystemHeaders.RequireMaster, requireMaster ? "True" : "False"}
                       },
                       TimeSpan.FromMilliseconds(10000),
                       response =>
                       {
                           sw.Stop();
                           context.Log.Info("[{0} ({1})]: READ events from <{2}>.",
                                            response.HttpStatusCode, response.StatusDescription, eventStreamId);
                           context.Log.Info("Response:\n{0}\n\n{1}\n",
                                            string.Join("\n", response.Headers.AllKeys.Select(x => string.Format("{0,-20}: {1}", x, response.Headers[x]))),
                                            response.Body);
                           context.Log.Info("Read request took: {0}.", sw.Elapsed);
                           context.Success();
                       },
                       e => context.Fail(e, string.Format("READ events from <{0}>: FAILED", eventStreamId)));

            return true;
        }
开发者ID:kijanawoodard,项目名称:EventStore,代码行数:49,代码来源:ReadHttpProcessor.cs

示例7: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var package = new TcpPackage(TcpCommand.ScavengeDatabase, Guid.NewGuid(), null);
            context.Log.Info("Sending SCAVENGE request...");

            var connection = context.Client.CreateTcpConnection(
                context,
                (conn, pkg) => { },
                null,
                (typedConnection, error) =>
                {
                    if (error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });
            connection.EnqueueSend(package.AsByteArray());
            connection.Close("OK");
            return true;
        }
开发者ID:thinkbeforecoding,项目名称:EventStore,代码行数:20,代码来源:ScavengeProcessor.cs

示例8: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var version = 0;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;

                eventStreamId = args[0];

                if (args.Length == 2)
                    version = int.Parse(args[1]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var readUrl = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}/event/{1}", eventStreamId, version);

            context.Log.Info("[{0}]: Reading...", context.Client.HttpEndpoint);

            var sw = Stopwatch.StartNew();
            client.Get(readUrl,
                       response =>
                       {
                           sw.Stop();
                           context.Log.Info("READ events from <{0}>: {1}", eventStreamId, response.Body);
                           context.Log.Info("Read request took: {0}.", sw.Elapsed);
                           context.Success();
                       },
                       e => context.Fail(e, string.Format("READ events from <{0}>: FAILED", eventStreamId)));

            return true;
        }
开发者ID:vishal-h,项目名称:EventStore-1,代码行数:36,代码来源:ReadHttpProcessor.cs

示例9: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var fromNumber = 0;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;

                eventStreamId = args[0];

                if (args.Length == 2)
                    fromNumber = int.Parse(args[1]);
            }

            context.IsAsync();

            var readDto = new ClientMessageDto.ReadEvent(Guid.NewGuid(), eventStreamId, fromNumber);
            var package = new TcpPackage(TcpCommand.ReadEvent, readDto.Serialize());

            var sw = new Stopwatch();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}]: Reading...", conn.EffectiveEndPoint);
                    sw.Start();
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.ReadEventCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    sw.Stop();

                    var dto = pkg.Data.Deserialize<ClientMessageDto.ReadEventCompleted>();

                    context.Log.Info("READ events from <{0}>:\n\n"
                                     + "\tCorrelationId: {1}\n"
                                     + "\tEventStreamId: {2}\n"
                                     + "\tEventNumber:   {3}\n"
                                     + "\tReadResult:    {4}\n"
                                     + "\tEventType:     {5}\n"
                                     + "\tData:          {6}\n"
                                     + "\tMetadata:      {7}\n",
                                     eventStreamId,
                                     dto.CorrelationId,
                                     dto.EventStreamId,
                                     dto.EventNumber,
                                     (SingleReadResult) dto.Result,
                                     dto.EventType,
                                     Encoding.UTF8.GetString(dto.Data ?? new byte[0]),
                                     Encoding.UTF8.GetString(dto.Metadata ?? new byte[0]));

                    context.Log.Info("Read request took: {0}.", sw.Elapsed);

                    PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);

                    conn.Close();
                    context.Success();
                },
                connectionClosed: (connection, error) =>
                {
                    if (error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });

            context.WaitForCompletion();
            return true;
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:78,代码来源:ReadProcessor.cs

示例10: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            const string data = "test-data";
            var eventStreamId = "test-stream";
            var writeCount = 10;
            var expectedVersion = ExpectedVersion.Any;

            if (args.Length > 0)
            {
                if (args.Length > 3)
                    return false;
                writeCount = int.Parse(args[0]);
                if (args.Length >= 2)
                    eventStreamId = args[1];
                if (args.Length >= 3)
                    expectedVersion = args[2].Trim().ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[2].Trim());
            }

            context.IsAsync();
            var sw = new Stopwatch();
            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}, L{1}]: Writing...", conn.RemoteEndPoint, conn.LocalEndPoint);
                    var writeDto = new TcpClientMessageDto.WriteEvents(
                        eventStreamId,
                        expectedVersion,
                        Enumerable.Range(0, writeCount).Select(x => new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
                                                                                                     "type",
                                                                                                     0,0,
                                                                                                     Helper.UTF8NoBom.GetBytes(data),
                                                                                                     new byte[0])).ToArray(),
                        false);
                    var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), writeDto.Serialize()).AsByteArray();
                    sw.Start();
                    conn.EnqueueSend(package);
                },
                handlePackage: (conn, pkg) =>
                {
                    sw.Stop();
                    context.Log.Info("Write request took: {0}.", sw.Elapsed);

                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize<TcpClientMessageDto.WriteEventsCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        context.Log.Info("Successfully written {0} events.", writeCount);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)Math.Round(sw.Elapsed.TotalMilliseconds));
                        context.Success();
                    }
                    else
                    {
                        context.Log.Info("Error while writing: {0}.", dto.Result);
                        context.Fail();
                    }
                    conn.Close();
                },
                connectionClosed: (connection, error) => context.Fail(reason: "Connection was closed prematurely."));

            context.WaitForCompletion();
            return true;
        }
开发者ID:czcz1024,项目名称:EventStore,代码行数:68,代码来源:MultiWriteProcessor.cs

示例11: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;
            var data = "test-data";
            string metadata = null;

            if (args.Length > 0)
            {
                if (args.Length < 3 || args.Length > 4)
                    return false;
                eventStreamId = args[0];
                expectedVersion = args[1].ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
                data = args[2];
                if (args.Length == 4)
                    metadata = args[3];
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var url = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", eventStreamId);
            context.Log.Info("Writing to {0}...", url);

            var request = Codec.Xml.To(new HttpClientMessageDto.WriteEventsText(
                    expectedVersion,
                    new[] { new HttpClientMessageDto.ClientEventText(Guid.NewGuid(), "type", data, metadata) }));

            var sw = Stopwatch.StartNew();
            client.Post(
                url,
                request,
                Codec.Xml.ContentType,
                response =>
                {
                    sw.Stop();
                    if (response.HttpStatusCode == HttpStatusCode.Created)
                        context.Log.Info("Successfully written");
                    else
                        context.Log.Info("Error while writing: [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);

                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    context.Success();
                },
                e =>
                {
                    context.Log.ErrorException(e, "Error during POST");
                    context.Fail(e, "Error during POST.");
                });

            return true;
        }
开发者ID:robashton,项目名称:EventStore,代码行数:52,代码来源:WriteHttpProcessor.cs

示例12: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            var connection = context.Client.CreateTcpConnection(
                    context,
                    connectionEstablished: conn =>
                    {
                    },
                    handlePackage: (conn, pkg) =>
                    {
                        switch (pkg.Command)
                        {
                            case TcpCommand.StreamEventAppeared:
                            {
                                var dto = pkg.Data.Deserialize<ClientMessageDto.StreamEventAppeared>();
                                context.Log.Info("NEW EVENT:\n\n"
                                                 + "\tEventStreamId: {0}\n"
                                                 + "\tEventNumber:   {1}\n"
                                                 + "\tEventType:     {2}\n"
                                                 + "\tData:          {3}\n"
                                                 + "\tMetadata:      {4}\n",
                                                 dto.EventStreamId,
                                                 dto.EventNumber,
                                                 dto.EventType,
                                                 Encoding.UTF8.GetString(dto.Data ?? new byte[0]),
                                                 Encoding.UTF8.GetString(dto.Metadata ?? new byte[0]));
                                break;
                            }
                            case TcpCommand.SubscriptionDropped:
                            {
                                var dto = pkg.Data.Deserialize<ClientMessageDto.SubscriptionDropped>();
                                context.Log.Error("Subscription to <{0}> WAS DROPPED!", dto.EventStreamId);
                                break;
                            }
                            case TcpCommand.SubscriptionToAllDropped:
                            {
                                var dto = pkg.Data.Deserialize<ClientMessageDto.SubscriptionToAllDropped>();
                                context.Log.Error("Subscription to ALL WAS DROPPED!");
                                break;
                            }
                            default:
                                context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                                break;
                        }
                    },
                    connectionClosed: (c, error) =>
                    {
                        if (error == SocketError.Success)
                            context.Success();
                        else
                            context.Fail();
                    });

            if (args.Length == 0)
            {
                context.Log.Info("SUBSCRIBING TO ALL STREAMS...");
                var corrid = Guid.NewGuid();
                var cmd = new ClientMessageDto.SubscribeToAllStreams(corrid);
                connection.EnqueueSend(new TcpPackage(TcpCommand.SubscribeToAllStreams, corrid, cmd.Serialize()).AsByteArray());
            }
            else
            {
                foreach (var stream in args)
                {
                    context.Log.Info("SUBSCRIBING TO STREAM <{0}>...", stream);
                    var corrid = Guid.NewGuid();
                    var cmd = new ClientMessageDto.SubscribeToStream(corrid, stream);
                    connection.EnqueueSend(new TcpPackage(TcpCommand.SubscribeToStream, corrid, cmd.Serialize()).AsByteArray());
                }
            }

            context.WaitForCompletion();
            return true;
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:75,代码来源:SubscribeToStreamProcessor.cs

示例13: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            const string data = "test-data";
            var writeCount = 10;
            var expectedVersion = ExpectedVersion.Any;

            if (args.Length > 0)
            {
                if (args.Length > 3)
                    return false;
                writeCount = int.Parse(args[0]);
                if (args.Length >= 2)
                    eventStreamId = args[1];
                if (args.Length >= 3)
                    expectedVersion = args[2].Trim().ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[2].Trim());
            }

            context.IsAsync();

            var writeDto = new ClientMessageDto.WriteEvents(
                Guid.Empty,
                eventStreamId,
                expectedVersion,
                Enumerable.Range(0, writeCount).Select(x =>
                                                       new ClientMessageDto.Event(Guid.NewGuid(),
                                                                                  "type",
                                                                                  Encoding.UTF8.GetBytes(data),
                                                                                  new byte[0])).ToArray());

            var package = new TcpPackage(TcpCommand.WriteEvents, writeDto.Serialize());

            var sw = new Stopwatch();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}]: Writing...", conn.EffectiveEndPoint);
                    sw.Start();
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    sw.Stop();

                    var dto = pkg.Data.Deserialize<ClientMessageDto.WriteEventsCompleted>();
                    if (dto.ErrorCode == (int)OperationErrorCode.Success)
                    {
                        context.Log.Info("Successfully written {0} events. CorrelationId: {1}.",
                                         writeCount,
                                         dto.CorrelationId);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);
                    }
                    else
                    {
                        context.Log.Info("Error while writing: {0}. CorrelationId: {1}.", dto.Error, dto.CorrelationId);
                    }
                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    
                    conn.Close();
                    context.Success();
                },
                connectionClosed:(connection, error) =>
                    {
                        if(error == SocketError.Success)
                            context.Success();
                        else
                            context.Fail();
                    });

            context.WaitForCompletion();
            return true;
        }
开发者ID:vishal-h,项目名称:EventStore-1,代码行数:80,代码来源:MultiWriteProcessor.cs

示例14: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;
            var data = GenerateTestData();
            string metadata = null;

            if (args.Length > 0)
            {
                if (args.Length < 3 || args.Length > 4)
                    return false;
                eventStreamId = args[0];
                expectedVersion = args[1].ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
                data = args[2];
                if (args.Length == 4)
                    metadata = args[3];
            }

            context.IsAsync();
            var writeDto = new TcpClientMessageDto.WriteEvents(
                eventStreamId,
                expectedVersion,
                new[]
                {
                    new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
                                                     "JsonDataEvent",
                                                     1,0,
                                                     Helper.UTF8NoBom.GetBytes(data),
                                                     Helper.UTF8NoBom.GetBytes(metadata ?? string.Empty))
                },
                false);
            var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), writeDto.Serialize());

            var sw = new Stopwatch();
            bool dataReceived = false;

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}, L{1}]: Writing...", conn.RemoteEndPoint, conn.LocalEndPoint);
                    sw.Start();
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    dataReceived = true;
                    sw.Stop();

                    var dto = pkg.Data.Deserialize<TcpClientMessageDto.WriteEventsCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        context.Log.Info("Successfully written. EventId: {0}.", package.CorrelationId);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);
                    }
                    else
                    {
                        context.Log.Info("Error while writing: {0} ({1}).", dto.Message, dto.Result);
                    }

                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    conn.Close();
                    context.Success();
                },
                connectionClosed: (connection, error) =>
                {
                    if (dataReceived && error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });

            context.WaitForCompletion();
            return true;
        }
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:81,代码来源:WriteJsonProcessor.cs

示例15: Flood


//.........这里部分代码省略.........
                            Console.Write(".");

                        Interlocked.Increment(ref requestsCnt);
                        Interlocked.Increment(ref received);
                    };

                    var sentCount = 0;
                    var sleepTime = 0;

                    var currentMinute = -1;

                    while (true)
                    {
                        TimeSpan elapsed;
                        lock (watchLockRoot)
                            elapsed = sw.Elapsed;

                        if (elapsed.TotalMinutes > runTimeMinutes)
                        {
                            autoResetEvent.Set();
                            break;
                        }

                        if (sentCount == 0)
                        {
                            int elapsedMinutesInt = (int)elapsed.TotalMinutes;

                            lock (_randomLockRoot)
                            {
                                sentCount = minPerSecond == maxPerSecond
                                                ? maxPerSecond
                                                : _random.Next(minPerSecond, maxPerSecond);
                            }

                            if (currentMinute != elapsedMinutesInt)
                            {
                                currentMinute = elapsedMinutesInt;
                                context.Log.Info(Environment.NewLine + "Elapsed {0} of {1} minutes, sent {2}",
                                                 elapsedMinutesInt,
                                                 runTimeMinutes,
                                                 sent);
                            }

                            sleepTime = 1000 / sentCount;
                        }

                        var url = context.Client.HttpEndpoint.ToHttpUrl("/ping");

                        client.Get(url,
                                   succHandler,
                                   exc => context.Log.ErrorException(exc, "Error during GET."));

                        Interlocked.Increment(ref sent);

                        Thread.Sleep(sleepTime);
                        sentCount -= 1;

                        while (sent - received > context.Client.Options.PingWindow/clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();

            sw.Stop();

            context.Log.Info("Completed. Successes: {0}, failures: {1}", succ, fail);

            var reqPerSec = (requestsCnt + 0.0)/sw.ElapsedMilliseconds*1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                    Keyword,
                    PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                         PerfUtils.Col("requestsCnt", requestsCnt),
                         PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                    PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail))
                );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int) reqPerSec);

            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt),
                (int) ((fail/(succ + 0.0))*100));

            context.Success();
        }
开发者ID:base31,项目名称:geteventstore_EventStore,代码行数:101,代码来源:PingHttpLongTermProcessor.cs


注:本文中的CommandProcessorContext.Success方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。