Exemple #1
0
        private async Task Handle(EventData eventData)
        {
            try
            {
                HConsole.WriteLine(this, "Execute event handler");
                await eventData.Subscription.HandleAsync(eventData.Message).CfAwait();
            }
            catch (Exception e)
            {
                HConsole.WriteLine(this, "Handler has thrown.");

                Interlocked.Increment(ref _exceptionCount);
                var args          = new DistributedEventExceptionEventArgs(e, eventData.Message);
                var correlationId = eventData.Message.CorrelationId;

                try
                {
                    OnError?.Invoke(this, args);
                }
                catch (Exception ee)
                {
                    var ae = new AggregateException(e, ee);
                    _logger.LogError(ae, $"An event handler [{correlationId}] has thrown an unhandled exception. " +
                                     "In addition, the error handler has also thrown an exception.");
                }

                if (!args.Handled)
                {
                    Interlocked.Increment(ref _unhandledExceptionCount);
                    _logger.LogError(e, $"An event handler [{correlationId}] has thrown an unhandled exception.");
                }
            }
        }
        public void WritesOverloads()
        {
            var capture = new ConsoleCapture();

            var o = new object();

            HConsole.Configure(o, config => config.SetMaxLevel(0));

            using (capture.Output())
            {
                HConsole.WriteLine(o, "text0");
                HConsole.WriteLine(o, 0, "text1");
                HConsole.WriteLine(o, 2);
                HConsole.WriteLine(o, 0, 3);
                HConsole.WriteLine(o, "-{0}-", 4);
                HConsole.WriteLine(o, 0, "-{0}-", 5);

                HConsole.WriteLine(o, 1, "text1");
                HConsole.WriteLine(o, 1, 3);
                HConsole.WriteLine(o, 1, "-{0}-", 5);
            }

            Assert.That(capture.ReadToEnd().ToLf(), Is.EqualTo($@"{Prefix()}text0
{Prefix()}text1
{Prefix()}2
{Prefix()}3
{Prefix()}-4-
{Prefix()}-5-
".ToLf()));
        }
Exemple #3
0
        public void WritesOverloads()
        {
            var o = new object();

            HConsole.Configure(x => x.Set(o, xx => xx.SetLevel(0)));

            HConsole.WriteLine(o, "text0");
            HConsole.WriteLine(o, 0, "text1");
            HConsole.WriteLine(o, 2);
            HConsole.WriteLine(o, 0, 3);
            HConsole.WriteLine(o, "-{0}-", 4);
            HConsole.WriteLine(o, 0, "-{0}-", 5);

            HConsole.WriteLine(o, 1, "text1");
            HConsole.WriteLine(o, 1, 3);
            HConsole.WriteLine(o, 1, "-{0}-", 5);

            Assert.That(HConsole.Text.ToLf(), Is.EqualTo($@"{Prefix()}text0
{Prefix()}text1
{Prefix()}2
{Prefix()}3
{Prefix()}-4-
{Prefix()}-5-
".ToLf()));
        }
        public async Task Events()
        {
            var map = await Client.GetMapAsync <string, int>("map_" + CreateUniqueName()).CfAwait();

            await using var _ = DestroyAndDispose(map);

            var eventsCount = 0;
            var id          = await map.SubscribeAsync(on => on
                                                       .EntryAdded((sender, args) =>
            {
                HConsole.WriteLine(this, $"! added: {args.Key} {args.Value}");
                Interlocked.Increment(ref eventsCount);
            }));

            await map.SetAsync("a", 1).CfAwait();

            await map.SetAsync("b", 2).CfAwait();

            await AssertEx.SucceedsEventually(() =>
                                              Assert.That(eventsCount, Is.EqualTo(2)),
                                              4000, 500);

            await map.UnsubscribeAsync(id).CfAwait();

            await map.SetAsync("c", 3).CfAwait();

            await Task.Delay(500).CfAwait();

            Assert.AreEqual(2, eventsCount);
        }
Exemple #5
0
        private async ValueTask ReceiveMessage(Server server, ClientMessageConnection connection, ClientMessage message)
        {
            HConsole.WriteLine(this, "Respond");
            var text = Encoding.UTF8.GetString(message.FirstFrame.Bytes);

#if NETSTANDARD2_1
            var responseText = text switch
            {
                "a" => "alpha",
                "b" => "bravo",
                _ => "??"
            };
#else
            var responseText =
                text == "a" ? "alpha" :
                text == "b" ? "bravo" :
                "??";
#endif
            // this is very basic stuff and does not respect HZ protocol
            // the 64-bytes header is nonsense etc
            var response = new ClientMessage()
                           .Append(new Frame(new byte[64])) // header stuff
                           .Append(new Frame(Encoding.UTF8.GetBytes(responseText)));

            response.CorrelationId = message.CorrelationId;
            response.MessageType   = 0x1; // 0x00 means exception

            // send in one fragment, set flags
            response.Flags |= ClientMessageFlags.BeginFragment | ClientMessageFlags.EndFragment;

            await connection.SendAsync(response).CfAwait();

            HConsole.WriteLine(this, "Responded");
        }
        public async Task AsyncEvents()
        {
            var map = await Client.GetMapAsync <string, int>("map_" + CreateUniqueName()).CfAwait();

            await using var _ = DestroyAndDispose(map);

            var eventsCount = 0;
            var id          = await map.SubscribeAsync(on => on
                                                       .EntryAdded(async(sender, args) =>
            {
                await Task.Yield();
                HConsole.WriteLine(this, $"! added: {args.Key} {args.Value}");
                Interlocked.Increment(ref eventsCount);
            }));

            await map.SetAsync("a", 1).CfAwait();

            await map.SetAsync("b", 2).CfAwait();

            while (eventsCount < 2)
            {
                await Task.Delay(500).CfAwait();
            }

            await map.UnsubscribeAsync(id).CfAwait();

            await map.SetAsync("c", 3).CfAwait();

            await Task.Delay(500).CfAwait();

            Assert.AreEqual(2, eventsCount);
        }
Exemple #7
0
        public async Task Cluster()
        {
            // this test expects a server

            HConsole.Configure(x => x.Configure(this).SetIndent(0).SetPrefix("TEST"));
            HConsole.WriteLine(this, "Begin");

            HConsole.WriteLine(this, "Cluster?");

            var serializationService = new SerializationServiceBuilder(new NullLoggerFactory())
                                       .SetVersion(1)
                                       .Build();

            var options = new HazelcastOptions();

            //options.Networking.Addresses.Add("sgay-l4");
            options.Networking.Addresses.Add("localhost");

            var cluster = new Cluster(options, serializationService, new NullLoggerFactory());
            await cluster.Connections.ConnectAsync(CancellationToken.None).CfAwait();

            // now we can send messages...
            //await cluster.SendAsync(new ClientMessage()).CAF();

            // events?
            await Task.Delay(4000).CfAwait();

            HConsole.WriteLine(this, "End");
            await Task.Delay(100).CfAwait();
        }
Exemple #8
0
        /// <summary>
        /// Subscribes a connection to cluster events.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="correlationId">The correlation identifier.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A task that will complete when the subscription has been processed, and represent whether it was successful.</returns>
        private async Task <bool> SubscribeToClusterEventsAsync(MemberConnection connection, long correlationId, CancellationToken cancellationToken)
        {
            // aka subscribe to member/partition view events
            HConsole.TraceLine(this, "subscribe");

            // handles the event
            ValueTask HandleEventAsync(ClientMessage message, object _)
            => ClientAddClusterViewListenerCodec.HandleEventAsync(message,
                                                                  HandleCodecMemberViewEvent,
                                                                  HandleCodecPartitionViewEvent,
                                                                  connection.Id,
                                                                  _clusterState.LoggerFactory);

            try
            {
                var subscribeRequest = ClientAddClusterViewListenerCodec.EncodeRequest();
                _correlatedSubscriptions[correlationId] = new ClusterSubscription(HandleEventAsync);
                _ = await _clusterMessaging.SendToMemberAsync(subscribeRequest, connection, correlationId, cancellationToken).CfAwait();

                HConsole.WriteLine(this, "subscribed");
                return(true);
            }
            catch (Exception e)
            {
                HConsole.WriteLine(this, "failed " + e);
                _correlatedSubscriptions.TryRemove(correlationId, out _);
                _logger.LogWarning(e, "Failed to subscribe to cluster events, may retry.");
                return(false);
            }
        }
Exemple #9
0
        public async ValueTask DisposeAsync()
        {
            // note: DisposeAsync should not throw (CA1065)

            if (Interlocked.CompareExchange(ref _active, 0, 1) == 0)
            {
                return;
            }

            HConsole.WriteLine(this, "Stopping...");

            _cancel.Cancel();

            try
            {
                await _heartbeating.CfAwaitCanceled();
            }
            catch (Exception e)
            {
                // unexpected
                _logger.LogWarning(e, "Caught an exception while disposing Heartbeat.");
            }

            _cancel.Dispose();

            HConsole.WriteLine(this, "Stopped.");
        }
        // background task that connect members
        private async Task ConnectMembers(CancellationToken cancellationToken)
        {
            await foreach (var(member, token) in _clusterMembers.MembersToConnect.WithCancellation(cancellationToken))
            {
                HConsole.WriteLine(this, $"Ensure a connection for member {member.Id.ToShortString()} (at {member.Address})");

                var(ensured, wasCanceled, exception) = await EnsureConnectionInternalAsync(member, token, cancellationToken).CfAwait();

                if (ensured)
                {
                    continue;
                }

                if (_disposed > 0)
                {
                    _logger.LogWarning($"Could not connect to member at {member.Address}: shutting down.");
                }
                else
                {
                    var details = wasCanceled ? "canceled" : "failed";
                    _logger.LogWarning(exception, $"Could not connect to member at {member.Address}: {details}.");

                    _clusterMembers.FailedToConnect(member);
                }
            }
        }
Exemple #11
0
        /// <inheritdoc />
        public async Task CommitAsync()
        {
            if (State != TransactionState.Active)
            {
                throw new InvalidOperationException("There is no active transaction to commit.");
            }

            if (_threadId != ContextId)
            {
                HConsole.WriteLine(this, $"Commit transaction on context #{ContextId} that was started on #{_threadId}");
                throw new InvalidOperationException("Transactions cannot span multiple async contexts.");
            }

            HConsole.WriteLine(this, $"Commit transaction on context #{ContextId}");

            try
            {
                var requestMessage  = TransactionCommitCodec.EncodeRequest(TransactionId, ContextId);
                var responseMessage = await _cluster.Messaging.SendToMemberAsync(requestMessage, _connection).CfAwait();

                _     = TransactionCommitCodec.DecodeResponse(responseMessage);
                State = TransactionState.Committed;
            }
            catch
            {
                State = TransactionState.RollingBack;
                throw;
            }
            finally
            {
                lock (_inTransactionMutex) AsyncContext.Current.InTransaction = false;
            }
        }
        private async Task Handle(int partitionId, Queue queue)
        {
            // using (!_disposed) condition here instead of (true) means
            // that on shutdown queued events will be dropped - otherwise,
            // we could have a ton of events to process and shutting down
            // would take time - TODO: is this the right decision?

            while (!_disposed)
            {
                if (!queue.TryDequeue(out var eventData))
                {
                    lock (_mutex)
                    {
                        if (!queue.TryDequeue(out eventData))
                        {
                            HConsole.WriteLine(this, $"Release queue:{partitionId}");
                            _queues.Remove(partitionId);
                            queue.Task = null;
                            _pool.Return(queue);
                            return;
                        }
                    }
                }

                await Handle(eventData).CfAwait(); // does not throw
            }
        }
Exemple #13
0
 public static void WriteMethodInfoToConsole([System.Runtime.CompilerServices.CallerMemberName] string memberName    = "",
                                             [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath  = "",
                                             [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
 {
     HConsole.WriteLine("MemberName: " + memberName);
     HConsole.WriteLine("SourceFilePath: " + sourceFilePath);
     HConsole.WriteLine("SourceLineNumber: " + sourceLineNumber);
 }
Exemple #14
0
        public async Task TimeoutsAfterMultipleRetries()
        {
            var address = NetworkAddress.Parse("127.0.0.1:11001");

            using var _ = HConsole.Capture(consoleOptions => consoleOptions
                                           .ClearAll()
                                           .Configure().SetMaxLevel()
                                           .Configure(this).SetPrefix("TEST")
                                           .Configure <AsyncContext>().SetMinLevel()
                                           .Configure <SocketConnectionBase>().SetIndent(1).SetLevel(0).SetPrefix("SOCKET"));

            HConsole.WriteLine(this, "Begin");

            HConsole.WriteLine(this, "Start server");
            await using var server = new Server(address, async(xsvr, xconn, xmsg)
                                                => await HandleAsync(xsvr, xconn, xmsg, async(svr, conn, msg) =>
            {
                HConsole.WriteLine(svr, "Handle request (wait...)");
                await Task.Delay(500).CfAwait();

                HConsole.WriteLine(svr, "Respond with error.");
                var response = ErrorsServerCodec.EncodeResponse(new[]
                {
                    // make sure the error is retryable
                    new ErrorHolder(RemoteError.RetryableHazelcast, "classname", "message", Enumerable.Empty <StackTraceElement>())
                });

                //HConsole.WriteLine(svr, "Respond with success.");
                //var response = ClientPingServerCodec.EncodeResponse();

                response.CorrelationId = msg.CorrelationId;
                await conn.SendAsync(response).CfAwait();
            }), LoggerFactory);
            await server.StartAsync().CfAwait();

            HConsole.WriteLine(this, "Start client");
            var options = HazelcastOptions.Build(configure: (configuration, options) =>
            {
                options.Networking.Addresses.Add("127.0.0.1:11001");
                options.Messaging.RetryTimeoutSeconds = 3; // default value is 120s
            });

            await using var client = (HazelcastClient) await HazelcastClientFactory.StartNewClientAsync(options);

            HConsole.WriteLine(this, "Send message");
            var message = ClientPingServerCodec.EncodeRequest();

            // note: the error only happens *after* the server has responded
            // we could wait for the response for ever
            await AssertEx.ThrowsAsync <TaskTimeoutException>(async() =>
            {
                // server will respond w/ error every 500ms and client will retry
                // until the 3s retry timeout (options above) is reached
                await client.Cluster.Messaging.SendAsync(message).CfAwait();
            });

            await server.StopAsync().CfAwait();
        }
        // runs once on a connection to a member
        private async Task RunAsync(MemberConnection connection, DateTime now, CancellationToken cancellationToken)
        {
            // must ensure that timeout > interval ?!

            var readElapsed  = now - connection.LastReadTime;
            var writeElapsed = now - connection.LastWriteTime;

            HConsole.WriteLine(this, $"Heartbeat on {connection.Id.ToShortString()}, written {(long)(now - connection.LastWriteTime).TotalMilliseconds}ms ago, read {(long)(now - connection.LastReadTime).TotalMilliseconds}ms ago");

            // make sure we read from the client at least every 'timeout',
            // which is greater than the interval, so we *should* have
            // read from the last ping, if nothing else, so no read means
            // that the client not responsive - terminate it

            if (readElapsed > _timeout && writeElapsed < _period)
            {
                _logger.LogWarning("Heartbeat timeout for connection {ConnectionId}.", connection.Id);
                if (connection.Active)
                {
                    await connection.TerminateAsync().CfAwait();                    // does not throw;
                }
                return;
            }

            // make sure we write to the client at least every 'interval',
            // this should trigger a read when we receive the response
            if (writeElapsed > _period)
            {
                _logger.LogDebug("Ping client {ClientId}", connection.Id);

                var requestMessage = ClientPingCodec.EncodeRequest();

                try
                {
                    // ping should complete within the default invocation timeout
                    var responseMessage = await _clusterMessaging
                                          .SendToMemberAsync(requestMessage, connection, cancellationToken)
                                          .CfAwait();

                    // just to be sure everything is ok
                    _ = ClientPingCodec.DecodeResponse(responseMessage);
                }
                catch (TaskTimeoutException)
                {
                    _logger.LogWarning("Heartbeat ping timeout for connection {ConnectionId}.", connection.Id);
                    if (connection.Active)
                    {
                        await connection.TerminateAsync().CfAwait();                    // does not throw;
                    }
                }
                catch (Exception e)
                {
                    // unexpected
                    _logger.LogWarning(e, "Heartbeat has thrown an exception.");
                }
            }
        }
        public async Task Test()
        {
            //var host = Dns.GetHostEntry(_hostname);
            //var ipAddress = host.AddressList[0];
            //var endpoint = new IPEndPoint(ipAddress, _port);

            var address = NetworkAddress.Parse("127.0.0.1:11001");

            HConsole.Configure(this, config => config.SetIndent(0).SetPrefix("TEST"));
            HConsole.WriteLine(this, "Begin");

            HConsole.WriteLine(this, "Start server");
            var server = new Server(address, ReceiveMessage, LoggerFactory);
            await server.StartAsync().CAF();

            var options = HazelcastOptions.Build(Array.Empty <string>(), configure: (configuration, options) =>
            {
                options.Networking.Addresses.Add("127.0.0.1:11001");
            });

            HConsole.WriteLine(this, "Start client 1");
            await using var client1 = (HazelcastClient)HazelcastClientFactory.CreateClient(options);
            await client1.StartAsync().CAF();

            HConsole.WriteLine(this, "Send message 1 to client 1");
            var message  = CreateMessage("ping");
            var response = await client1.Cluster.Messaging.SendAsync(message, CancellationToken.None).CAF();

            HConsole.WriteLine(this, "Got response: " + GetText(response));

            HConsole.WriteLine(this, "Start client 2");
            await using var client2 = (HazelcastClient)HazelcastClientFactory.CreateClient(options);
            await client2.StartAsync().CAF();

            HConsole.WriteLine(this, "Send message 1 to client 2");
            message  = CreateMessage("a");
            response = await client2.Cluster.Messaging.SendAsync(message, CancellationToken.None).CAF();

            HConsole.WriteLine(this, "Got response: " + GetText(response));

            HConsole.WriteLine(this, "Send message 2 to client 1");
            message  = CreateMessage("foo");
            response = await client1.Cluster.Messaging.SendAsync(message, CancellationToken.None).CAF();

            HConsole.WriteLine(this, "Got response: " + GetText(response));

            //XConsole.WriteLine(this, "Stop client");
            //await client1.CloseAsync().CAF();

            HConsole.WriteLine(this, "Stop server");
            await server.StopAsync().CAF();

            await Task.Delay(1000).CAF();

            HConsole.WriteLine(this, "End");
            await Task.Delay(100).CAF();
        }
Exemple #17
0
        public static List <DotNetBarSettings> ReadBarSettingFromXML()
        {
            Util.WriteMethodInfoToConsole();
            List <DotNetBarSettings> retValue = null;

            if (File.Exists(xmlFile))
            {
                retValue = new List <DotNetBarSettings>();
                DotNetBarSettings setting;
                XmlTextReader     textReader = new XmlTextReader(xmlFile);
                textReader.Read();
                // If the node has value
                while (textReader.Read())
                {
                    if (textReader.Name.ToUpper().StartsWith("DOTNETBAR"))
                    {
                        if (textReader.HasAttributes)
                        {
                            setting = new DotNetBarSettings();
                            while (textReader.MoveToNextAttribute())
                            {
                                HConsole.WriteLine(string.Format("{0} --> {1}", textReader.Name, textReader.Value));
                                switch (textReader.Name)
                                {
                                case "Name":
                                    setting.Name = textReader.Value;
                                    break;

                                case "Docked":
                                    setting.Docked = textReader.Value;
                                    break;

                                case "Position":
                                    setting.Position = textReader.Value;
                                    break;

                                case "State":
                                    setting.State = textReader.Value;
                                    break;

                                case "AutoHide":
                                    setting.AutoHide = textReader.Value;
                                    break;

                                case "Visible":
                                    setting.Visible = textReader.Value;
                                    break;
                                }
                            }
                            retValue.Add(setting);
                        }
                    }
                }
                textReader.Close();
            }
            return(retValue);
        }
Exemple #18
0
        public void WritesNothingByDefault()
        {
            var o = new object();

            HConsole.WriteLine(o, "text0"); // default level is 0
            HConsole.WriteLine(o, 1, "text1");

            Assert.That(HConsole.Text.ToLf(), Is.EqualTo("".ToLf()));
        }
        public void ArgumentExceptions()
        {
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, "text"));
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, 1));
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, 0, "text"));
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, 0, "{0}", 0));
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, 0, 1));

            Assert.Throws <ArgumentNullException>(() => HConsole.Lines(null, 0, ""));
        }
