Beispiel #1
0
        public static async Task <Token> GetAuthorizationToken(ClientIdentifier clientIdentifier, Token savedTokenData)
        {
            if (clientIdentifier == null)
            {
                return(null);
            }

            if (savedTokenData != null)
            {
                if (savedTokenData.IsValidForAuth())
                {
                    return(savedTokenData);
                }
                else if (savedTokenData.IsValidForRefresh())
                {
                    Token refreshedToken = await RefreshToken(clientIdentifier, savedTokenData);

                    return(refreshedToken);
                }
            }

            KillPendingAuthorization();

            Token newToken = await RequestToken(clientIdentifier);

            return(newToken);
        }
Beispiel #2
0
        public void ConstructorSetsValue()
        {
            Guid             identity   = Guid.NewGuid();
            ClientIdentifier identifier = new ClientIdentifier(identity);

            Assert.AreEqual(identifier.Identity, identity);
        }
Beispiel #3
0
        private static async Task <Token> RefreshToken(ClientIdentifier clientIdentifier, Token tokenData)
        {
            Token resultToken = null;

            HttpContent requestContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("client_secret", clientIdentifier.GetSecret()),
                new KeyValuePair <string, string>("grant_type", "refresh_token"),
                new KeyValuePair <string, string>("refresh_token", tokenData.refreshToken),
                new KeyValuePair <string, string>("client_id", clientIdentifier.GetID()),
            });

            requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            try
            {
                HttpClient          client   = new HttpClient();
                HttpResponseMessage response = await client.PostAsync(TokenApi, requestContent);

                if (response.IsSuccessStatusCode)
                {
                    string replyJson = await response.Content.ReadAsStringAsync();

                    resultToken = CreateToken(replyJson);
                    resultToken.refreshToken = tokenData.refreshToken;
                }
            }
            catch (Exception) { }

            return(resultToken);
        }
Beispiel #4
0
        public void Analytics_default_span_tags_are_added_when_not_using_threshold_logging_tracer()
        {
            var expectedTags = new Dictionary <string, string>
            {
                { Tags.Component.Key, ClientIdentifier.GetClientDescription() },
                { Tags.DbType.Key, CouchbaseTags.DbTypeCouchbase },
                { Tags.SpanKind.Key, Tags.SpanKindClient },
                { CouchbaseTags.OperationId, "1" },
                { CouchbaseTags.Service, CouchbaseTags.ServiceAnalytics },
                { Tags.DbStatement.Key, DefaultStatement }
            };

            var mockAnalyticsQuery = new Mock <IAnalyticsRequest>();

            mockAnalyticsQuery.Setup(x => x.OriginalStatement).Returns(DefaultStatement);
            mockAnalyticsQuery.Setup(x => x.CurrentContextId).Returns("1");

            var mockTracer = new MockTracer();

            using (mockTracer.StartParentScope(mockAnalyticsQuery.Object))
            {
                // start and end scope
            }

            Assert.AreEqual(1, mockTracer.FinishedSpans().Count);
            var span = mockTracer.FinishedSpans().First();

            Assert.AreEqual(expectedTags, span.Tags);
        }
        public void Duplicate_Identifiers_for_same_client_passes()
        {
            var identifier = new ClientEditorForm.Identifier {
                TypeId = 1, Value = "foo"
            };
            var clientIdentifer = new ClientIdentifier
            {
                Client = new Client {
                    Id = 42
                },
                ClientIdentifierType = new ClientIdentifierType {
                    Id = 1
                },
                Value = "foo"
            };
            var command = GetCommand(add: true);

            command.Editor.ClientId    = 42;
            command.Editor.Identifiers = new[] { identifier };

            context.ClientIdentifiers = Substitute.For <IDbSet <ClientIdentifier>, IDbAsyncEnumerable <ClientIdentifier> >()
                                        .Initialize(new[] { clientIdentifer }.AsQueryable());

            handler.EnsureIdentifiersAreNotInUse(command);

            Assert.IsTrue(command.ModelState.IsValid);
        }
        public async Task InitWithKeylessAnonUserAddsKeyAndReusesIt()
        {
            // Note, we don't care about polling mode vs. streaming mode for this functionality.
            await WithServerAsync(async server =>
            {
                server.ForAllRequests(r => r.WithDelay(TimeSpan.FromSeconds(2)).WithJsonBody(PollingData(_flagData1)));

                var config   = BaseConfig(server, UpdateMode.Polling);
                var name     = "Sue";
                var anonUser = User.Builder((string)null).Name(name).Anonymous(true).Build();

                // Note, on mobile platforms, the generated user key is the device ID and is stable; on other platforms,
                // it's a GUID that is cached in local storage. Calling ClearCachedClientId() resets the latter.
                ClientIdentifier.ClearCachedClientId();

                string generatedKey = null;
                using (var client = await TestUtil.CreateClientAsync(config, anonUser))
                {
                    Assert.NotNull(client.User.Key);
                    generatedKey = client.User.Key;
                    Assert.Equal(name, client.User.Name);
                }

                using (var client = await TestUtil.CreateClientAsync(config, anonUser))
                {
                    Assert.Equal(generatedKey, client.User.Key);
                }
            });
        }
