public ClientRegistered(ClientId clientId, IdentityNumber identityNumber, PersonName clientName, TelephoneNumber primaryContactNumber)
 {
     ClientId = clientId;
     IdentityNumber = identityNumber;
     ClientName = clientName;
     PrimaryContactNumber = primaryContactNumber;
 }
Beispiel #2
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public ActiveClient(ClientId id)
        {
            _id = id;

            _executionStrategy = null;
            _messageBus = null;
        }
        public AccountAssingedToClient(ClientId clientId, AccountNumber accountNumber)
        {
            Mandate.ParameterNotNullOrEmpty(accountNumber, "accountNumber");
            Mandate.ParameterNotNullOrEmpty(clientId, "clientId");

            ClientId = clientId;
            AccountNumber = accountNumber;
        }
        public ClientDateOfBirthCorrected(ClientId clientId, DateOfBirth dateOfBirth)
        {
            Mandate.ParameterNotNull(clientId, "clientId");
            Mandate.ParameterNotDefaut(dateOfBirth, "dateOfBirth");

            ClientId = clientId;
            DateOfBirth = dateOfBirth;
        }
Beispiel #5
0
        public AccountOpened(ClientId clientId, AccountNumber accountNumber)
        {
            Mandate.ParameterNotNull(clientId, "clientId");
            Mandate.ParameterNotNull(accountNumber, "accountNumber");

            ClientId = clientId;
            AccountNumber = accountNumber;
        }
        public void Build(string[] args)
        {
            if (args.Length != 1)
            {
                throw new Exception(String.Format("Error. Usage is: {0}", Usage));
            }

            ClientId = new ClientId(args[0]);
        }
Beispiel #7
0
        public AccountBilled(AccountNumber accountNumber, ClientId clientId, Recency recency)
        {
            Mandate.ParameterNotNullOrEmpty(accountNumber, "accountNumber");
            Mandate.ParameterNotNullOrEmpty(clientId, "clientId");

            Recency = recency;
            ClientId = clientId;
            AccountNumber = accountNumber;
        }
Beispiel #8
0
        /// <summary>
        /// Implementing the ISerializable to provide a faster, more optimized
        /// serialization for the class.
        /// </summary>
        public EnvelopeStamp(SerializationInfo info, StreamingContext context)
        {
            // Get from the info.
            SerializationReader reader = new SerializationReader((byte[])info.GetValue("data", typeof(byte[])));

            _stampId = reader.ReadInt64();
            _receiverId = (ClientId)reader.ReadObject();
            _senderId = (ClientId)reader.ReadObject();
        }
        public void Build(string[] args)
        {
            if (args.Length != 2)
            {
                throw new Exception(String.Format("Error. Usage is: {0}", Usage));
            }

            ClientId = new ClientId(args[0]);
            DateOfBirth = new DateOfBirth(DateTime.Parse(args[1]));
        }
        public AccountStatusChanged(AccountNumber accountNumber, ClientId clientId, AccountStatus status)
        {
            Mandate.ParameterNotNull(accountNumber, "accountNumber");
            Mandate.ParameterNotNull(clientId, "clientId");
            Mandate.ParameterNotDefaut(status, "status");

            Status = status;
            AccountNumber = accountNumber;
            ClientId = clientId;
        }
        public AccountNumber GetAccountNumberForClient(ClientId clientId)
        {
            var accountNumber = dataQuery.GetQueryable<ClientView>()
                                         .Where(a => a.IdentityNumber == clientId.Id)
                                         .Select(a => a.AccountNumber)
                                         .FirstOrDefault();

            return String.IsNullOrWhiteSpace(accountNumber)
                ? AccountNumber.Empty
                : new AccountNumber(accountNumber);
        }
        public ClientRegistered(ClientId clientId, IdentityNumber identityNumber, PersonName clientName, TelephoneNumber primaryContactNumber)
        {
            Mandate.ParameterNotNull(clientId, "clientId");
            Mandate.ParameterNotDefaut(identityNumber, "identityNumber");
            Mandate.ParameterNotDefaut(clientName, "clientName");
            Mandate.ParameterNotDefaut(primaryContactNumber, "primaryContactNumber");

            ClientId = clientId;
            IdentityNumber = identityNumber;
            ClientName = clientName;
            PrimaryContactNumber = primaryContactNumber;
        }
        /// <summary>
        /// Gather a lsit of update requests, related to a specific target.
        /// </summary>
        /// <returns></returns>
        public List<EventSubscriptionRequest> GatherSourceRelatedUpdates(ClientId sourceId)
        {
            List<EventSubscriptionRequest> result = new List<EventSubscriptionRequest>();

            HotSwapDictionary<ClientId, ClientEventSubscriptionInfo> values;
            if (_subscriptionsHotSwap.TryGetValue(sourceId, out values))
            {

                foreach (KeyValuePair<ClientId, ClientEventSubscriptionInfo> pair in values)
                {
                    foreach (KeyValuePair<MethodInfo, int> subPair in pair.Value.Data)
                    {
                        EventSubscriptionRequest request = new EventSubscriptionRequest(sourceId);
                        request.DelegateInstanceMethodInfo = subPair.Key;
                        request.SpecificCountOptional = subPair.Value;
                        request.ExtendedEventName = _extendedEventName;

                        request.SenderId = pair.Key;
                        request.IsAdd = true;

                        result.Add(request);
                    }
                }
            }

            //foreach (KeyValuePair<MessageBusClientId, HotSwapDictionary<MessageBusClientId, ClientEventSubscriptionInfo>> pair
            //    in _subscriptionsHotSwap)
            //{
            //    ClientEventSubscriptionInfo info;
            //    if (pair.Value.TryGetValue(sourceId, out info))
            //    {
            //        foreach (KeyValuePair<MethodInfo, int> subPair in info.Data)
            //        {
            //            EventSubscriptionRequest request = new EventSubscriptionRequest(sourceId);
            //            request.DelegateInstanceMethodInfo = subPair.Key;
            //            request.SpecificCountOptional = subPair.Value;
            //            request.ExtendedEventName = _extendedEventName;

            //            request.SenderId = pair.Key;
            //            request.IsAdd = true;

            //            result.Add(request);
            //        }
            //    }
            //}

            return result;
        }
 internal OperationResult(
     Operation operationType,
     PositionBlock positionBlock,
     byte[] dataBuffer,
     int dataBufferLength,
     byte[] keyBuffer,
     sbyte keyNumber,
     ClientId clientId)
 {
     this.OperationType = operationType;
     this.PositionBlock = positionBlock;
     this.DataBuffer = dataBuffer;
     this.DataBufferLength = dataBufferLength;
     this.KeyBuffer = keyBuffer;
     this.KeyNumber = keyNumber;
     this.ClientId = clientId;
 }
        private NLogEvents TranslateLogEvents(IList <AsyncLogEventInfo> logEvents)
        {
            if (logEvents.Count == 0 && !LogManager.ThrowExceptions)
            {
                InternalLogger.Error("LogReceiverServiceTarget(Name={0}): LogEvents array is empty, sending empty event...", Name);
                return(new NLogEvents());
            }

            string clientID = string.Empty;

            if (ClientId != null)
            {
                clientID = ClientId.Render(logEvents[0].LogEvent);
            }

            var networkLogEvents = new NLogEvents
            {
                ClientName  = clientID,
                LayoutNames = new StringCollection(),
                Strings     = new StringCollection(),
                BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks
            };

            var stringTable = new Dictionary <string, int>();

            for (int i = 0; i < Parameters.Count; ++i)
            {
                networkLogEvents.LayoutNames.Add(Parameters[i].Name);
            }

            if (IncludeEventProperties)
            {
                AddEventProperties(logEvents, networkLogEvents);
            }

            networkLogEvents.Events = new NLogEvent[logEvents.Count];
            for (int i = 0; i < logEvents.Count; ++i)
            {
                AsyncLogEventInfo ev = logEvents[i];
                networkLogEvents.Events[i] = TranslateEvent(ev.LogEvent, networkLogEvents, stringTable);
            }

            return(networkLogEvents);
        }
