Skip to content

Commit 36d5900

Browse files
[Examples] Nullable (open-telemetry#5881)
Co-authored-by: Mikel Blanchard <[email protected]>
1 parent b0ebf35 commit 36d5900

16 files changed

+142
-127
lines changed

examples/Console/Examples.Console.csproj

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,6 @@
44
<OutputType>Exe</OutputType>
55
<TargetFramework>$(DefaultTargetFrameworkForExampleApps)</TargetFramework>
66
<NoWarn>$(NoWarn),CS0618</NoWarn>
7-
8-
<!-- this is temporary. will remove in future PR. -->
9-
<Nullable>disable</Nullable>
107
</PropertyGroup>
118

129
<ItemGroup>

examples/Console/InstrumentationWithActivitySource.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,13 @@ public void Start(string url)
4747
var context = this.listener.GetContext();
4848

4949
using var activity = source.StartActivity(
50-
$"{context.Request.HttpMethod}:{context.Request.Url.AbsolutePath}",
50+
$"{context.Request.HttpMethod}:{context.Request.Url!.AbsolutePath}",
5151
ActivityKind.Server);
5252

5353
var headerKeys = context.Request.Headers.AllKeys;
5454
foreach (var headerKey in headerKeys)
5555
{
56-
string headerValue = context.Request.Headers[headerKey];
56+
string? headerValue = context.Request.Headers[headerKey];
5757
activity?.SetTag($"http.header.{headerKey}", headerValue);
5858
}
5959

@@ -62,7 +62,7 @@ public void Start(string url)
6262
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
6363
{
6464
requestContent = reader.ReadToEnd();
65-
childSpan.AddEvent(new ActivityEvent("StreamReader.ReadToEnd"));
65+
childSpan?.AddEvent(new ActivityEvent("StreamReader.ReadToEnd"));
6666
}
6767

6868
activity?.SetTag("request.content", requestContent);
@@ -90,8 +90,8 @@ public void Dispose()
9090

9191
private class SampleClient : IDisposable
9292
{
93-
private CancellationTokenSource cts;
94-
private Task requestTask;
93+
private CancellationTokenSource? cts;
94+
private Task? requestTask;
9595

9696
public void Start(string url)
9797
{
@@ -154,7 +154,7 @@ public void Dispose()
154154
if (this.cts != null)
155155
{
156156
this.cts.Cancel();
157-
this.requestTask.Wait();
157+
this.requestTask!.Wait();
158158
this.requestTask.Dispose();
159159
this.cts.Dispose();
160160
}

examples/Console/Program.cs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,16 @@ public static void Main(string[] args)
3333
{
3434
Parser.Default.ParseArguments<ZipkinOptions, PrometheusOptions, MetricsOptions, LogsOptions, GrpcNetClientOptions, HttpClientOptions, ConsoleOptions, OpenTelemetryShimOptions, OpenTracingShimOptions, OtlpOptions, InMemoryOptions>(args)
3535
.MapResult(
36-
(ZipkinOptions options) => TestZipkinExporter.Run(options.Uri),
37-
(PrometheusOptions options) => TestPrometheusExporter.Run(options.Port),
36+
(ZipkinOptions options) => TestZipkinExporter.Run(options),
37+
(PrometheusOptions options) => TestPrometheusExporter.Run(options),
3838
(MetricsOptions options) => TestMetrics.Run(options),
3939
(LogsOptions options) => TestLogs.Run(options),
40-
(GrpcNetClientOptions options) => TestGrpcNetClient.Run(),
41-
(HttpClientOptions options) => TestHttpClient.Run(),
40+
(GrpcNetClientOptions options) => TestGrpcNetClient.Run(options),
41+
(HttpClientOptions options) => TestHttpClient.Run(options),
4242
(ConsoleOptions options) => TestConsoleExporter.Run(options),
4343
(OpenTelemetryShimOptions options) => TestOTelShimWithConsoleExporter.Run(options),
4444
(OpenTracingShimOptions options) => TestOpenTracingShim.Run(options),
45-
(OtlpOptions options) => TestOtlpExporter.Run(options.Endpoint, options.Protocol),
45+
(OtlpOptions options) => TestOtlpExporter.Run(options),
4646
(InMemoryOptions options) => TestInMemoryExporter.Run(options),
4747
errs => 1);
4848
}
@@ -54,7 +54,7 @@ public static void Main(string[] args)
5454
internal class ZipkinOptions
5555
{
5656
[Option('u', "uri", HelpText = "Please specify the uri of Zipkin backend", Required = true)]
57-
public string Uri { get; set; }
57+
public required string Uri { get; set; }
5858
}
5959

6060
[Verb("prometheus", HelpText = "Specify the options required to test Prometheus")]
@@ -83,10 +83,10 @@ internal class MetricsOptions
8383
public int DefaultCollectionPeriodMilliseconds { get; set; }
8484

8585
[Option("useExporter", Default = "console", HelpText = "Options include otlp or console.", Required = false)]
86-
public string UseExporter { get; set; }
86+
public string? UseExporter { get; set; }
8787

8888
[Option('e', "endpoint", HelpText = "Target to which the exporter is going to send metrics (default value depends on protocol).", Default = null)]
89-
public string Endpoint { get; set; }
89+
public string? Endpoint { get; set; }
9090

9191
[Option('p', "useGrpc", HelpText = "Use gRPC or HTTP when using the OTLP exporter", Required = false, Default = true)]
9292
public bool UseGrpc { get; set; }
@@ -121,26 +121,26 @@ internal class OpenTracingShimOptions
121121
internal class OtlpOptions
122122
{
123123
[Option('e', "endpoint", HelpText = "Target to which the exporter is going to send traces (default value depends on protocol).", Default = null)]
124-
public string Endpoint { get; set; }
124+
public string? Endpoint { get; set; }
125125

126126
[Option('p', "protocol", HelpText = "Transport protocol used by exporter. Supported values: grpc and http/protobuf.", Default = "grpc")]
127-
public string Protocol { get; set; }
127+
public string? Protocol { get; set; }
128128
}
129129

130130
[Verb("logs", HelpText = "Specify the options required to test Logs")]
131131
internal class LogsOptions
132132
{
133133
[Option("useExporter", Default = "otlp", HelpText = "Options include otlp or console.", Required = false)]
134-
public string UseExporter { get; set; }
134+
public string? UseExporter { get; set; }
135135

136136
[Option('e', "endpoint", HelpText = "Target to which the OTLP exporter is going to send logs (default value depends on protocol).", Default = null)]
137-
public string Endpoint { get; set; }
137+
public string? Endpoint { get; set; }
138138

139139
[Option('p', "protocol", HelpText = "Transport protocol used by OTLP exporter. Supported values: grpc and http/protobuf. Only applicable if Exporter is OTLP", Default = "grpc")]
140-
public string Protocol { get; set; }
140+
public string? Protocol { get; set; }
141141

142142
[Option("processorType", Default = "batch", HelpText = "export processor type. Supported values: simple and batch", Required = false)]
143-
public string ProcessorType { get; set; }
143+
public string? ProcessorType { get; set; }
144144

145145
[Option("scheduledDelay", Default = 5000, HelpText = "The delay interval in milliseconds between two consecutive exports.", Required = false)]
146146
public int ScheduledDelayInMilliseconds { get; set; }

examples/Console/TestConsoleExporter.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,21 @@ internal class TestConsoleExporter
1515
// (eg: C:\repos\opentelemetry-dotnet\examples\Console\)
1616
//
1717
// dotnet run console
18-
internal static object Run(ConsoleOptions options)
18+
internal static int Run(ConsoleOptions options)
1919
{
2020
return RunWithActivitySource();
2121
}
2222

23-
private static object RunWithActivitySource()
23+
private static int RunWithActivitySource()
2424
{
2525
// Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
2626
// and use Console exporter.
2727
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
28-
.AddSource("Samples.SampleClient", "Samples.SampleServer")
29-
.ConfigureResource(res => res.AddService("console-test"))
30-
.AddProcessor(new MyProcessor()) // This must be added before ConsoleExporter
31-
.AddConsoleExporter()
32-
.Build();
28+
.AddSource("Samples.SampleClient", "Samples.SampleServer")
29+
.ConfigureResource(res => res.AddService("console-test"))
30+
.AddProcessor(new MyProcessor()) // This must be added before ConsoleExporter
31+
.AddConsoleExporter()
32+
.Build();
3333

3434
// The above line is required only in applications
3535
// which decide to use OpenTelemetry.
@@ -43,7 +43,7 @@ private static object RunWithActivitySource()
4343
System.Console.ReadLine();
4444
}
4545

46-
return null;
46+
return 0;
4747
}
4848

4949
/// <summary>

examples/Console/TestGrpcNetClient.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@ namespace Examples.Console;
1212

1313
internal class TestGrpcNetClient
1414
{
15-
internal static object Run()
15+
internal static int Run(GrpcNetClientOptions options)
1616
{
17+
Debug.Assert(options != null, "options was null");
18+
1719
// Prerequisite for running this example.
1820
// In a separate console window, start the example
1921
// ASP.NET Core gRPC service by running the following command
@@ -55,6 +57,6 @@ internal static object Run()
5557
System.Console.WriteLine("Press Enter key to exit.");
5658
System.Console.ReadLine();
5759

58-
return null;
60+
return 0;
5961
}
6062
}

examples/Console/TestHttpClient.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@ internal class TestHttpClient
1515
// (eg: C:\repos\opentelemetry-dotnet\examples\Console\)
1616
//
1717
// dotnet run httpclient
18-
internal static object Run()
18+
internal static int Run(HttpClientOptions options)
1919
{
20+
Debug.Assert(options != null, "options was null");
21+
2022
System.Console.WriteLine("Hello World!");
2123

2224
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
@@ -36,6 +38,6 @@ internal static object Run()
3638
System.Console.WriteLine("Press Enter key to exit.");
3739
System.Console.ReadLine();
3840

39-
return null;
41+
return 0;
4042
}
4143
}

examples/Console/TestInMemoryExporter.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ internal class TestInMemoryExporter
1515
// (eg: C:\repos\opentelemetry-dotnet\examples\Console\)
1616
//
1717
// dotnet run inmemory
18-
internal static object Run(InMemoryOptions options)
18+
internal static int Run(InMemoryOptions options)
1919
{
2020
// List that will be populated with the traces by InMemoryExporter
2121
var exportedItems = new List<Activity>();
@@ -28,18 +28,18 @@ internal static object Run(InMemoryOptions options)
2828
System.Console.WriteLine($"ActivitySource: {activity.Source.Name} logged the activity {activity.DisplayName}");
2929
}
3030

31-
return null;
31+
return 0;
3232
}
3333

3434
private static void RunWithActivitySource(ICollection<Activity> exportedItems)
3535
{
3636
// Enable OpenTelemetry for the sources "Samples.SampleServer" and "Samples.SampleClient"
3737
// and use InMemory exporter.
3838
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
39-
.AddSource("Samples.SampleClient", "Samples.SampleServer")
40-
.ConfigureResource(r => r.AddService("inmemory-test"))
41-
.AddInMemoryExporter(exportedItems)
42-
.Build();
39+
.AddSource("Samples.SampleClient", "Samples.SampleServer")
40+
.ConfigureResource(r => r.AddService("inmemory-test"))
41+
.AddInMemoryExporter(exportedItems)
42+
.Build();
4343

4444
// The above line is required only in applications
4545
// which decide to use OpenTelemetry.

examples/Console/TestLogs.cs

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,16 @@ namespace Examples.Console;
99

1010
internal class TestLogs
1111
{
12-
internal static object Run(LogsOptions options)
12+
internal static int Run(LogsOptions options)
1313
{
1414
using var loggerFactory = LoggerFactory.Create(builder =>
1515
{
1616
builder.AddOpenTelemetry((opt) =>
1717
{
1818
opt.IncludeFormattedMessage = true;
1919
opt.IncludeScopes = true;
20-
if (options.UseExporter.Equals("otlp", StringComparison.OrdinalIgnoreCase))
20+
21+
if ("otlp".Equals(options.UseExporter, StringComparison.OrdinalIgnoreCase))
2122
{
2223
/*
2324
* Prerequisite to run this example:
@@ -43,31 +44,46 @@ internal static object Run(LogsOptions options)
4344

4445
var protocol = OpenTelemetry.Exporter.OtlpExportProtocol.Grpc;
4546

46-
if (options.Protocol.Trim().ToLower().Equals("grpc"))
47-
{
48-
protocol = OpenTelemetry.Exporter.OtlpExportProtocol.Grpc;
49-
}
50-
else if (options.Protocol.Trim().ToLower().Equals("http/protobuf"))
47+
if (!string.IsNullOrEmpty(options.Protocol))
5148
{
52-
protocol = OpenTelemetry.Exporter.OtlpExportProtocol.HttpProtobuf;
49+
switch (options.Protocol.Trim())
50+
{
51+
case "grpc":
52+
protocol = OpenTelemetry.Exporter.OtlpExportProtocol.Grpc;
53+
break;
54+
case "http/protobuf":
55+
protocol = OpenTelemetry.Exporter.OtlpExportProtocol.HttpProtobuf;
56+
break;
57+
default:
58+
System.Console.WriteLine($"Export protocol {options.Protocol} is not supported. Default protocol 'grpc' will be used.");
59+
break;
60+
}
5361
}
5462
else
5563
{
56-
System.Console.WriteLine($"Export protocol {options.Protocol} is not supported. Default protocol 'grpc' will be used.");
64+
System.Console.WriteLine("Protocol is null or empty. Default protocol 'grpc' will be used.");
5765
}
5866

5967
var processorType = ExportProcessorType.Batch;
60-
if (options.ProcessorType.Trim().ToLower().Equals("batch"))
61-
{
62-
processorType = ExportProcessorType.Batch;
63-
}
64-
else if (options.ProcessorType.Trim().ToLower().Equals("simple"))
68+
69+
if (!string.IsNullOrEmpty(options.ProcessorType))
6570
{
66-
processorType = ExportProcessorType.Simple;
71+
switch (options.ProcessorType.Trim())
72+
{
73+
case "batch":
74+
processorType = ExportProcessorType.Batch;
75+
break;
76+
case "simple":
77+
processorType = ExportProcessorType.Simple;
78+
break;
79+
default:
80+
System.Console.WriteLine($"Export processor type {options.ProcessorType} is not supported. Default processor type 'batch' will be used.");
81+
break;
82+
}
6783
}
6884
else
6985
{
70-
System.Console.WriteLine($"Export processor type {options.ProcessorType} is not supported. Default processor type 'batch' will be used.");
86+
System.Console.WriteLine("Processor type is null or empty. Default processor type 'batch' will be used.");
7187
}
7288

7389
opt.AddOtlpExporter((exporterOptions, processorOptions) =>
@@ -103,6 +119,6 @@ internal static object Run(LogsOptions options)
103119
logger.LogInformation("Hello from {name} {price}.", "tomato", 2.99);
104120
}
105121

106-
return null;
122+
return 0;
107123
}
108124
}

0 commit comments

Comments
 (0)