Beispiel #7
0
        protected HttpServiceBase(CouchbaseHttpClient httpClient)
        {
            HttpClient = httpClient;

            // set custom header for client / connection ID
            httpClient.DefaultRequestHeaders.Add(ConnectionIdHeaderName, ClientIdentifier.FormatConnectionString(ConnectionId));
        }
        public void BuidConnectionId_returns_expected_json_structure()
        {
            var connectionId = SequenceGenerator.GetRandomLong();
            var expected     = $"{ClientIdentifier.InstanceId:x16}/{connectionId:x16}";

            Assert.AreEqual(expected, ClientIdentifier.FormatConnectionString(connectionId));
        }
Beispiel #9
0
 internal static ISpanBuilder AddDefaultTags(this ISpanBuilder builder)
 {
     return(builder
            .WithTag(Tags.Component, ClientIdentifier.GetClientDescription())
            .WithTag(Tags.DbType, CouchbaseTags.DbTypeCouchbase)
            .WithTag(Tags.SpanKind, Tags.SpanKindClient));
 }
 public ProteinBenchmark UpdateFromClientIdentifier(ClientIdentifier clientIdentifier)
 {
     SourceName = clientIdentifier.Name;
     SourcePath = clientIdentifier.ToServerPortString();
     SourceGuid = clientIdentifier.Guid;
     return(this);
 }
Beispiel #11
0
        public void SetCommand(ClientIdentifier id, ICommand command)
        {
            if (!clients.Contains(id))
                throw new InvalidOperationException("ID " + id.Name + "is unknown");

            commands[id] = command;
        }
Beispiel #12
0
 internal static IInternalSpan WithDefaultAttributes(this IInternalSpan span)
 {
     span.WithTag(CouchbaseTags.OpenTracingTags.Component, ClientIdentifier.GetClientDescription());
     span.WithTag(CouchbaseTags.OpenTracingTags.DbType, CouchbaseTags.DbTypeCouchbase);
     span.WithTag(CouchbaseTags.OpenTracingTags.SpanKind, CouchbaseTags.OpenTracingTags.SpanKindClient);
     return(span);
 }
        public void Can_Create_DiagnosticsReport_With_ReportId()
        {
            using (var cluster = new Cluster(TestConfiguration.GetDefaultConfiguration()))
            {
                cluster.SetupEnhancedAuth();
                cluster.OpenBucket("default");

                const string reportId = "my-report";
                var          report   = cluster.Diagnostics(reportId);

                Assert.IsNotNull(report);
                Assert.AreEqual(reportId, report.Id);
                Assert.AreEqual(ClientIdentifier.GetClientDescription(), report.Sdk);
                Assert.AreEqual(1, report.Version);

                Assert.IsTrue(report.Services["kv"].Any(e => e.Type == ServiceType.KeyValue)); // at least one KV
                Assert.IsTrue(report.Services["view"].Any(e => e.Type == ServiceType.Views));  // at least one Index
                Assert.IsTrue(report.Services["n1ql"].Any(e => e.Type == ServiceType.Query));  // at least one N1QL

                if (cluster.GetClusterVersion() >= new ClusterVersion(new Version(5, 0)))
                {
                    Assert.IsTrue(report.Services["fts"].Any(e => e.Type == ServiceType.Search));
                }
                if (cluster.GetClusterVersion() >= new ClusterVersion(new Version(6, 0)))
                {
                    Assert.IsFalse(report.Services.ContainsKey("cbas"));
                }
            }
        }