Beispiel #16
0
        /// <summary>
        /// This constructor expects an App Setting for 'UniversalAnalytics.TrackingId'
        /// in the config. UniversalAnalytics.TrackingId must be a Universal Analytics Web Property.
        /// </summary>
        /// <param name="anonymousClientId">Required. Anonymous client id for the event.
        /// See https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#cid for details.</param>
        /// <param name="eventCategory">Required. The event category for the event.
        /// See https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ec for details.</param>
        /// <param name="eventAction">Required. The event action for the event.
        /// See https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ea for details.</param>
        /// <param name="eventLabel">The event label for the event.
        /// See https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#el for details.</param>
        /// <param name="eventValue">Optional. The event value for the event.
        /// See https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ev for details.</param>
        /// <exception cref="UniversalAnalyticsHttpWrapper.Exceptions.ConfigEntryMissingException">Thrown when
        /// one of the required config attributes are missing.</exception>
        /// <exception cref="System.ArgumentException">Thrown when one of the required fields are null or whitespace.</exception>
        /// <exception cref="System.Web.HttpException">Thrown when the HttpRequest that's posted to Google returns something
        /// other than a 200 OK response.</exception>
        public IUniversalAnalyticsEvent MakeUniversalAnalyticsEvent(
            ClientId clientId,
            string eventCategory,
            string eventAction,
            string eventLabel,
            string eventValue = null)
        {
            if (clientId == null)
            {
                throw new ArgumentNullException(nameof(clientId));
            }

            return(MakeUniversalAnalyticsEvent(
                       clientId.Id.ToString(),
                       eventCategory,
                       eventAction,
                       eventLabel,
                       eventValue));
        }
