/// <summary>
        /// Adds Dapr client services to the provided <see cref="IServiceCollection" />. This does not include integration
        /// with ASP.NET Core MVC. Use the <c>AddDapr()</c> extension method on <c>IMvcBuilder</c> to register MVC integration.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" />.</param>
        /// <param name="configure"></param>
        public static void AddDaprClient(this IServiceCollection services, Action <DaprClientBuilder> configure = null)
        {
            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            // This pattern prevents registering services multiple times in the case AddDaprClient is called
            // by non-user-code.
            if (services.Any(s => s.ImplementationType == typeof(DaprClientMarkerService)))
            {
                return;
            }

            services.AddSingleton <DaprClientMarkerService>();

            services.AddSingleton(_ =>
            {
                var builder = new DaprClientBuilder();
                if (configure != null)
                {
                    configure.Invoke(builder);
                }

                return(builder.Build());
            });
        }
        public void DaprClientBuilder_UsesThrowOperationCanceledOnCancellation_ByDefault()
        {
            var builder    = new DaprClientBuilder();
            var daprClient = builder.Build();

            Assert.True(builder.GrpcChannelOptions.ThrowOperationCanceledOnCancellation);
        }
示例#3
0
        public static IServiceCollection AddDaprClient(
            [NotNull] this IServiceCollection services,
            Action <DaprClientBuilder> setup = null)
        {
            Check.NotNull(services, nameof(services));

            services.TryAddSingleton(provider =>
            {
                var abpSystemTextJsonSerializerOptions = provider.GetRequiredService <IOptions <AbpSystemTextJsonSerializerOptions> >().Value;
                var abpDaprClientOptions = provider.GetRequiredService <IOptions <AbpDaprClientOptions> >().Value;

                var builder = new DaprClientBuilder()
                              .UseHttpEndpoint(abpDaprClientOptions.HttpEndpoint)
                              .UseJsonSerializationOptions(abpSystemTextJsonSerializerOptions.JsonSerializerOptions);

                if (!abpDaprClientOptions.GrpcEndpoint.IsNullOrWhiteSpace() &&
                    abpDaprClientOptions.GrpcChannelOptions != null)
                {
                    builder
                    .UseGrpcEndpoint(abpDaprClientOptions.GrpcEndpoint)
                    .UseGrpcChannelOptions(abpDaprClientOptions.GrpcChannelOptions);
                }

                setup?.Invoke(builder);

                return(builder.Build());
            });

            services.AddHttpClient(AbpDaprClientModule.DaprHttpClient);

            return(services);
        }
示例#4
0
        static internal async void StartMessageGeneratorAsync(int delayInMilliseconds)
        {
            // the name of the component and the topic happen to be the same here...
            const string PubsubComponentName = "receivemediapost";
            const string PubsubTopicName     = "receivemediapost";

            TimeSpan delay = TimeSpan.FromMilliseconds(delayInMilliseconds);

            DaprClientBuilder daprClientBuilder = new DaprClientBuilder();

            DaprClient client = daprClientBuilder.Build();

            while (true)
            {
                SocialMediaMessage message = GeneratePost();

                try
                {
                    Console.WriteLine("Publishing");
                    using (PublishCallTime.NewTimer())
                    {
                        await client.PublishEventAsync <SocialMediaMessage>(PubsubComponentName, PubsubTopicName, message);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Caught {0}", e.ToString());
                    PublishFailureCount.Inc();
                }

                await Task.Delay(delay);
            }
        }
        public void DaprClientBuilder_SetsNullApiToken()
        {
            var builder = new DaprClientBuilder();

            builder.UseDaprApiToken(null);
            builder.Build();
            Assert.Null(builder.DaprApiToken);
        }
        public void DaprClientBuilder_SetsApiToken()
        {
            var builder = new DaprClientBuilder();

            builder.UseDaprApiToken("test_token");
            builder.Build();
            Assert.Equal("test_token", builder.DaprApiToken);
        }
示例#7
0
        static internal async void StartQueryLoopAsync(int delayInMilliseconds)
        {
            Console.WriteLine("Starting query loop");

            TimeSpan delay = TimeSpan.FromMilliseconds(delayInMilliseconds);

            DaprClientBuilder daprClientBuilder = new DaprClientBuilder();
            DaprClient        client            = daprClientBuilder.Build();

            DateTime lastSnapshotTime = DateTime.MinValue;

            while (true)
            {
                Console.WriteLine("Sleeping '{0}' ms", delayInMilliseconds);
                await Task.Delay(delay);

                Dictionary <string, int> stats = new Dictionary <string, int>();

                if (lastSnapshotTime != DateTime.MinValue)
                {
                    DelaySinceLastSnapShot.Set(DateTime.UtcNow.Subtract(lastSnapshotTime).TotalSeconds);
                }

                foreach (string hashtag in Constants.HashTags)
                {
                    foreach (string sentiment in Constants.Sentiments)
                    {
                        string key     = hashtag + "_" + sentiment;
                        var    actorId = new ActorId(key);
                        var    proxy   = ActorProxy.Create <IHashTagActor>(actorId, "HashTagActor");

                        Console.WriteLine($"GetCount on {key}.");
                        int count = -1;
                        try
                        {
                            using (ActorMethodCallTime.NewTimer())
                            {
                                count = await proxy.GetCount(key);
                            }

                            stats.Add(key, count);
                            Console.WriteLine($"key={key}, value={count}.");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"{e}");
                            ActorMethodFailureCount.Inc();
                            throw;
                        }
                    }
                }

                lastSnapshotTime = DateTime.UtcNow;

                await client.SaveStateAsync <Dictionary <string, int> >("statestore", "statskey", stats);
            }
        }
        public void DaprClientBuilder_ValidatesHttpEndpointScheme()
        {
            var builder = new DaprClientBuilder();

            builder.UseHttpEndpoint("ftp://example.com");

            var ex = Assert.Throws <InvalidOperationException>(() => builder.Build());

            Assert.Equal("The HTTP endpoint must use http or https.", ex.Message);
        }
        public override void PostConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;

            services.ExecutePreConfiguredActions <DaprServiceBusOptions>();
            services.TryAddSingleton(provider =>
            {
                var options = provider.GetRequiredService <IOptions <DaprServiceBusOptions> >();
                var builder = new DaprClientBuilder();
                options.Value.ConfigreDaprClientBuilder?.Invoke(builder);
                return(builder.Build());
            });
        }