Beispiel #14
0
        public void Search_default_span_tags_are_added_when_not_using_threshold_logging_tracer()
        {
            // need to reset to ensure request IDs match
            SequenceGenerator.Reset();

            var expectedTags = new Dictionary <string, string>
            {
                { Tags.Component.Key, ClientIdentifier.GetClientDescription() },
                { Tags.DbType.Key, CouchbaseTags.DbTypeCouchbase },
                { Tags.SpanKind.Key, Tags.SpanKindClient },
                { CouchbaseTags.OperationId, "1" },
                { CouchbaseTags.Service, CouchbaseTags.ServiceSearch }
            };

            var searchQuery = new SearchQuery
            {
                Index = "index",
                Query = new MatchQuery("test")
            };

            var mockTracer = new MockTracer();

            using (mockTracer.StartParentScope(searchQuery))
            {
                // start and end scope
            }

            Assert.AreEqual(1, mockTracer.FinishedSpans().Count);
            var span = mockTracer.FinishedSpans().First();

            Assert.AreEqual(expectedTags, span.Tags);
        }
Beispiel #15
0
        public void DifferentObjectsCanStillBeEqual()
        {
            Guid             identity    = Guid.NewGuid();
            ClientIdentifier identifier1 = new ClientIdentifier(identity);
            ClientIdentifier identifier2 = new ClientIdentifier(identity);

            Assert.AreEqual(identifier1, identifier2);
        }
Beispiel #16
0
 public User(UserDto dto)
 {
     Identifier       = new UserIdentifier(dto.Id);
     ClientIdentifier = new ClientIdentifier(dto.ClientId);
     LoginInfo        = new LoginInfo(dto.Username, dto.Password);
     Name             = new Name(dto.FirstName, dto.LastName);
     Email            = new Email(dto.EmailAddress);
 }
Beispiel #17
0
 public User(Guid clientId, string username, string password, string firstName, string lastName, string email)
 {
     Identifier       = new UserIdentifier();
     ClientIdentifier = new ClientIdentifier(clientId);
     LoginInfo        = new LoginInfo(username, password);
     Name             = new Name(firstName, lastName);
     Email            = new Email(email);
 }
Beispiel #18
0
        public Client GetBy(ClientIdentifier identifier)
        {
            if (dict.ContainsKey(identifier))
            {
                return(dict [identifier]);
            }

            return(null);
        }
Beispiel #19
0
        protected HttpServiceBase(HttpClient httpClient, IDataMapper dataMapper, ClusterOptions clusterOptions)
        {
            HttpClient     = httpClient;
            DataMapper     = dataMapper;
            ClusterOptions = clusterOptions;

            // set custom header for client / connection ID
            httpClient.DefaultRequestHeaders.Add(ConnectionIdHeaderName, ClientIdentifier.FormatConnectionString(ConnectionId));
        }
Beispiel #20
0
        protected HttpServiceBase(HttpClient httpClient, IDataMapper dataMapper, Couchbase.Configuration configuration)
        {
            HttpClient    = httpClient;
            DataMapper    = dataMapper;
            Configuration = configuration;

            // set custom header for client / connection ID
            httpClient.DefaultRequestHeaders.Add(ConnectionIdHeaderName, ClientIdentifier.FormatConnectionString(ConnectionId));
        }
Beispiel #21
0
        private void ValidateInput(ClientIdentifier id, Object obj, string varName)
        {
            if (!commands.ContainsKey(id))
                throw new InvalidOperationException("Id " + id.Name + " not found");

            obj.CheckNull(varName);

            if (commands[id] != null)
                throw new InvalidOperationException(id.Name + " already made a move for this turn.");
        }
Beispiel #22
0
        public override void SetCharacter(ClientIdentifier id, Pokemon pkmn)
        {
            if (!clients.ContainsKey(id))
                throw new InvalidOperationException("ClientIdentifier " + id.Name + " not found.");

            if (clients[id] != null)
                throw new InvalidOperationException("ClientIdentifer " + id.Name + " has already set its char");

            clients[id] = pkmn;
            clientsLeft--;
        }