Beispiel #17
0
        public List <string> Validate()
        {
            var errors = new List <string>();

            if (string.IsNullOrEmpty(ClientId))
            {
                errors.Add("ClientId is empty");
            }
            else if (ClientId.Length > 6)
            {
                errors.Add("ClientId is longer then 6 chars");
            }
            else if (ClientId.Contains(" "))
            {
                errors.Add("ClientId contains spaces");
            }

            if (RequestId == null)
            {
                errors.Add("RequestId is not a long");
            }

            if (string.IsNullOrEmpty(Name))
            {
                errors.Add("Name is empty");
            }
            else if (Name.Length > 255)
            {
                errors.Add("Name is longer then 255 chars");
            }

            if (Quantity == null)
            {
                errors.Add("Quantity is not an int");
            }

            if (Price == null)
            {
                errors.Add("Price is not a double");
            }

            return(errors);
        }
        /// <summary>
        /// Check that the options are valid. Should throw an exception if things are not ok.
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// You must either set Authority or IntrospectionEndpoint
        /// or
        /// You must either set a ClientId or set an introspection HTTP handler
        /// </exception>
        /// <exception cref="ArgumentException">TokenRetriever must be set - TokenRetriever</exception>
        public override void Validate()
        {
            base.Validate();

            if (Authority.IsMissing() && IntrospectionEndpoint.IsMissing())
            {
                throw new InvalidOperationException("You must either set Authority or IntrospectionEndpoint");
            }

            if (ClientId.IsMissing() && IntrospectionHttpHandler == null)
            {
                throw new InvalidOperationException("You must either set a ClientId or set an introspection HTTP handler");
            }

            if (TokenRetriever == null)
            {
                throw new ArgumentException("TokenRetriever must be set", nameof(TokenRetriever));
            }
        }
        void DoUpdateSubscription(ClientId subscriberId, MethodInfo subscriberMethodInfo,
                                  ClientId targetSourceId, bool addSubscription, int?specificValue)
        {
            HotSwapDictionary <ClientId, ClientEventSubscriptionInfo> data;

            if (_subscriptionsHotSwap.TryGetValue(targetSourceId, out data) == false)
            {// Create a new list for this id.
                data = _subscriptionsHotSwap.GetOrAdd(targetSourceId, new HotSwapDictionary <ClientId, ClientEventSubscriptionInfo>());
            }

            ClientEventSubscriptionInfo dataInfo;

            if (data.TryGetValue(subscriberId, out dataInfo) == false)
            {
                dataInfo = data.GetOrAdd(subscriberId, new ClientEventSubscriptionInfo());
            }

            dataInfo.Update(subscriberMethodInfo, addSubscription, specificValue);
        }
        public override int GetHashCode()
        {
            var hashCode = 82934527;

            hashCode = hashCode * -1521134295 + ClientId.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(AcctCode);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Time);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Symbol);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(SecType);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Exchange);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Side);

            return(hashCode);
        }
        protected override IAsyncResult BeginExecute(NativeActivityContext context, AsyncCallback callback, object state)
        {
            string restApiUrl = RestApiUrl.Get(context);

            if (!restApiUrl.EndsWith("/"))
            {
                restApiUrl += "/";
            }
            string client_id = ClientId.Get(context);
            string client_secret;

            if (ClientSecretSecure.Get(context) != null)
            {
                client_secret = SecureStringToString(ClientSecretSecure.Get(context));
            }
            else
            {
                client_secret = ClientSecretInsecure.Get(context);
            }

            string redirect_uri  = RedirectUrl.Get(context);
            int    serverTimeout = TimeoutMS.Get(context);


            authAgent = new AuthenticationAgent(restApiUrl, client_id, client_secret, redirect_uri, serverTimeout);

            if (AuthentificationTokenIn.Get(context) != null)
            {
                authAgent.authToken = JsonConvert.DeserializeObject <AuthToken>(AuthentificationTokenIn.Get(context));
                authAgent.GetAuthUrl();
                authAgent.authCode        = JsonConvert.DeserializeObject <ConcurrentDictionary <string, string> >(AuthentificationCodeIn.Get(context));
                AuthenticateAsyncDelegate = new Action(ConfigureAuthentification);
            }
            else
            {
                authAgent.GetAuthUrl();
                ScheduleAuthActivities(context);
                AuthenticateAsyncDelegate = new Action(AuthenticateAsync);
            }

            return(AuthenticateAsyncDelegate.BeginInvoke(callback, state));
        }
Beispiel #22
0
        private void OnClFileTransferRespond(ClFileTransferRespond msg, ClientId id)
        {
            var cl = clients[id];
            var ft = ftsContainer.GetSessionById(msg.SessionId);

            if (ft == null)
            {
                Root.Log(LogLevel.Warning, "Server: bad file transfer session id ({0}) received from client {1} ",
                         msg.SessionId, cl.Login);
                // XXX: send result
                return;
            }
            SocketClientBase fileSender;

            if (!nameToClient.TryGetValue(ft.Sender, out fileSender))
            {
                Root.Log(LogLevel.Warning, "Server: client {0} attempted to send file transfer verification result " +
                         "to disconnected client {1}", cl.Login, ft.Receiver);
                // XXX: suspend session (cl is offline)
                return;
            }
            var result = new SvFileTransferResult
            {
                Result = msg.Result,
                Token  = ft.Token
            };

            if (msg.Result == FileTransferRequestResult.Accepted)
            {
                var newBlockSize = Math.Min(SelectBlockSize(msg.BlockSize), ft.BlockSize);
                ft.BlockSize     = newBlockSize;
                ft.State         = FileTransferState.Working;
                result.BlockSize = newBlockSize;
                result.SessionId = msg.SessionId;
            }
            else
            {
                ftsContainer.DeleteSession(ft.Id);
                result.SessionId = FileTransferId.InvalidId;
            }
            SendTo(fileSender.Id, result);
        }
        public void Send100EventsAsQuicklyAsPossibleAndARateLimitStillWontOccur()
        {
            var randomCid = new ClientId("rate limit test cid");

            for (var i = 1; i <= 100; i++)
            {
                var analyticsEvent = _eventFactory.MakeUniversalAnalyticsEvent(
                    randomCid,
                    "rate limit test category",
                    "rate limit test action",
                    "rate limit test label",
                    i.ToString());
                var result = _eventTracker.TrackEvent(analyticsEvent);

                if (result.Failed)
                {
                    Assert.Fail("Failed after " + i + " transmissions with the following exception: " + result.Exception.Message);
                }
            }
        }
        private bool Handshake(CodedInputStream inputStream, CodedOutputStream outputStream, out ClientId?clientId)
        {
            var connectRequestMessage = Request.Parser.ParseFrom(inputStream);

            if (gameEngine.TryAcceptNewPlayer(mapper.Map <ConnectRequestMessage>(connectRequestMessage), out var responseMessage))
            {
                var connectResponseMessage = mapper.Map <Response>(responseMessage);
                connectResponseMessage.WriteTo(outputStream);

                clientId = new ClientId
                {
                    LobbyId  = responseMessage.LobbyIdentifier,
                    PlayerId = responseMessage.PlayerId
                };
                return(true);
            }

            clientId = null;
            return(false);
        }