Exemple #20
0
        public void WritesOtherLevelsIfConfigured()
        {
            var o = new object();

            HConsole.Configure(x => x.Set(o, xx => xx.SetLevel(1)));

            HConsole.WriteLine(o, "text0"); // default level is 0
            HConsole.WriteLine(o, 1, "text1");

            Assert.That(HConsole.Text.ToLf(), Is.EqualTo($"{Prefix()}text0\n{Prefix()}text1\n".ToLf()));
        }
Exemple #21
0
        /// <summary>
        /// Begins the transaction.
        /// </summary>
        public async Task BeginAsync()
        {
            if (State != TransactionState.None)
            {
                throw new InvalidOperationException("The transaction context is already involved in a transaction.");
            }

            var asyncContext = AsyncContext.Current;

            lock (_inTransactionMutex)
            {
                // this is used to prevent an asynchronous context from being in multiple (thus nested) transactions,
                // it was implemented, before async, via a [ThreadStatic] boolean (when everything was bound to
                // threads) which cannot be appropriate anymore. instead we move it to the async context.

                if (asyncContext.InTransaction)
                {
                    throw new InvalidOperationException("Nested transactions are not supported.");
                }
                asyncContext.InTransaction = true;
            }

            _connection = _cluster.Members.GetRandomConnection();
            if (_connection == null)
            {
                throw _cluster.State.ThrowClientOfflineException();
            }

            _threadId = ContextId;
            //_startTime = Clock.Milliseconds;

            HConsole.WriteLine(this, $"Begin transaction on context #{ContextId}");

            try
            {
                // codec wants 0 for server config, -1 for infinite (?)
                var timeoutMs = _options.Timeout.RoundedMilliseconds(false);

                var requestMessage  = TransactionCreateCodec.EncodeRequest(timeoutMs, _options.Durability, (int)_options.Type, ContextId);
                var responseMessage = await _cluster.Messaging.SendToMemberAsync(requestMessage, _connection).CfAwait();

                TransactionId = TransactionCreateCodec.DecodeResponse(responseMessage).Response;
                State         = TransactionState.Active;
            }
            catch
            {
                lock (_inTransactionMutex) asyncContext.InTransaction = false;
                _threadId = 0;
                //_startTime = 0;
                TransactionId = default;
                State         = TransactionState.None;
                throw;
            }
        }
        public void ArgumentExceptions()
        {
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, "text"));
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, 1));
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, 0, "text"));
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, 0, "{0}", 0));
            Assert.Throws <ArgumentNullException>(() => HConsole.WriteLine(null, 0, 1));
            Assert.Throws <ArgumentNullException>(() => HConsole.Configure(new object(), null));
            Assert.Throws <ArgumentNullException>(() => HConsole.Configure <object>(null));

            Assert.Throws <ArgumentNullException>(() => HConsole.Lines(null, 0, ""));
        }