Beispiel #23
0
        internal BattleData(ClientIdentifier player, ClientIdentifier ai)
        {
            Player = player;
            Ai = ai;

            clients.Add(Ai);
            clients.Add(Player);

            PlayerPokemon = new PokemonWrapper(Player);
            AiPokemon = new PokemonWrapper(Ai);
        }
Beispiel #24
0
        public void Can_Create_DiagnosticsReport()
        {
            var reportId              = Guid.NewGuid().ToString();
            var kvLastActivity        = DateTime.UtcNow;
            var viewLastActivity      = kvLastActivity.AddSeconds(-5);
            var queryLastActivity     = kvLastActivity.AddSeconds(-10);
            var searchLastActivity    = kvLastActivity.AddSeconds(-15);
            var analyticsLastActivity = kvLastActivity.AddSeconds(-20);

            var connection = Mock.Of <IConnection>(c =>
                                                   c.LastActivity == kvLastActivity &&
                                                   c.IsConnected == true &&
                                                   c.IsAuthenticated == true
                                                   );

            var connectionPool = Mock.Of <IConnectionPool>(p =>
                                                           p.Connections == new List <IConnection> {
                connection
            }
                                                           );

            var server = Mock.Of <IServer>(s =>
                                           s.IsDataNode == true &&
                                           s.ConnectionPool == connectionPool &&
                                           s.IsViewNode == true &&
                                           s.ViewClient.LastActivity == viewLastActivity &&
                                           s.IsQueryNode == true &&
                                           s.QueryClient.LastActivity == queryLastActivity &&
                                           s.IsSearchNode == true &&
                                           s.SearchClient.LastActivity == searchLastActivity &&
                                           s.IsAnalyticsNode == true &&
                                           s.AnalyticsClient.LastActivity == analyticsLastActivity
                                           );

            var configInfo = Mock.Of <IConfigInfo>(c =>
                                                   c.Servers == new List <IServer> {
                server
            }
                                                   );

            var report = DiagnosticsReportProvider.CreateDiagnosticsReport(reportId, new[] { configInfo });

            Assert.IsNotNull(report);
            Assert.AreEqual(reportId, report.Id);
            Assert.AreEqual(1, report.Version);
            Assert.AreEqual(ClientIdentifier.GetClientDescription(), report.Sdk);

            Assert.IsTrue(report.Services["kv"].First(x => x.Type == ServiceType.KeyValue).LastActivity > 0);
            Assert.IsTrue(report.Services["view"].First(x => x.Type == ServiceType.Views).LastActivity > 0);
            Assert.IsTrue(report.Services["n1ql"].First(x => x.Type == ServiceType.Query).LastActivity > 0);
            Assert.IsTrue(report.Services["fts"].First(x => x.Type == ServiceType.Search).LastActivity > 0);
            Assert.IsTrue(report.Services["cbas"].First(x => x.Type == ServiceType.Analytics).LastActivity > 0);
        }
Beispiel #25
0
        private LogonMsg RemoveLookup(ClientIdentifier client)
        {
            if (client == null)
            {
                return(default(LogonMsg));
            }

            var clientIdType  = client.ClientIdType;
            var clientIdValue = client.ClientIdValue;

            return(this.RemoveLookup(clientIdType, clientIdValue));
        }
 /// <summary>
 /// Serves as a hash function for a particular type.
 /// </summary>
 /// <returns>
 /// A hash code for the current <see cref="T:System.Object"/>.
 /// </returns>
 /// <filterpriority>2</filterpriority>
 public override int GetHashCode()
 {
     unchecked
     {
         var result = (SystemDataSet != null ? SystemDataSet.GetHashCode() : 0);
         result = (result * 397) ^ (ProviderIdentifier != null ? ProviderIdentifier.GetHashCode() : 0);
         result = (result * 397) ^ (ClientIdentifier != null ? ClientIdentifier.GetHashCode() : 0);
         result = (result * 397) ^ CoDependentIndicator.GetHashCode();
         result = (result * 397) ^ (TedsServiceType != null ? TedsServiceType.GetHashCode() : 0);
         return(result);
     }
 }