Beispiel #25
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ValidateSessions();
        DataView dv  = (DataView)VenueName.Select(DataSourceSelectArguments.Empty);
        DataView dv7 = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

        Label1.Text  = (string)dv.Table.Rows[0][0];
        Label12.Text = (string)dv7.Table.Rows[0][0];
        Label3.Text  = Session["EventName"].ToString();
        Label4.Text  = ConvertMode(Session["StartTime"].ToString());
        Label5.Text  = Session["NoofHours"].ToString() + "hrs";
        Label6.Text  = ConvertMode(Session["EndTime"].ToString());
        compute();
        MembershipUser ma = Membership.GetUser();

        Session["uid"] = ma.ProviderUserKey.ToString();
        DataView dv2 = (DataView)ClientId.Select(DataSourceSelectArguments.Empty);

        cid.Text = Convert.ToString((int)dv2.Table.Rows[0][0]);
    }
Beispiel #26
0
        public void Copy(PayPalPlusPaymentSettings settings, bool fromSettings)
        {
            if (fromSettings)
            {
                MiniMapper.Map(settings, this);
            }
            else
            {
                TransactMode = TransactMode.AuthorizeAndCapture;

                MiniMapper.Map(this, settings);
                settings.ApiAccountName      = ApiAccountName.TrimSafe();
                settings.ApiAccountPassword  = ApiAccountPassword.TrimSafe();
                settings.ClientId            = ClientId.TrimSafe();
                settings.ExperienceProfileId = ExperienceProfileId.TrimSafe();
                settings.Secret    = Secret.TrimSafe();
                settings.Signature = Signature.TrimSafe();
                settings.WebhookId = WebhookId.TrimSafe();
            }
        }
Beispiel #27
0
        public void Listen(CancellationToken cancel)
        {
            // TODO: [vermorel] Use a 'ConnectionId' instead.
            cancel.Register(() => _listener.Close());
            while (!cancel.IsCancellationRequested)
            {
                try
                {
                    var s = _listener.Accept();
                    _queue.Append(new ClientConnection(s, ClientId.Next(), _bufferOutLength));
                }
                catch
                {
                    // TODO: [vermorel] We must log exceptions here.
                    // TODO: [vermorel] In debug mode, I would still suggest to crash the server.

                    // An exception is not allowed to kill the accept loop
                }
            }
        }
Beispiel #28
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ClientId.Length != 0)
            {
                hash ^= ClientId.GetHashCode();
            }
            hash ^= subscribeTopics_.GetHashCode();
            hash ^= unsubscribeTopics_.GetHashCode();
            if (SubscribeTopicRegexp.Length != 0)
            {
                hash ^= SubscribeTopicRegexp.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Beispiel #29
0
        public override bool Equals(object obj)
        {
            var other = obj as PersistedGrantModel;

            if (other == null)
            {
                return(false);
            }


            var result = ClientId.SafeEquals(other.ClientId) &&
                         CreationTime.SafeEquals(other.CreationTime) &&
                         Data.SafeEquals(other.Data) &&
                         Expiration.SafeEquals(other.Expiration) &&
                         Key.SafeEquals(other.Key) &&
                         SubjectId.SafeEquals(other.SubjectId) &&
                         Type.SafeEquals(other.Type);

            return(result);
        }
Beispiel #30
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (application_ != null)
            {
                hash ^= Application.GetHashCode();
            }
            if (boundedContext_ != null)
            {
                hash ^= BoundedContext.GetHashCode();
            }
            if (clientId_ != null)
            {
                hash ^= ClientId.GetHashCode();
            }
            hash ^= offsets_.GetHashCode();
            hash ^= events_.GetHashCode();
            return(hash);
        }
Beispiel #31
0
 public virtual bool Equals(S2SAppSettings settings)
 {
     if (!ClientId.Equals(settings.ClientId))
     {
         return(false);
     }
     if (!ClientSecret.Equals(settings.ClientSecret))
     {
         return(false);
     }
     if (!Resource.Equals(settings.Resource))
     {
         return(false);
     }
     if (!TenantId.Equals(settings.TenantId))
     {
         return(false);
     }
     return(true);
 }
Beispiel #32
0
        public IEnumerable <string> Validate()
        {
            if (Host.IsEmpty())
            {
                yield return("Host not configured.");
            }
            if (Port <= 0)
            {
                yield return($"Port {Port} is invalid.");
            }
            if (ClientId.IsEmpty())
            {
                yield return("Host not configured.");
            }

            if (ClientStatusTopic.IsEmpty())
            {
                yield return("ClientStatusTopic is invalid.");
            }
        }