Exemple #23
0
        public void WritesWithPrefix()
        {
            HConsole.Configure(x => x.Set <object>(xx => xx.SetPrefix("XX")));

            var o = new object();

            HConsole.Configure(x => x.Set(o, xx => xx.SetLevel(0)));

            HConsole.WriteLine(o, "text0");

            Assert.That(HConsole.Text.ToLf(), Is.EqualTo($"{Prefix("XX")}text0\n".ToLf()));
        }
        // tries to authenticate
        // returns a result if successful
        // returns null if failed due to credentials (may want to retry)
        // throws if anything else went wrong
        private async ValueTask <AuthenticationResult> TryAuthenticateAsync(MemberConnection client, string clusterName, Guid clusterClientId, string clusterClientName, ISet <string> labels, ICredentialsFactory credentialsFactory, CancellationToken cancellationToken)
        {
            const string clientType = "CSP"; // CSharp

            var serializationVersion = _serializationService.GetVersion();
            var clientVersion        = ClientVersion;
            var credentials          = credentialsFactory.NewCredentials();

            ClientMessage requestMessage;

            switch (credentials)
            {
            case IPasswordCredentials passwordCredentials:
                requestMessage = ClientAuthenticationCodec.EncodeRequest(clusterName, passwordCredentials.Name, passwordCredentials.Password, clusterClientId, clientType, serializationVersion, clientVersion, clusterClientName, labels);
                break;

            case ITokenCredentials tokenCredentials:
                requestMessage = ClientAuthenticationCustomCodec.EncodeRequest(clusterName, tokenCredentials.GetToken(), clusterClientId, clientType, serializationVersion, clientVersion, clusterClientName, labels);
                break;

            default:
                var bytes = _serializationService.ToData(credentials).ToByteArray();
                requestMessage = ClientAuthenticationCustomCodec.EncodeRequest(clusterName, bytes, clusterClientId, clientType, serializationVersion, clientVersion, clusterClientName, labels);
                break;
            }

            cancellationToken.ThrowIfCancellationRequested();

            HConsole.WriteLine(this, "Send auth request");
            var responseMessage = await client.SendAsync(requestMessage).CfAwait();

            HConsole.WriteLine(this, "Rcvd auth response");
            var response = ClientAuthenticationCodec.DecodeResponse(responseMessage);

            HConsole.WriteLine(this, "Auth response is: " + (AuthenticationStatus)response.Status);

            return((AuthenticationStatus)response.Status switch
            {
                AuthenticationStatus.Authenticated
                => new AuthenticationResult(response.ClusterId, response.MemberUuid, response.Address, response.ServerHazelcastVersion, response.FailoverSupported, response.PartitionCount, response.SerializationVersion, credentials.Name),

                AuthenticationStatus.CredentialsFailed
                => null,     // could want to retry

                AuthenticationStatus.NotAllowedInCluster
                => throw new AuthenticationException("Client is not allowed in cluster."),

                AuthenticationStatus.SerializationVersionMismatch
                => throw new AuthenticationException("Serialization mismatch."),

                _ => throw new AuthenticationException($"Received unsupported status code {response.Status}.")
            });
Exemple #25
0
        public static void Click(SideBarPanelItem sideBar,
                                 SuperTabControl superTabControl, ButtonItem ClickedButton, SuperTabItem TabItem)
        {
            Util.WriteMethodInfoToConsole();
            try
            {
                HConsole.WriteLine(LastCheckedButton.Text + " (" + LastCheckedButton.Name + ") --> unchecked");
                LastCheckedButton.Checked = false;
            }
            catch { }
            foreach (ButtonItem bi in sideBar.SubItems)
            {
                if (bi.Name == ClickedButton.Name)
                {
                    bi.Checked = true;
                    HConsole.WriteLine(bi.Text + " (" + bi.Name + ") --> is now LastCheckedButton");
                    LastCheckedButton = bi;
                }
                else
                {
                    bi.Checked = false;
                }
            }
            //System.Windows.Forms.Form MainForm = System.Windows.Forms.Application.OpenForms.Cast<System.Windows.Forms.Form>().Where(x => x.Name == "frmMain").FirstOrDefault();
            //var c = GetAllControlsOfType(MainForm, typeof(SideBar));
            //Console.WriteLine("Total ButtonItem Controls: " + c.Count());
            if (TabItem != null)
            {
                foreach (SuperTabItem sti in superTabControl.Tabs)
                {
                    if (sti.Name == TabItem.Name)
                    {
                        sti.Visible = true;
                        sti.Text    = ClickedButton.Text;
                    }
                    else
                    {
                        sti.Visible = false;
                    }
                }
                superTabControl.Visible = true;
            }
            else
            {
                superTabControl.Visible = false;
            }

            //if (!superTabControl.Visible)
            //{
            //    superTabControl.Visible = true;
            //}
        }
Exemple #26
0
        public void MoveWorkItem(WorkGroup fromWorkGroup, WorkGroup toWorkGroup, Organization oe)
        {
            Util.WriteMethodInfoToConsole();
            ProcessInstance PI = null;

            List <AccessRule> Rules   = new List <AccessRule>();
            AccessRule        arRead  = new AccessRule(session, CCD.Domea.Fw.Base.AccessType.Read, RuleType.SpecificOrganization, oe);
            AccessRule        arWrite = new AccessRule(session, CCD.Domea.Fw.Base.AccessType.Write, RuleType.SpecificOrganization, oe);

            //Rules.Add(new AccessRule(session, CCD.Domea.Fw.Base.AccessType.Read, RuleType.SpecificOrganization, oe));
            //Rules.Add(new AccessRule(session, CCD.Domea.Fw.Base.AccessType.Write, RuleType.SpecificOrganization, oe));
            counter      = 0;
            sWatchMovePI = new Stopwatch();
            foreach (WorkItem wi in fromWorkGroup.GetWorkItems())
            {
                try
                {
                    sWatchMovePI.Reset();
                    sWatchMovePI.Start();
                    counter = counter + 1;
                    PI      = wi.GetProcessInstance();
                    HConsole.WriteLine(">> Verschieben des Aktes " + PI.Name + " beginnt...");

                    Rules.Clear();
                    Rules.AddRange(PI.GetAccessRules(CCD.Domea.Fw.Base.AccessType.Read));
                    Rules.Add(arRead);
                    Rules.AddRange(PI.GetAccessRules(CCD.Domea.Fw.Base.AccessType.Write));
                    Rules.Add(arWrite);

                    PI.SetActiveWorkItem(wi);
                    PI.SetLock(ProcessInstanceLockLevel.Whole);
                    wi.WriteHistoryLogEvent(30, "Start BIG Changes 2.0", new HistoryLogEventType(session, 99));
                    PI.SetCustomAttribute("CSVERANTWOE", oe.Id.ToString());
                    PI.AssignAccessRules(Rules.ToArray(), true);
                    PI.Update();

                    wi.SetLock(WorkItemLockLevel.WorkItem);
                    wi.DelegateTo(toWorkGroup);
                    wi.ReleaseLock(WorkItemLockLevel.WorkItem);

                    wi.WriteHistoryLogEvent(30, "BIG Changes 2.0 erfolgreich durchgeführt", new HistoryLogEventType(session, 99));
                    PI.ReleaseLock(ProcessInstanceLockLevel.Whole);
                    sWatchMovePI.Stop();
                    HConsole.WriteLine(">> Verschieben des Aktes " + PI.Name + " abgeschlossen... (Zähler: " + counter + " / Stopwatch: " + sWatchMovePI.Elapsed.ToString("ss\\.ff") + ")");
                }
                catch (Exception ex)
                {
                    HConsole.WriteError(ex);
                }
            }
        }
Exemple #27
0
        private async Task BeatAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(_period, cancellationToken).CfAwait();

                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
                HConsole.WriteLine(this, $"Run with period={(int)_period.TotalSeconds}s, timeout={(int)_timeout.TotalSeconds}s");
                await RunAsync(cancellationToken).CfAwait();
            }
        }
