Exemplo n.º 1
0
        public void LoadEventToCalendar()
        {
            ReadEvent reader = new ReadEvent();

            eventCollection.Clear();
            scheduler.Events.Clear();
            eventCollection = reader.ReadEventByPatientId(currentUser);
            foreach (Event e in eventCollection)
            {
                if (ConfirmEventPopup.Visibility == Visibility.Visible)
                {
                    //ConfirmEventPopup.Visibility = Visibility.Collapsed;
                }
                else
                {
                    Event eventToAdd = new Event();
                    eventToAdd = e;
                    if (e.End < DateTime.Now)
                    {
                        ConfirmEventPopup.Visibility = Visibility.Visible;
                        txtEvent.Text       = e.Subject;
                        txtDate.Text        = e.Start.ToLongDateString();
                        btnAcceptEvent.Tag  = e.Id;
                        btnDeclineEvent.Tag = e.Id;
                        btnAcceptStep.Tag   = e.Id;
                        btnDeclineStep.Tag  = e.Id;
                    }
                    scheduler.AddEvent(eventToAdd);
                }
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// Verifies that the read event is a control word.
 /// </summary>
 public static void ControlWord(ReadEvent e, string name, bool starred = false, int?param = null)
 {
     Assert.AreEqual(EventType.ControlWord, e.Type);
     Assert.AreEqual(starred, e.Starred);
     Assert.AreEqual(param, e.Parameter);
     Assert.AreEqual(name, e.Text);
 }
Exemplo n.º 3
0
        public void Read()
        {
            int  number;
            bool res = true;

            while (res)
            {
                try
                {
                    number = GetNumberFromConsole("Выберите направление сортировки: 1 - А-Я, 2 - Я-А ");
                    res    = false;
                    ReadEvent?.Invoke(number);
                }
                catch (MyException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (res)
                    {
                        Console.WriteLine("Попробуйте еще раз!");
                    }
                }
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Verifies that the read event is a group start ('{').
 /// </summary>
 public static void GroupStart(ReadEvent e)
 {
     Assert.AreEqual(EventType.GroupStart, e.Type);
     Assert.IsFalse(e.Starred);
     Assert.IsNull(e.Parameter);
     Assert.IsNull(e.Text);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Read a tag
        /// </summary>
        /// <typeparam name="T">The type of tag to read</typeparam>
        /// <param name="tag">The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name.
        /// E.g: the tag `foo.bar` reads the tag `bar` on the folder `foo`</param>
        /// <returns>The value retrieved from the OPC</returns>
        public ReadEvent <T> Read <T>(string tag)
        {
            var nodesToRead = BuildReadValueIdCollection(tag, Attributes.Value);
            DataValueCollection      results;
            DiagnosticInfoCollection diag;

            _session.Read(
                requestHeader: null,
                maxAge: 0,
                timestampsToReturn: TimestampsToReturn.Neither,
                nodesToRead: nodesToRead,
                results: out results,
                diagnosticInfos: out diag);
            var val = results[0];

            var readEvent = new ReadEvent <T>();

            readEvent.Value           = (T)val.Value;
            readEvent.SourceTimestamp = val.SourceTimestamp;
            readEvent.ServerTimestamp = val.ServerTimestamp;
            if (StatusCode.IsGood(val.StatusCode))
            {
                readEvent.Quality = Quality.Good;
            }
            if (StatusCode.IsBad(val.StatusCode))
            {
                readEvent.Quality = Quality.Bad;
            }
            return(readEvent);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Read a tag
        /// </summary>
        /// <typeparam name="T">The type of tag to read</typeparam>
        /// <param name="tag">The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name.
        /// E.g: the tag `foo.bar` reads the tag `bar` on the folder `foo`</param>
        /// <returns>The value retrieved from the OPC</returns>
        public ReadEvent <T> Read <T>(string tag)
        {
            var item = new OpcDa.Item {
                ItemName = tag
            };

            if (Status == OpcStatus.NotConnected)
            {
                throw new OpcException("Server not connected. Cannot read tag.");
            }
            var result = _server.Read(new[] { item })[0];
            T   casted;

            TryCastResult(result.Value, out casted);

            var readEvent = new ReadEvent <T>();

            readEvent.Value           = casted;
            readEvent.SourceTimestamp = result.Timestamp;
            readEvent.ServerTimestamp = result.Timestamp;
            if (result.Quality == OpcDa.Quality.Good)
            {
                readEvent.Quality = Quality.Good;
            }
            if (result.Quality == OpcDa.Quality.Bad)
            {
                readEvent.Quality = Quality.Bad;
            }

            return(readEvent);
        }
Exemplo n.º 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="engineEXE"></param>
        /// <param name="engineExtraCommand"></param>
        /// <param name="runnerIndex">optional index of this runner within parallel set of runners</param>
        public UCIGameRunner(string engineEXE,
                             bool resetStateAndCachesBeforeMoves,
                             string extraCommandLineArguments = null,
                             string[] uciSetOptionCommands    = null,
                             int runnerIndex = -1)
        {
            EngineEXE = engineEXE;
            ResetStateAndCachesBeforeMoves = resetStateAndCachesBeforeMoves;
            EngineExtraCommand             = extraCommandLineArguments;
            Index = runnerIndex;

            ReadEvent readHandler = new ReadEvent(DataRead);

            string engine1Name = new FileInfo(engineEXE).Name;

            engine = StartEngine(engine1Name, engineEXE, extraCommandLineArguments, readHandler);

            System.Threading.Thread.Sleep(20);

            if (uciSetOptionCommands != null)
            {
                foreach (string extraCommand in uciSetOptionCommands)
                {
                    engine.SendCommandLine(extraCommand);
                }
            }

            freq      = Stopwatch.Frequency;
            startTime = Stopwatch.GetTimestamp();
        }
Exemplo n.º 8
0
 /// <summary>
 /// Verifies that the read event is a span of text.
 /// </summary>
 public static void Span(ReadEvent e, string text)
 {
     Assert.AreEqual(EventType.Span, e.Type);
     Assert.IsFalse(e.Starred);
     Assert.IsNull(e.Parameter);
     Assert.AreEqual(text, e.Text);
 }
Exemplo n.º 9
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            SocketState state = (SocketState)ar.AsyncState;

            try
            {
                Socket client    = state.workSocket;
                int    bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    if (client.Available == 0)
                    {
                        string response = state.sb.ToString();

                        state.sb.Clear();

                        if (LoggingLevel == 1)
                        {
                            OnLogWriteEntry(EventLogEntryCodes.SocketClientDataReceived, new string[] { string.Empty });
                        }
                        else if (LoggingLevel == 2)
                        {
                            OnLogWriteEntry(EventLogEntryCodes.SocketClientDataReceived, new string[] { response });
                        }

                        ReadEvent.Invoke(new Payload
                                         (
                                             ReadEvent.Id,
                                             new PayloadSubject[] { new PayloadSubject(ReadEvent.Subjects[0], response) }
                                         ));
                    }

                    client.BeginReceive(state.buffer, 0, SocketState.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                }
            }
            catch (ObjectDisposedException)
            {
                ConnectionInError = true;
                // Connection Closed
            }
            catch (SocketException theSocketException)
            {
                OnSocketException(theSocketException);
            }
            catch (Exception theException)
            {
                ConnectionInError = true;

                if (!state.workSocket.Connected)
                {
                    InitialiseAfterDelay();
                }

                OnLogWriteEntry(EventLogEntryCodes.SocketClientException, new string[] { theException.Message });
            }
        }
Exemplo n.º 10
0
        public int Read(byte[] buffer, int offset, int count)
        {
            int readCount = parent.Read(buffer, offset, count);

            var args = new WaveProviderReadEventArgs(buffer, offset, count, readCount);

            ReadEvent?.Invoke(this, args);

            return(readCount);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Monitor the specified tag for changes
        /// </summary>
        /// <typeparam name="T">the type of tag to monitor</typeparam>
        /// <param name="tag">The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name.
        /// E.g: the tag `foo.bar` monitors the tag `bar` on the folder `foo`</param>
        /// <param name="callback">the callback to execute when the value is changed.
        /// The first parameter is a MonitorEvent object which represents the data point, the second is an `unsubscribe` function to unsubscribe the callback</param>
        public void Monitor <T>(string tag, Action <ReadEvent <T>, Action> callback)
        {
            var node = FindNode(tag);

            var sub = new Subscription
            {
                PublishingInterval = _options.DefaultMonitorInterval,
                PublishingEnabled  = true,
                LifetimeCount      = _options.SubscriptionLifetimeCount,
                KeepAliveCount     = _options.SubscriptionKeepAliveCount,
                DisplayName        = tag,
                Priority           = byte.MaxValue
            };

            var item = new MonitoredItem
            {
                StartNodeId      = node.NodeId,
                AttributeId      = Attributes.Value,
                DisplayName      = tag,
                SamplingInterval = _options.DefaultMonitorInterval
            };

            sub.AddItem(item);
            _session.AddSubscription(sub);
            sub.Create();
            sub.ApplyChanges();

            item.Notification += (monitoredItem, args) =>
            {
                var    p           = (MonitoredItemNotification)args.NotificationValue;
                var    t           = p.Value.WrappedValue.Value;
                Action unsubscribe = () =>
                {
                    sub.RemoveItems(sub.MonitoredItems);
                    sub.Delete(true);
                    _session.RemoveSubscription(sub);
                    sub.Dispose();
                };

                var monitorEvent = new ReadEvent <T>();
                monitorEvent.Value           = (T)t;
                monitorEvent.SourceTimestamp = p.Value.SourceTimestamp;
                monitorEvent.ServerTimestamp = p.Value.ServerTimestamp;
                if (StatusCode.IsGood(p.Value.StatusCode))
                {
                    monitorEvent.Quality = Quality.Good;
                }
                if (StatusCode.IsBad(p.Value.StatusCode))
                {
                    monitorEvent.Quality = Quality.Bad;
                }
                callback(monitorEvent, unsubscribe);
            };
        }
Exemplo n.º 12
0
        private void RecieveSocket(IAsyncResult ar)
        {
            var socket  = (System.Net.Sockets.Socket)ar.AsyncState;
            var localEp = socket.LocalEndPoint;
            var count   = socket.EndReceive(ar);

            var readEventArgs = new ReadEventArgs(_buffer, count, localEp);

            ReadEvent?.Invoke(this, readEventArgs);
            BeginRead();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Read a tag asynchronously
        /// </summary>
        /// <typeparam name="T">The type of tag to read</typeparam>
        /// <param name="tag">The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name.
        /// E.g: the tag `foo.bar` reads the tag `bar` on the folder `foo`</param>
        /// <returns>The value retrieved from the OPC</returns>
        public Task <ReadEvent <T> > ReadAsync <T>(string tag)
        {
            var nodesToRead = BuildReadValueIdCollection(tag, Attributes.Value);

            // Wrap the ReadAsync logic in a TaskCompletionSource, so we can use C# async/await syntax to call it:
            var taskCompletionSource = new TaskCompletionSource <ReadEvent <T> >();

            _session.BeginRead(
                requestHeader: null,
                maxAge: 0,
                timestampsToReturn: TimestampsToReturn.Neither,
                nodesToRead: nodesToRead,
                callback: ar =>
            {
                DataValueCollection results;
                DiagnosticInfoCollection diag;
                var response = _session.EndRead(
                    result: ar,
                    results: out results,
                    diagnosticInfos: out diag);

                try
                {
                    CheckReturnValue(response.ServiceResult);
                    var val                   = results[0];
                    var readEvent             = new ReadEvent <T>();
                    readEvent.Value           = (T)val.Value;
                    readEvent.SourceTimestamp = val.SourceTimestamp;
                    readEvent.ServerTimestamp = val.ServerTimestamp;
                    if (StatusCode.IsGood(val.StatusCode))
                    {
                        readEvent.Quality = Quality.Good;
                    }
                    if (StatusCode.IsBad(val.StatusCode))
                    {
                        readEvent.Quality = Quality.Bad;
                    }
                    taskCompletionSource.TrySetResult(readEvent);
                }
                catch (Exception ex)
                {
                    taskCompletionSource.TrySetException(ex);
                }
            },
                asyncState: null);

            return(taskCompletionSource.Task);
        }
Exemplo n.º 14
0
 public RFIDReader()
 {
     s = new SdSerial((string log) =>
     {
         //Console.WriteLine("Log: " + log);
     },
                      (byte[] message) =>
     {
         Console.WriteLine("NFC read with ID: " + BitConverter.ToString(message, 0, message.Length));
         ReadEvent?.Invoke(this, new NfcReaderReadEventArgs(message));
     },
                      commands,
                      31, 115200);
     s.setTrace(true);
     s.connect("COM6", "");
 }
Exemplo n.º 15
0
        /// <summary>
        /// Monitor the specified tag for changes
        /// </summary>
        /// <typeparam name="T">the type of tag to monitor</typeparam>
        /// <param name="tag">The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name.
        /// E.g: the tag `foo.bar` monitors the tag `bar` on the folder `foo`</param>
        /// <param name="callback">the callback to execute when the value is changed.
        /// The first parameter is a MonitorEvent object which represents the data point, the second is an `unsubscribe` function to unsubscribe the callback</param>
        public void Monitor <T>(string tag, Action <ReadEvent <T>, Action> callback)
        {
            var subItem = new OpcDa.SubscriptionState
            {
                Name       = (++_sub).ToString(CultureInfo.InvariantCulture),
                Active     = true,
                UpdateRate = DefaultMonitorInterval
            };
            var sub = _server.CreateSubscription(subItem);

            // I have to start a new thread here because unsubscribing
            // the subscription during a datachanged event causes a deadlock
            Action unsubscribe = () => new Thread(o =>
                                                  _server.CancelSubscription(sub)).Start();

            sub.DataChanged += (handle, requestHandle, values) =>
            {
                T casted;
                TryCastResult(values[0].Value, out casted);
                var monitorEvent = new ReadEvent <T>();
                monitorEvent.Value           = casted;
                monitorEvent.SourceTimestamp = values[0].Timestamp;
                monitorEvent.ServerTimestamp = values[0].Timestamp;
                if (values[0].Quality == OpcDa.Quality.Good)
                {
                    monitorEvent.Quality = Quality.Good;
                }
                if (values[0].Quality == OpcDa.Quality.Bad)
                {
                    monitorEvent.Quality = Quality.Bad;
                }
                callback(monitorEvent, unsubscribe);
            };
            sub.AddItems(new[] { new OpcDa.Item {
                                     ItemName = tag
                                 } });
            sub.SetEnabled(true);
        }
Exemplo n.º 16
0
        private void Read(Status status, int readerIdx, CommandProcessorContext context,
                          ManualResetEventSlim finishedEvent)
        {
            TcpTypedConnection <byte[]> connection;
            var iteration = new AutoResetEvent(false);

            var successes = 0;
            var fails     = 0;

            var rnd = new Random(readerIdx);

            var streamIdx = -1;
            var eventidx  = -1;

            Action <TcpTypedConnection <byte[]>, TcpPackage> packageReceived = (conn, pkg) => {
                var dto = pkg.Data.Deserialize <ReadEventCompleted>();
                switch (dto.Result)
                {
                case ReadEventCompleted.Types.ReadEventResult.Success:
                    if (Equal(_streams[streamIdx], eventidx, dto.Event.Event.EventType, dto.Event.Event.Data.ToByteArray()))
                    {
                        successes++;
                        if (successes % 1000 == 0)
                        {
                            status.ReportReadsProgress(readerIdx, successes, fails);
                        }
                    }
                    else
                    {
                        fails++;
                        status.ReportReadError(readerIdx, _streams[streamIdx], eventidx);
                    }

                    break;

                case ReadEventCompleted.Types.ReadEventResult.NotFound:
                case ReadEventCompleted.Types.ReadEventResult.NoStream:
                case ReadEventCompleted.Types.ReadEventResult.StreamDeleted:
                case ReadEventCompleted.Types.ReadEventResult.Error:
                case ReadEventCompleted.Types.ReadEventResult.AccessDenied:
                    fails++;
                    status.ReportNotFoundOnRead(readerIdx, _streams[streamIdx], eventidx);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                iteration.Set();
            };
            Action <TcpTypedConnection <byte[]> >             established = _ => { };
            Action <TcpTypedConnection <byte[]>, SocketError> closed      = null;

            closed = (_, __) => {
                if (!context._tcpTestClient.Options.Reconnect)
                {
                    return;
                }
                Thread.Sleep(TimeSpan.FromSeconds(1));
                connection =
                    context._tcpTestClient.CreateTcpConnection(context, packageReceived, cn => iteration.Set(), closed, false);
            };

            connection = context._tcpTestClient.CreateTcpConnection(context, packageReceived, established, closed, false);

            while (!_stopReading)
            {
                streamIdx = NextStreamForReading(rnd, readerIdx);
                int head;
                lock (_heads)
                    head = _heads[streamIdx];

                if (head > 0)
                {
                    eventidx = NextRandomEventVersion(rnd, head);
                    var stream = _streams[streamIdx];
                    var corrid = Guid.NewGuid();
                    var read   = new ReadEvent(stream, eventidx, resolveLinkTos: false,
                                               requireLeader: false);
                    var package = new TcpPackage(TcpCommand.ReadEvent, corrid, read.Serialize());

                    connection.EnqueueSend(package.AsByteArray());
                    iteration.WaitOne();
                }
                else
                {
                    Thread.Sleep(100);
                }
            }

            status.ReportReadsProgress(readerIdx, successes, fails);
            status.FinilizeStatus(readerIdx, fails == 0);
            context._tcpTestClient.Options.Reconnect = false;
            connection.Close();
            finishedEvent.Set();
        }
Exemplo n.º 17
0
 public static int ReadCheckpoint(Hashtable h)
 {
     return(ReadEvent.ReadKeyFromHashtable <int>(h, Constants.LEVEL_EVENT_KEY));
 }
Exemplo n.º 18
0
 public static float ReadDistance(Hashtable h)
 {
     return(ReadEvent.ReadKeyFromHashtable <float>(h, distanceKey));
 }
Exemplo n.º 19
0
 private void Awake()
 {
     _instance = gameObject.GetComponent <ReadEvent>();
     SetPanelProperty();
 }
Exemplo n.º 20
0
 protected virtual void OnRead(TelnetReadEventArgs e)
 {
     ReadEvent?.Invoke(this, e);
 }
Exemplo n.º 21
0
 protected void onRead(VncReadEventArgs a_args)
 {
     ReadEvent?.Invoke(this, a_args);
 }
Exemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="exe"></param>
        /// <param name="extraCommand"></param>
        /// <param name="readHandler"></param>
        /// <param name="numThreads">N.B. when doing single static position evals from LC0, must set to 1</param>
        /// <returns></returns>
        UCIEngineProcess StartEngine(string engineName, string exePath, string extraCommand, ReadEvent readHandler, int numThreads = 1)
        {
            UCIEngineProcess engine = new UCIEngineProcess(engineName, exePath, extraCommand);

            engine.ReadEvent += readHandler;
            engine.StartEngine();

            engine.ReadAsync();

            engine.SendCommandLine("uci");
            engine.SendIsReadyAndWaitForOK();

            return(engine);
        }
Exemplo n.º 23
0
        private void ReadFlood(CommandProcessorContext context, string streamPrefix, int clientsCnt, long requestsCnt, int streamsCnt,
                               bool resolveLinkTos, bool requireLeader, RequestMonitor monitor)
        {
            context.IsAsync();

            string[] streams = streamsCnt == 1
                                ? new[] { streamPrefix }
                                : Enumerable.Range(0, streamsCnt).Select(x => $"{streamPrefix}-{x}").ToArray();

            context.Log.Information("Reading streams {first} through to {last}",
                                    streams.FirstOrDefault(),
                                    streams.LastOrDefault());

            var  clients   = new List <TcpTypedConnection <byte[]> >();
            var  threads   = new List <Thread>();
            var  doneEvent = new ManualResetEventSlim(false);
            var  sw2       = new Stopwatch();
            long succ      = 0;
            long fail      = 0;
            long all       = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var  count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long received = 0;
                long sent     = 0;
                var  client   = context._tcpTestClient.CreateTcpConnection(
                    context,
                    (conn, pkg) => {
                    if (pkg.Command != TcpCommand.ReadEventCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize <ReadEventCompleted>();
                    monitor.EndOperation(pkg.CorrelationId);
                    if (dto.Result == ReadEventCompleted.Types.ReadEventResult.Success)
                    {
                        if (Interlocked.Increment(ref succ) % 1000 == 0)
                        {
                            Console.Write(".");
                        }
                    }
                    else
                    {
                        if (Interlocked.Increment(ref fail) % 1000 == 0)
                        {
                            Console.Write("#");
                        }
                    }

                    Interlocked.Increment(ref received);
                    var localAll = Interlocked.Increment(ref all);
                    if (localAll % 100000 == 0)
                    {
                        var elapsed = sw2.Elapsed;
                        sw2.Restart();
                        context.Log.Verbose("\nDONE TOTAL {reads} READS IN {elapsed} ({rate:0.0}/s).", localAll,
                                            elapsed, 1000.0 * 100000 / elapsed.TotalMilliseconds);
                    }

                    if (localAll == requestsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                var clientNum = i;
                threads.Add(new Thread(() => {
                    int streamIndex = (streamsCnt / clientsCnt) * clientNum;
                    context.Log.Information("Reader #{clientNum} performing {count} reads on {streamsCnt} streams starting at stream index {streamIndex}",
                                            clientNum, count, streamsCnt, streamIndex);
                    for (int j = 0; j < count; ++j)
                    {
                        var corrId = Guid.NewGuid();

                        var eventStreamId = streams[streamIndex++];
                        if (streamIndex >= streamsCnt)
                        {
                            streamIndex = 0;
                        }
                        var read    = new ReadEvent(eventStreamId, 0, resolveLinkTos, requireLeader);
                        var package = new TcpPackage(TcpCommand.ReadEvent, corrId, read.Serialize());
                        monitor.StartOperation(corrId);
                        client.EnqueueSend(package.AsByteArray());

                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) >
                               context._tcpTestClient.Options.ReadWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(client => client.Close());

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Information("Completed. READS succ: {success}, fail: {failures}.", Interlocked.Read(ref succ),
                                    Interlocked.Read(ref fail));
            context.Log.Information("{requests} requests completed in {elapsed}ms ({rate:0.00} reqs per sec).", all,
                                    sw.ElapsedMilliseconds, reqPerSec);
            monitor.GetMeasurementDetails();
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                              PerfUtils.Row(PerfUtils.Col("readsCnt", all)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            if (succ != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
Exemplo n.º 24
0
        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var        eventStreamId  = "test-stream";
            var        fromNumber     = 0;
            const bool resolveLinkTos = false;
            var        requireLeader  = false;

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

            context.IsAsync();

            var sw = new Stopwatch();

            context._tcpTestClient.CreateTcpConnection(
                context,
                connectionEstablished: conn => {
                context.Log.Information("[{remoteEndPoint}, L{localEndPoint}]: Reading...", conn.RemoteEndPoint,
                                        conn.LocalEndPoint);
                var readDto =
                    new ReadEvent(eventStreamId, fromNumber, resolveLinkTos, requireLeader);
                var package =
                    new TcpPackage(TcpCommand.ReadEvent, Guid.NewGuid(), readDto.Serialize()).AsByteArray();
                sw.Start();
                conn.EnqueueSend(package);
            },
                handlePackage: (conn, pkg) => {
                sw.Stop();
                context.Log.Information("Read request took: {elapsed}.", sw.Elapsed);

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

                var dto = pkg.Data.Deserialize <ReadEventCompleted>();
                context.Log.Information("READ events from <{stream}>:\n\n"
                                        + "\tEventStreamId: {stream}\n"
                                        + "\tEventNumber:   {eventNumber}\n"
                                        + "\tReadResult:    {readResult}\n"
                                        + "\tEventType:     {eventType}\n"
                                        + "\tData:          {data}\n"
                                        + "\tMetadata:      {metadata}\n",
                                        eventStreamId,
                                        eventStreamId,
                                        dto.Event.Event.EventNumber,
                                        dto.Result,
                                        dto.Event.Event.EventType,
                                        Helper.UTF8NoBom.GetString(dto.Event.Event.Data.ToByteArray()),
                                        Helper.UTF8NoBom.GetString(dto.Event.Event.Metadata.ToByteArray()));


                if (dto.Result == ReadEventCompleted.Types.ReadEventResult.Success)
                {
                    PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword),
                                                   (int)Math.Round(sw.Elapsed.TotalMilliseconds));
                    context.Success();
                }
                else
                {
                    context.Fail();
                }

                conn.Close();
            },
                connectionClosed: (connection, error) => context.Fail(reason: "Connection was closed prematurely."));

            return(true);
        }
Exemplo n.º 25
0
 public static Vector2 Read(Hashtable h)
 {
     return(ReadEvent.ReadKeyFromHashtable <Vector2>(h, PLAYER_MOVE_EVENT));
 }