Beispiel #33
0
        public void WriteCoinCons()
        {
            var sozu = new VolatileCoinStore();

            var inbox      = new BoundedInbox();
            var outbox     = new BoundedInbox();
            var controller = new CoinController(inbox, outbox, sozu, _hash);

            controller.Lineage = new MockLineage();

            var clientId = new ClientId();
            var reqId    = new RequestId(1);

            var coin = GetCoin(_rand);

            sozu.AddProduction(
                _hash.Hash(ref coin.Outpoint),
                ref coin.Outpoint,
                false, coin.Payload,
                new BlockAlias(2),
                null);

            var pool             = new SpanPool <byte>(4096);
            var buffer           = new byte[ConsumeCoinRequest.SizeInBytes];
            var writeCoinRequest = new ConsumeCoinRequest(
                reqId, ref coin.Outpoint, new BlockAlias(2).ConvertToBlockHandle(clientId.Mask), pool);

            inbox.TryWrite(writeCoinRequest.Span);
            controller.HandleRequest();

            var raw = outbox.Peek();

            Assert.Equal(ConsumeCoinResponse.SizeInBytes, raw.Length);
            var response = new ConsumeCoinResponse(raw.Span);

            // verify response contents
            Assert.Equal(reqId, response.MessageHeader.RequestId);
            Assert.Equal(clientId, response.MessageHeader.ClientId);
            Assert.Equal(MessageKind.ConsumeCoinResponse, response.MessageHeader.MessageKind);
            Assert.Equal(ChangeCoinStatus.Success, response.Status);
        }
Beispiel #34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="senderId"></param>
        /// <param name="receiverId"></param>
        /// <param name="envelope"></param>
        /// <param name="requestConfirm">Only valid for remote clients, since all local calls are confirmed or denied by default.</param>
        /// <returns></returns>
        protected override SendToClientResultEnum DoSendToClient(ClientId senderId, ClientId receiverId,
                                                                 Envelope envelope, TimeSpan?requestConfirmTimeout)
        {
            if (receiverId.IsMessageBusIndexValid && (receiverId.MessageBus == this))
            //|| receiverId.MessageBus == null)) // This allows for "lost" ids.
            {// Receiver seems to be a local item.
                SendToClientResultEnum result = base.DoSendToClient(senderId, receiverId, envelope, requestConfirmTimeout);
                if (result != SendToClientResultEnum.ClientNotFound)
                {
                    return(result);
                }
            }

            int clientSocketId = 0;

            lock (_syncRoot)
            {
                if (_remoteClientNetId.TryGetValue(receiverId, out clientSocketId) == false)
                {
                    return(SendToClientResultEnum.ClientNotFound);
                }
            }

            // Send message.
            EnvelopeMessage message = new EnvelopeMessage()
            {
                Envelope        = envelope,
                Receivers       = new ClientId[] { receiverId },
                Sender          = senderId,
                RequestResponse = false
            };

            if (ToClient(clientSocketId, message, requestConfirmTimeout) == false)
            {
                return(SendToClientResultEnum.Failure);
            }
            else
            {
                return(SendToClientResultEnum.Success);
            }
        }
Beispiel #35
0
        public R <ClientList, LocalStr> GetFallbackedClientById(ClientId id)
        {
            var result = ClientBufferRequest(client => client.ClientId == id);

            if (result.Ok)
            {
                return(result);
            }
            Log.Warn("Slow double request due to missing or wrong permission configuration!");
            var result2 = ts3FullClient.Send <ClientList>("clientinfo", new CommandParameter("clid", id)).WrapSingle();

            if (!result2.Ok)
            {
                return(new LocalStr(strings.error_ts_no_client_found));
            }
            ClientList cd = result2.Value;

            cd.ClientId = id;
            clientbuffer.Add(cd);
            return(cd);
        }
Beispiel #36
0
        public void TestMissingQuit()
        {
            var tracker         = new ChannelTracker();
            var someoneClientId = new ClientId("Someone", "user", "example.com");

            var message = new Message("JOIN", new[] { "#Test" });

            message.Prefix.ClientId = someoneClientId;
            tracker.UpdateFromMessage(message);

            message = new Message("PART", new[] { "#Test" });
            message.Prefix.ClientId = someoneClientId;
            tracker.UpdateFromMessage(message);

            message = new Message("QUIT");
            message.Prefix.ClientId = someoneClientId;

            tracker.UpdateFromMessage(message);

            Assert.False(tracker["#test"].ContainsKey("someone"));
        }
        public static string GetName(this ClientId clientId, bool includeThread)
        {
            string processName = Windows.GetProcessName(clientId.ProcessId);

            if (includeThread)
            {
                if (!string.IsNullOrEmpty(processName))
                {
                    return(processName + " (" + clientId.ProcessId.ToString() + "): " + clientId.ThreadId.ToString());
                }

                return("Non-existent process (" + clientId.ProcessId.ToString() + "): " + clientId.ThreadId.ToString());
            }

            if (!string.IsNullOrEmpty(processName))
            {
                return(processName + " (" + clientId.ProcessId.ToString() + ")");
            }

            return("Non-existent process (" + clientId.ProcessId.ToString() + ")");
        }