Exemple #28
0
        /// <summary>
        /// Starts the server.
        /// </summary>
        /// <returns>A task that will complete when the server has started.</returns>
        public async Task StartAsync()
        {
            HConsole.WriteLine(this, $"Start server at {_endpoint}");

            _listener = new ServerSocketListener(_endpoint)
            {
                OnAcceptConnection = AcceptConnection, OnShutdown = ListenerShutdown
            };
            HConsole.Configure(_listener, config => config.SetIndent(24).SetPrefix("LISTENER"));
            _open = true;
            await _listener.StartAsync().CAF();

            HConsole.WriteLine(this, "Server started");
        }
        /// <summary>
        /// Starts the server.
        /// </summary>
        /// <returns>A task that will complete when the server has started.</returns>
        public async Task StartAsync()
        {
            HConsole.WriteLine(this, $"Start server at {_endpoint}");

            _listener = new ServerSocketListener(_endpoint, _hcname)
            {
                OnAcceptConnection = AcceptConnection, OnShutdown = ListenerShutdown
            };

            _open = true;
            await _listener.StartAsync().CfAwait();

            HConsole.WriteLine(this, "Server started");
        }
        public void WritesNothingByDefault()
        {
            var capture = new ConsoleCapture();

            var o = new object();

            using (capture.Output())
            {
                HConsole.WriteLine(o, "text0"); // default level is 0
                HConsole.WriteLine(o, 1, "text1");
            }

            Assert.That(capture.ReadToEnd().ToLf(), Is.EqualTo("".ToLf()));
        }