示例#10
0
        public static TestClient <DaprClient> CreateForDaprClient(Action <DaprClientBuilder>?configure = default)
        {
            var handler    = new CapturingHandler();
            var httpClient = new HttpClient(handler);

            var builder = new DaprClientBuilder();

            configure?.Invoke(builder);

            builder.UseHttpClientFactory(() => httpClient);
            builder.UseGrpcChannelOptions(new GrpcChannelOptions()
            {
                HttpClient = httpClient,
                ThrowOperationCanceledOnCancellation = true,
            });

            return(new TestClient <DaprClient>(builder.Build(), handler));
        }
示例#11
0
        static async Task StartMessageGeneratorAsync()
        {
            var daprClientBuilder = new DaprClientBuilder();
            var client            = daprClientBuilder.Build();

            while (true)
            {
                var message = GenerateNewMessage();
                Console.WriteLine("Publishing: {0}", message);

                try
                {
                    await client.PublishEventAsync <SampleMessage>("sampletopic", message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }

                // Delay 10 seconds
                await Task.Delay(TimeSpan.FromSeconds(10.0));
            }
        }
示例#12
0
        static internal async void StartValidationLoopAsync(int delayInSeconds)
        {
            const string SnapshotAppName = "snapshot";
            TimeSpan     delay           = TimeSpan.FromSeconds(delayInSeconds);

            DaprClientBuilder daprClientBuilder = new DaprClientBuilder();
            DaprClient        client            = daprClientBuilder.Build();

            Dictionary <string, int> prevStats = null;
            Dictionary <string, int> stats     = null;

            while (true)
            {
                Console.WriteLine("Checking stats in {0} seconds", delayInSeconds);
                await Task.Delay(delay);

                try
                {
                    using (ServiceInvocationCallTime.NewTimer())
                    {
                        var httpOptions = new HttpInvocationOptions()
                        {
                            Method = HttpMethod.Get
                        };

                        stats = await client.InvokeMethodAsync <Dictionary <string, int> >(SnapshotAppName, "hashtagdata", httpOptions);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Caught {0}", e.ToString());
                    ServiceInvocationFailureCount.Inc();
                    continue;
                }

                // skip the calculation the first time
                if (prevStats != null)
                {
                    int changed = 0;
                    foreach (var kv in stats)
                    {
                        if (prevStats.ContainsKey(kv.Key) == false ||
                            prevStats[kv.Key] != kv.Value)
                        {
                            changed++;
                        }
                    }

                    Console.WriteLine("Number changed is {0}", changed);
                    if (changed == 0)
                    {
                        LogStats(prevStats, stats);
                        UnchangedStatsMetric.IncTo(1);
                    }
                    else
                    {
                        UnchangedStatsMetric.IncTo(0);
                    }
                }

                prevStats = stats;
            }
        }