Beispiel #38
0
        public void ShouldNotHaveAllocationToPoolAndExternalAccount()
        {
            var mock = new Mock <InterestRates>();

            mock.Setup(i => i.PositiveInterestRate()).Returns(2.0);
            var clientId    = new ClientId("ABC123");
            var account1    = new Account(new AccountId(12341234), clientId);
            var account2    = new Account(new AccountId(43121235), clientId);
            var allocations = new List <Allocation> {
                new Allocation(account1, 70), new Allocation(account2, 30)
            };

            try
            {
                GetTestStructure(1000.0, -500.0, allocations, mock.Object, null);
                Assert.Fail("Should not Allocate Interest to both Pool And External Account");
            }
            catch (ArgumentException)
            {
            }
        }
Beispiel #39
0
        /// <summary>
        /// Allocate an array. Intended for testing purposes only.
        /// </summary>
        internal static GetCoinRequest From(
            RequestId requestId,
            ClientId clientId,
            Outpoint outpoint,
            BlockAlias context,
            BlockHandleMask mask)
        {
            var request = new GetCoinRequest {
                _buffer = new Span <byte>(new byte[Header.SizeInBytes])
            };

            request.MessageHeader.MessageSizeInBytes = Header.SizeInBytes;
            request.MessageHeader.RequestId          = requestId;
            request.MessageHeader.ClientId           = clientId;
            request.MessageHeader.MessageKind        = MessageKind.GetCoin;

            request.AsHeader.Outpoint = outpoint;
            request.AsHeader.Context  = context.ConvertToBlockHandle(mask);

            return(request);
        }
Beispiel #40
0
        public bool Receive(LocoShunterActionPacket packet, ClientId client)
        {
            if (packet.Id != Id)
            {
                return(false);
            }

            Logging <TrainCarSync> .LogDebug($"LocoShunterActionPacket: {packet.Flags} / {packet.TargetThrottle} / {packet.TargetBrake} / {packet.TargetIndependentBrake}");

            _controller.SetThrottle(packet.TargetThrottle);
            _controller.SetBrake(packet.TargetBrake);
            _controller.SetIndependentBrake(packet.TargetIndependentBrake);
            _controller.SetReverser(packet.Reverser);
            _controller.SetEngineRunning((packet.Flags & ShunterStateFlags.EngineOn) != 0);
            _controller.SetSandersOn((packet.Flags & ShunterStateFlags.SandOn) != 0);
            _controller.backlight = (packet.Flags & ShunterStateFlags.LightOn) != 0;
            _controller.fan       = (packet.Flags & ShunterStateFlags.FanOn) != 0;
            _controller.headlights.SetActive((packet.Flags & ShunterStateFlags.HeadlightOn) != 0);

            return(true);
        }
Beispiel #41
0
        internal Dictionary <string, string> ToQueryParams()
        {
            var queryParams = new Dictionary <string, string>();

            if (ClientId.IsNotEmpty())
            {
                queryParams.Add("clientId", ClientId);
            }

            if (DeviceId.IsNotEmpty())
            {
                queryParams.Add("deviceId", DeviceId);
            }

            if (Limit.HasValue)
            {
                queryParams.Add("limit", Limit.Value.ToString());
            }

            return(queryParams);
        }
Beispiel #42
0
        public void ShouldNotCreateStructureWithout100PercentAllocation()
        {
            var mock = new Mock <InterestRates>();

            mock.Setup(i => i.PositiveInterestRate()).Returns(2.0);
            var clientId    = new ClientId("ABC123");
            var account1    = new Account(new AccountId(12341234), clientId);
            var account2    = new Account(new AccountId(12341235), clientId);
            var allocations = new List <Allocation> {
                new Allocation(account1, 30), new Allocation(account2, 30)
            };

            try
            {
                GetTestStructure(1000.0, -500.0, allocations, mock.Object, null);
                Assert.Fail("Should Not create Structure with Allocation interest percent sum not equal to 100");
            }
            catch (ArgumentException)
            {
            }
        }
Beispiel #43
0
        internal void ConfirmedCallTest()
        {
            CallOutcome outcome;

            Client1.CallConfirmed <ITestInterface>(Client2.Id, TimeSpan.FromSeconds(2), out outcome).SimpleMethod(2, "some param", EventArgs.Empty);

            if (outcome == null || outcome.Result != Outcomes.Success)
            {
                Assert.Fail("Failed to perform confirmed call.");
            }

            ClientId    dummyId = new ClientId("dummyId");
            CallOutcome outcome2;

            Client1.CallConfirmed <ITestInterface>(dummyId, TimeSpan.FromSeconds(2), out outcome2).SimpleMethod(2, "some param", EventArgs.Empty);

            if (outcome2 != null && outcome2.Result == Outcomes.Success)
            {
                Assert.Fail("Failed to verify invalid outcome.");
            }
        }