Beispiel #27
0
 public void Dispose()
 {
     if (!m_Disposed)
     {
         ClientIdentifier client = ClientStorage.GetInstance().RemoveClient(m_ListenSocket);
         this.m_PacketsHander.DirectionFilter.remove(client);
         m_ListenSocket.Disconnect(false);
         this.m_ListenSocket.Dispose();
         this.m_Disposed = true;
         this.m_Other.Dispose();
     }
 }
        public void Hello_key_is_formatted_with_json_properties()
        {
            const ulong connectionId = 123;
            var         result       = IOServiceBase.BuildHelloKey(connectionId);

            var expected = JsonConvert.SerializeObject(new
            {
                i = string.Join("/", ClientIdentifier.InstanceId.ToString("x16"), connectionId.ToString("x16")),
                a = ClientIdentifier.GetClientDescription()
            }, Formatting.None);

            Assert.AreEqual(expected, result);
        }
Beispiel #29
0
        protected HttpClient CreateHttpClient(TimeSpan?timeout = null)
        {
            var httpClient = HttpClientFactory.Create();

            // set custom header for client / connection ID
            httpClient.DefaultRequestHeaders.Add(ConnectionIdHeaderName, ClientIdentifier.FormatConnectionString(ConnectionId));

            if (timeout != null)
            {
                httpClient.Timeout = timeout.GetValueOrDefault();
            }

            return(httpClient);
        }
Beispiel #30
0
        public HttpClient Create()
        {
            var httpClient = new HttpClient(_sharedHandler, false)
            {
                DefaultRequestHeaders =
                {
                    ExpectContinue = _context.ClusterOptions.EnableExpect100Continue
                }
            };

            ClientIdentifier.SetUserAgent(httpClient.DefaultRequestHeaders);

            return(httpClient);
        }
        internal static string BuildHelloKey(ulong connectionId)
        {
            var agent = ClientIdentifier.GetClientDescription();

            if (agent.Length > 200)
            {
                agent = agent.Substring(0, 200);
            }

            return(JsonConvert.SerializeObject(new
            {
                i = ClientIdentifier.FormatConnectionString(connectionId),
                a = agent
            }, Formatting.None));
        }
Beispiel #32
0
        internal static string BuildHelloKey(ulong connectionId)
        {
            var agent = ClientIdentifier.GetClientDescription();

            if (agent.Length > 200)
            {
                agent = agent.Substring(0, 200);
            }

            return(JsonSerializer.Serialize(new HelloKey
            {
                Identifier = ClientIdentifier.FormatConnectionString(connectionId),
                Agent = agent
            }, InternalSerializationContext.Default.HelloKey));
        }
Beispiel #33
0
        public void UniqueDeviceIdGeneratesStableValue()
        {
            // Note, on mobile platforms, the generated user key is the device ID and is stable; on other platforms,
            // it's a GUID that is cached in local storage. Calling ClearCachedClientId() resets the latter.
            ClientIdentifier.ClearCachedClientId();

            var ddi = new DefaultDeviceInfo();
            var id0 = ddi.UniqueDeviceId();

            Assert.NotNull(id0);

            var id1 = ddi.UniqueDeviceId();

            Assert.Equal(id0, id1);
        }
Beispiel #34
0
        private static bool BenchmarkMatchesClientIdentifier(ProteinBenchmark b, ClientIdentifier clientIdentifier)
        {
            // most specific, matches ClientIdentifier on Guid first... then Name, Server, and Port
            if (b.SlotIdentifier.ClientIdentifier.Equals(clientIdentifier))
            {
                return(true);
            }

            // less specific, matches ClientIdentifier only on Name, Server, and Port
            if (ClientIdentifier.ProteinBenchmarkEqualityComparer.Equals(b.SlotIdentifier.ClientIdentifier, clientIdentifier))
            {
                return(true);
            }

            return(false);
        }
 public void PlayAttackAnimation(ClientIdentifier id)
 {
     sprites[id].PlayAttackAnimation();
 }
Beispiel #36
0
 public virtual void SetItem(ClientIdentifier id, ClientIdentifier target, Item item) { throw new InvalidOperationException("Wong operation"); }
 public void SetHP(ClientIdentifier id, int value)
 {
     dataViews[id].SetHP(value);
 }
Beispiel #38
0
 public virtual void SetCharacter(ClientIdentifier id, Pokemon pkmn) { throw new InvalidOperationException("Wong operation"); }
Beispiel #39
0
 public virtual void SetMove(ClientIdentifier id, ClientIdentifier target, Move move) { throw new InvalidOperationException("Wong operation"); }
 public void SetCharacter(ClientIdentifier id, Pokemon pkmn)
 {
     CurrentState.SetCharacter(id, pkmn);
 }
Beispiel #41
0
 public SetStatusEvent(IBattleGraphicController graphic, ClientIdentifier id, StatusCondition condition)
 {
     this.graphic = graphic;
     this.id = id;
     this.condition = condition;
 }
Beispiel #42
0
 public ChangeCommand(ClientIdentifier source, Pokemon newPkmn)
 {
     Source = source;
     Pokemon = newPkmn;
 }
Beispiel #43
0
 private bool NeedsPokemon(BattleData data, ClientIdentifier id)
 {
     var pkmn = data.GetPokemon(id);
     return pkmn.Pokemon == null || pkmn.Condition == StatusCondition.KO;
 }
Beispiel #44
0
 public ItemCommand(ClientIdentifier source, Item item)
 {
     Source = source;
     Item = item;
 }
 public void SetPokemonStatus(ClientIdentifier id, StatusCondition condition)
 {
     throw new NotImplementedException();
 }
Beispiel #46
0
 public void SetItem(ClientIdentifier id, ClientIdentifier target, Base.Item item)
 {
     ValidateInput(id, item, "item");
     commands[id] = new ItemCommand(id, item);
     clientCnt--;
 }
 public void SetMove(ClientIdentifier id, ClientIdentifier target, Move move)
 {
     CurrentState.SetMove(id, target, move);
 }
Beispiel #48
0
 public void SetMove(ClientIdentifier id, ClientIdentifier target, Move move)
 {
     ValidateInput(id, move, "move");
     commands[id] = new MoveCommand(id, target, move);
     clientCnt--;
 }
Beispiel #49
0
 public PokemonWrapper GetPokemon(ClientIdentifier id)
 {
     return id == Player ? PlayerPokemon : AiPokemon;
 }
Beispiel #50
0
 public MoveCommand(ClientIdentifier source, ClientIdentifier target, Move move)
 {
     this.Move = move;
     this.Source = source;
     this.Target = target;
 }
 public void SetPokemon(ClientIdentifier id, PokemonWrapper pokemon)
 {
     dataViews[id].SetPokemon(pokemon);
     sprites[id].SetPokemon(pokemon.ID);
 }
 public PokemonWrapper GetPokemon(ClientIdentifier id)
 {
     return data.GetPokemon(id);
 }
Beispiel #53
0
 public SetHPEvent(IBattleGraphicController graphic, ClientIdentifier id, int hp)
 {
     this.graphic = graphic;
     this.id = id;
     this.hp = hp;
 }
Beispiel #54
0
 public void SetPokemon(ClientIdentifier id, PokemonWrapper pokemon)
 {
     PokemonChanged(this, new ClientPokemonChangedEventArgs(id, pokemon));
 }
 public ClientStatusChangedEventArgs(ClientIdentifier id, StatusCondition status)
 {
     Status = status;
     ID = id;
 }
Beispiel #56
0
 public void SetHP(ClientIdentifier id, int hp)
 {
     HPChanged(this, new HPChangedEventArgs(id, hp));
 }
 public void SetItem(ClientIdentifier id, ClientIdentifier target, Item item)
 {
     CurrentState.SetItem(id, target, item);
 }
Beispiel #58
0
 public void SetCharacter(ClientIdentifier id, Pokemon pkmn)
 {
     ValidateInput(id, pkmn, "pkmn");
     commands[id] = new ChangeCommand(id, pkmn);
     clientCnt--;
 }
 public ClientPokemonChangedEventArgs(ClientIdentifier id, PokemonWrapper pokemon)
 {
     ID = id;
     Pokemon = pokemon;
 }
Beispiel #60
0
 public SetPokemonEvent(IBattleGraphicController graphic, ClientIdentifier id, PokemonWrapper pokemon)
 {
     this.graphic = graphic;
     this.id = id;
     this.pokemon = pokemon;
 }