Beispiel #44
0
        public void ShouldAllocateInterestAmountToExternalAccount()
        {
            const double netInterest = (10.0 / 365);

            var mock = new Mock <InterestRates>();

            mock.Setup(i => i.PositiveInterestRate()).Returns(2.0);
            var clientId    = new ClientId("ABC123");
            var account1    = new Account(new AccountId(43214321), clientId);
            var allocations = new List <Allocation> {
                new Allocation(account1, 100)
            };

            var expectedMap = new Dictionary <Account, double> {
                { account1, netInterest }
            };

            Assert.AreEqual(expectedMap[account1], GetTestStructure(1000.0, -500.0, allocations, mock.Object, null).GetAllocation()[account1]);

            mock.VerifyAll();
        }
        /// <summary>
        /// Obtain a list of the receivers of the event raise.
        /// </summary>
        /// <param name="specific">True to get the specific for this one, false to get the "subscribe to all"</param>
        public HotSwapDictionary<ClientId, ClientEventSubscriptionInfo> GetReceivers(ClientId sourceId, bool specific)
        {
            HotSwapDictionary<ClientId, ClientEventSubscriptionInfo> result;
            if (specific)
            {
                if (_subscriptionsHotSwap.TryGetValue(sourceId, out result) == false)
                {// If not found, return an empty one.
                    result = new HotSwapDictionary<ClientId, ClientEventSubscriptionInfo>();
                }
            }
            else
            {
                if (_subscriptionsHotSwap.TryGetValue(SubscribeToAllId, out result) == false)
                {// If not found, return an empty one.
                    result = new HotSwapDictionary<ClientId, ClientEventSubscriptionInfo>();
                }
            }

            return result;
        }
Beispiel #46
0
        void MessageBus_ClientAddedEvent(MessageBus.Core.IMessageBus messageBus, ClientId clientId)
        {
            // Once a new client has been added, we want to subscribe to its event.

            // Do the report on an invoke thread, since this message bus system event is raised on a non UI thread.
            this.Invoke(new GeneralHelper.GenericDelegate<string>(Report), "Subscribing client " + clientId.ToString());

            // We could also do a full subscribe like this _poolClient.Subscribe<ICommunicationInterface>()
            // but since this only works on local components (attached to this super pool instance) and not
            // ones that are remoted (TCP), we need to subscribe to each one separately.
            _poolClient.Subscribe<ICommunicationInterface>(clientId).EventOne += new HelperDelegate(FormServer_EventOne);
        }
Beispiel #47
0
 protected virtual void _messageBus_ClientRemovedEvent(IMessageBus messageBus, ClientId clientId, bool isPermanent)
 {
     HandleClientRemoved(messageBus, clientId, isPermanent);
 }
Beispiel #48
0
        /// <summary>
        /// 
        /// </summary>
        bool RegisterClientSourceTypes(ClientId clientId)
        {
            IMessageBus messageBus = _messageBus;
            if (messageBus == null)
            {
                Console.WriteLine("Failed to register client source type, message bus not found.");
            #if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to register client source type, message bus not found.");
            #endif
                return false;
            }

            List<string> sourceTypes = messageBus.GetClientSourceTypes(clientId);
            if (sourceTypes == null)
            {
                Console.WriteLine("Failed to register client source type, source type not found.");
            #if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to register client source type, source type not found.");
            #endif
                return false;
            }

            foreach (Type superType in ReflectionHelper.GetKnownTypes(sourceTypes))
            {
                if (superType.IsInterface == false ||
                    ReflectionHelper.TypeHasCustomAttribute(superType, typeof(SuperPoolInterfaceAttribute), false) == false)
                {
                    continue;
                }

                HotSwapList<ClientId> clientList = null;
                if (_clientsInterfaces.TryGetValue(superType, out clientList) == false)
                {
                    clientList = _clientsInterfaces.GetOrAdd(superType, new HotSwapList<ClientId>());
                }

                clientList.AddUnique(clientId);

                if (ReflectionHelper.TypeHasCustomAttribute(superType, typeof(SuperPoolInterfaceAttribute), false) == false)
                {// Register this type as well.
                    _proxyTypeManager.ObtainInterfaceProxy(superType);
                }
            }

            return true;
        }
Beispiel #49
0
        protected virtual bool HandleClientRemoved(IMessageBus messageBus, ClientId clientId, bool isPermanent)
        {
            Type clientType = messageBus.GetClientType(clientId);
            if (clientType == null)
            {
            #if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to establish client type.");
            #endif
                return false;
            }

            if (clientType != typeof(SuperPoolClient) &&
                clientType.IsSubclassOf(typeof(SuperPoolClient)) == false)
            {// Client not a super pool client.
                return false;
            }

            UnRegisterClientSourceTypes(clientId);

            return true;
        }
        internal void ConfirmedCallTest()
        {
            CallOutcome outcome;
            Client1.CallConfirmed<ITestInterface>(Client2.Id, TimeSpan.FromSeconds(2), out outcome).SimpleMethod(2, "some param", EventArgs.Empty);

            if (outcome == null || outcome.Result != Outcomes.Success)
            {
                Assert.Fail("Failed to perform confirmed call.");
            }

            ClientId dummyId = new ClientId("dummyId");
            CallOutcome outcome2;
            Client1.CallConfirmed<ITestInterface>(dummyId, TimeSpan.FromSeconds(2), out outcome2).SimpleMethod(2, "some param", EventArgs.Empty);

            if (outcome2 != null && outcome2.Result == Outcomes.Success)
            {
                Assert.Fail("Failed to verify invalid outcome.");
            }
        }
        internal CreateUserProcessResult(NtStatus status, ProcessCreateInfoData create_info, ProcessCreateState create_state)
        {
            ImageFile = null;
            if (create_state == ProcessCreateState.FailOnSectionCreate)
            {
                ImageFile = new NtFile(new SafeKernelObjectHandle(create_info.FileHandle, true));
            }
            else if (create_state == ProcessCreateState.FailExeName)
            {
                IFEOKeyHandle = RegistryKey.FromHandle(new SafeRegistryHandle(create_info.IFEOKey, true));
            }
            Status = status;
            CreateInfo = create_info;
            CreateState = create_state;

            Process = null;
            Thread = null;
            SectionHandle = null;
            ImageInfo = new SectionImageInformation();
            ClientId = new ClientId();
        }
 internal CreateUserProcessResult(SafeKernelObjectHandle process_handle, SafeKernelObjectHandle thread_handle,
   ProcessCreateInfoData create_info,
   SectionImageInformation image_info, ClientId client_id)
 {
     Process = new NtProcess(process_handle);
     Thread = new NtThread(thread_handle);
     ImageFile = new NtFile(new SafeKernelObjectHandle(create_info.Success.FileHandle, true));
     SectionHandle = new NtSection(new SafeKernelObjectHandle(create_info.Success.SectionHandle, true));
     ImageInfo = image_info;
     ClientId = client_id;
     CreateInfo = create_info;
     CreateState = ProcessCreateState.Success;
 }
        /// <summary>
        /// Remove any subscriptions this client may have.
        /// </summary>
        /// <param name="client"></param>
        public void RemoveClientSubscriptions(ClientId clientId)
        {
            foreach (KeyValuePair<ClientId, HotSwapDictionary<ClientId, ClientEventSubscriptionInfo>> pair in _subscriptionsHotSwap)
            {
                pair.Value.Remove(clientId);
            }

            //foreach (HotSwapList<KeyValuePair<MessageBusClientId, MethodInfo>> list in _subscriptionsHotSwap.Values)
            //{
            //    foreach (KeyValuePair<MessageBusClientId, MethodInfo> pair in list)
            //    {
            //        if (pair.Key.Equals(clientId))
            //        {// *WARNING*, hot swap specific operation (remove while iterating), will not work properly on non-hot swap lists.
            //            list.Remove(pair);
            //        }
            //    }
            //}
        }
Beispiel #54
0
        /// <summary>
        /// Actually supply the item to client. 
        /// </summary>
        /// <param name="senderId"></param>
        /// <param name="receiverId"></param>
        /// <param name="envelope"></param>
        /// <param name="requestConfirm">In local mode we have receival confirmation, so this value is ignored here (as result is always assured true).</param>
        /// <returns></returns>
        protected virtual SendToClientResultEnum DoSendToClient(ClientId senderId, ClientId receiverId,
                                                                Envelope envelope, TimeSpan? requestConfirmTimeout)
        {
            if (receiverId.MessageBus != this)
            {
                //// Maybe this is a "lost" id, try to see if it is one of ours.
                //if (receiverId.MessageBus == null && _guidToIndexHotSwap.ContainsKey(receiverId.Guid))
                //{// Yes!
                //    receiverId.MessageBus = this;
                //}
                return SendToClientResultEnum.ClientNotFound;
            }

            MessageBusClient client = GetLocalClientByIndex(receiverId.LocalMessageBusIndex);
            if (client == null)
            {
                return SendToClientResultEnum.ClientNotFound;
            }

            ISerializer serializer = _serializer;
            if (serializer == null)
            {
                return SendToClientResultEnum.Failure;
            }

            // Duplicate what (if anything) as according to envelope duplication model.
            envelope = envelope.Duplicate(serializer);
            envelope.History.PushStamp(new EnvelopeStamp(PendingStampId, receiverId, senderId));

            if (client.Receive(envelope))
            {
                return SendToClientResultEnum.Success;
            }
            else
            {
                return SendToClientResultEnum.Failure;
            }
        }
        void DoUpdateSubscription(ClientId subscriberId, MethodInfo subscriberMethodInfo,
                                  ClientId targetSourceId, bool addSubscription, int? specificValue)
        {
            HotSwapDictionary<ClientId, ClientEventSubscriptionInfo> data;
            if (_subscriptionsHotSwap.TryGetValue(targetSourceId, out data) == false)
            {// Create a new list for this id.
                data = _subscriptionsHotSwap.GetOrAdd(targetSourceId, new HotSwapDictionary<ClientId, ClientEventSubscriptionInfo>());
            }

            ClientEventSubscriptionInfo dataInfo;
            if (data.TryGetValue(subscriberId, out dataInfo) == false)
            {
                dataInfo = data.GetOrAdd(subscriberId, new ClientEventSubscriptionInfo());
            }

            dataInfo.Update(subscriberMethodInfo, addSubscription, specificValue);
        }
Beispiel #56
0
 void _messageBus_ClientUpdateEvent(IMessageBus messageBus, ClientId clientId)
 {
     UnRegisterClientSourceTypes(clientId);
     RegisterClientSourceTypes(clientId);
 }
        public ClientPassedAway(ClientId clientId)
        {
            Mandate.ParameterNotNull(clientId, "clientId");

            ClientId = clientId;
        }
Beispiel #58
0
 /// <summary>
 /// Will unregister all _clientInterfaces associations with this client.
 /// </summary>
 /// <param name="clientId"></param>
 void UnRegisterClientSourceTypes(ClientId clientId)
 {
     foreach (KeyValuePair<Type, HotSwapList<ClientId>> pair in _clientsInterfaces)
     {
         pair.Value.Remove(clientId);
     }
 }
 private ClientModel FetchModel(ClientId clientId)
 {
     return repository.GetQueryable<ClientModel>().First(client => client.IdentityNumber == clientId.Id);
 }
Beispiel #60
0
 void _messageBus_ClientAddedEvent(IMessageBus messageBus, ClientId clientId)
 {
     HandleClientAdded(messageBus, clientId);
 }