Clean up warnings in examples (#1628)

* Refactor examples to streamline code structure and improve readability

* Update LangVersion to 13.0 for improved compatibility
This commit is contained in:
Boshi Lian
2025-04-29 16:55:55 -07:00
committed by GitHub
parent 001189de77
commit ae79be6665
17 changed files with 335 additions and 446 deletions

View File

@@ -26,7 +26,7 @@
<SymbolPackageFormat>snupkg</SymbolPackageFormat> <SymbolPackageFormat>snupkg</SymbolPackageFormat>
<EmbedUntrackedSources>true</EmbedUntrackedSources> <EmbedUntrackedSources>true</EmbedUntrackedSources>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<LangVersion>11.0</LangVersion> <LangVersion>13.0</LangVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'"> <PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">

View File

@@ -3,12 +3,6 @@ using k8s.Models;
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace attach
{
internal class Attach
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!"); Console.WriteLine("Starting Request!");
@@ -16,9 +10,8 @@ namespace attach
var list = client.CoreV1.ListNamespacedPod("default"); var list = client.CoreV1.ListNamespacedPod("default");
var pod = list.Items[0]; var pod = list.Items[0];
await AttachToPod(client, pod).ConfigureAwait(false); await AttachToPod(client, pod).ConfigureAwait(false);
}
private static async Task AttachToPod(IKubernetes client, V1Pod pod) async Task AttachToPod(IKubernetes client, V1Pod pod)
{ {
var webSocket = var webSocket =
await client.WebSocketNamespacedPodAttachAsync(pod.Metadata.Name, "default", await client.WebSocketNamespacedPodAttachAsync(pod.Metadata.Name, "default",
@@ -36,5 +29,3 @@ namespace attach
Console.WriteLine(str); Console.WriteLine(str);
} }
} }
}
}

View File

@@ -21,7 +21,7 @@ string GenerateCertificate(string name)
var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false)); request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, false)); request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new ("1.3.6.1.5.5.7.3.1")], false));
request.CertificateExtensions.Add(sanBuilder.Build()); request.CertificateExtensions.Add(sanBuilder.Build());
var csr = request.CreateSigningRequest(); var csr = request.CreateSigningRequest();
var pemKey = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + var pemKey = "-----BEGIN CERTIFICATE REQUEST-----\r\n" +

View File

@@ -3,12 +3,6 @@ using k8s.Models;
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace exec
{
internal class Exec
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!"); Console.WriteLine("Starting Request!");
@@ -16,9 +10,8 @@ namespace exec
var list = client.CoreV1.ListNamespacedPod("default"); var list = client.CoreV1.ListNamespacedPod("default");
var pod = list.Items[0]; var pod = list.Items[0];
await ExecInPod(client, pod).ConfigureAwait(false); await ExecInPod(client, pod).ConfigureAwait(false);
}
private static async Task ExecInPod(IKubernetes client, V1Pod pod) async Task ExecInPod(IKubernetes client, V1Pod pod)
{ {
var webSocket = var webSocket =
await client.WebSocketNamespacedPodExecAsync(pod.Metadata.Name, "default", "ls", await client.WebSocketNamespacedPodExecAsync(pod.Metadata.Name, "default", "ls",
@@ -33,5 +26,3 @@ namespace exec
var str = System.Text.Encoding.Default.GetString(buff); var str = System.Text.Encoding.Default.GetString(buff);
Console.WriteLine(str); Console.WriteLine(str);
} }
}
}

View File

@@ -1,14 +1,7 @@
using k8s; using k8s;
using k8s.Models; using k8s.Models;
using System; using System;
using System.Threading.Tasks;
namespace exec
{
internal class Generic
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
var generic = new GenericClient(client, "", "v1", "nodes"); var generic = new GenericClient(client, "", "v1", "nodes");
@@ -21,6 +14,3 @@ namespace exec
{ {
Console.WriteLine(pod.Metadata.Name); Console.WriteLine(pod.Metadata.Name);
} }
}
}
}

View File

@@ -2,12 +2,6 @@ using k8s;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace simple
{
internal class PodList
{
private static void Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!"); Console.WriteLine("Starting Request!");
@@ -43,6 +37,3 @@ namespace simple
Console.WriteLine(); Console.WriteLine();
} }
}
}
}

View File

@@ -1,13 +1,6 @@
using k8s; using k8s;
using System; using System;
using System.Threading.Tasks;
namespace logs
{
internal class Logs
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!"); Console.WriteLine("Starting Request!");
@@ -26,6 +19,3 @@ namespace logs
pod.Metadata.NamespaceProperty, container: pod.Spec.Containers[0].Name, follow: true).ConfigureAwait(false); pod.Metadata.NamespaceProperty, container: pod.Spec.Containers[0].Name, follow: true).ConfigureAwait(false);
var stream = response.Body; var stream = response.Body;
stream.CopyTo(Console.OpenStandardOutput()); stream.CopyTo(Console.OpenStandardOutput());
}
}
}

View File

@@ -3,11 +3,7 @@ using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace metrics async Task NodesMetrics(IKubernetes client)
{
internal class Program
{
private static async Task NodesMetrics(IKubernetes client)
{ {
var nodesMetrics = await client.GetKubernetesNodesMetricsAsync().ConfigureAwait(false); var nodesMetrics = await client.GetKubernetesNodesMetricsAsync().ConfigureAwait(false);
@@ -22,7 +18,7 @@ namespace metrics
} }
} }
private static async Task PodsMetrics(IKubernetes client) async Task PodsMetrics(IKubernetes client)
{ {
var podsMetrics = await client.GetKubernetesPodsMetricsAsync().ConfigureAwait(false); var podsMetrics = await client.GetKubernetesPodsMetricsAsync().ConfigureAwait(false);
@@ -47,14 +43,9 @@ namespace metrics
} }
} }
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
var client = new Kubernetes(config); var client = new Kubernetes(config);
await NodesMetrics(client).ConfigureAwait(false); await NodesMetrics(client).ConfigureAwait(false);
Console.WriteLine(Environment.NewLine); Console.WriteLine(Environment.NewLine);
await PodsMetrics(client).ConfigureAwait(false); await PodsMetrics(client).ConfigureAwait(false);
}
}
}

View File

@@ -4,11 +4,7 @@ using System;
using System.Net; using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace @namespace void ListNamespaces(IKubernetes client)
{
internal class NamespaceExample
{
private static void ListNamespaces(IKubernetes client)
{ {
var list = client.CoreV1.ListNamespace(); var list = client.CoreV1.ListNamespace();
foreach (var item in list.Items) foreach (var item in list.Items)
@@ -22,7 +18,7 @@ namespace @namespace
} }
} }
private static async Task DeleteAsync(IKubernetes client, string name, int delayMillis) async Task DeleteAsync(IKubernetes client, string name, int delayMillis)
{ {
while (true) while (true)
{ {
@@ -59,13 +55,11 @@ namespace @namespace
} }
} }
private static void Delete(IKubernetes client, string name, int delayMillis) void Delete(IKubernetes client, string name, int delayMillis)
{ {
DeleteAsync(client, name, delayMillis).Wait(); DeleteAsync(client, name, delayMillis).Wait();
} }
private static void Main(string[] args)
{
var k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(k8SClientConfig); IKubernetes client = new Kubernetes(k8SClientConfig);
@@ -93,6 +87,3 @@ namespace @namespace
} }
ListNamespaces(client); ListNamespaces(client);
}
}
}

View File

@@ -3,12 +3,6 @@ using k8s.Models;
using System; using System;
using System.Linq; using System.Linq;
namespace patch
{
internal class Program
{
private static void Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!"); Console.WriteLine("Starting Request!");
@@ -28,9 +22,8 @@ namespace patch
client.CoreV1.PatchNamespacedPod(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), name, "default"); client.CoreV1.PatchNamespacedPod(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), name, "default");
PrintLabels(client.CoreV1.ReadNamespacedPod(name, "default")); PrintLabels(client.CoreV1.ReadNamespacedPod(name, "default"));
}
private static void PrintLabels(V1Pod pod) void PrintLabels(V1Pod pod)
{ {
Console.WriteLine($"Labels: for {pod.Metadata.Name}"); Console.WriteLine($"Labels: for {pod.Metadata.Name}");
foreach (var (k, v) in pod.Metadata.Labels) foreach (var (k, v) in pod.Metadata.Labels)
@@ -40,5 +33,3 @@ namespace patch
Console.WriteLine("=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=");
} }
}
}

View File

@@ -6,12 +6,6 @@ using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace portforward
{
internal class Portforward
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting port forward!"); Console.WriteLine("Starting port forward!");
@@ -19,9 +13,8 @@ namespace portforward
var list = client.CoreV1.ListNamespacedPod("default"); var list = client.CoreV1.ListNamespacedPod("default");
var pod = list.Items[0]; var pod = list.Items[0];
await Forward(client, pod).ConfigureAwait(false); await Forward(client, pod).ConfigureAwait(false);
}
private static async Task Forward(IKubernetes client, V1Pod pod) async Task Forward(IKubernetes client, V1Pod pod)
{ {
// Note this is single-threaded, it won't handle concurrent requests well... // Note this is single-threaded, it won't handle concurrent requests well...
var webSocket = await client.WebSocketNamespacedPodPortForwardAsync(pod.Metadata.Name, "default", new int[] { 80 }, "v4.channel.k8s.io").ConfigureAwait(false); var webSocket = await client.WebSocketNamespacedPodPortForwardAsync(pod.Metadata.Name, "default", new int[] { 80 }, "v4.channel.k8s.io").ConfigureAwait(false);
@@ -76,5 +69,3 @@ namespace portforward
listener.Close(); listener.Close();
} }
}
}

View File

@@ -1,12 +1,6 @@
using k8s; using k8s;
using System; using System;
namespace simple
{
internal class PodList
{
private static void Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildDefaultConfig(); var config = KubernetesClientConfiguration.BuildDefaultConfig();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!"); Console.WriteLine("Starting Request!");
@@ -21,6 +15,3 @@ namespace simple
{ {
Console.WriteLine("Empty!"); Console.WriteLine("Empty!");
} }
}
}
}

View File

@@ -4,12 +4,6 @@ using System;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace watch
{
internal class Program
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config); IKubernetes client = new Kubernetes(config);
@@ -24,13 +18,9 @@ namespace watch
Console.WriteLine("==on watch event=="); Console.WriteLine("==on watch event==");
} }
// uncomment if you prefer callback api #pragma warning disable CS8321 // Remove unused private members
// WatchUsingCallback(client); void WatchUsingCallback(IKubernetes client)
} #pragma warning restore CS8321 // Remove unused private members
#pragma warning disable IDE0051 // Remove unused private members
private static void WatchUsingCallback(IKubernetes client)
#pragma warning restore IDE0051 // Remove unused private members
{ {
var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true); var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);
using (podlistResp.Watch<V1Pod, V1PodList>((type, item) => using (podlistResp.Watch<V1Pod, V1PodList>((type, item) =>
@@ -48,5 +38,3 @@ namespace watch
ctrlc.Wait(); ctrlc.Wait();
} }
} }
}
}

View File

@@ -10,22 +10,23 @@ namespace webApiDependencyInjection.Controllers
private readonly IKubernetes kubernetesClient; private readonly IKubernetes kubernetesClient;
/// <summary> /// <summary>
/// Inject the kubernets class in the constructor. /// Initializes a new instance of the <see cref="ExampleDependencyInjectionOnConstructorController"/> class.
/// Injects the Kubernetes client into the controller.
/// </summary> /// </summary>
/// <param name="kubernetesClient"></param> /// <param name="kubernetesClient">The Kubernetes client to interact with the Kubernetes API.</param>
public ExampleDependencyInjectionOnConstructorController(IKubernetes kubernetesClient) public ExampleDependencyInjectionOnConstructorController(IKubernetes kubernetesClient)
{ {
this.kubernetesClient = kubernetesClient; this.kubernetesClient = kubernetesClient;
} }
/// <summary> /// <summary>
/// Example using the kubernetes client obtained from the constructor (this.kubernetesClient). /// Retrieves the names of all pods in the default namespace using the injected Kubernetes client.
/// </summary> /// </summary>
/// <returns></returns> /// <returns>A collection of pod names in the default namespace.</returns>
[HttpGet()] [HttpGet]
public IEnumerable<string> GetPods() public IEnumerable<string> GetPods()
{ {
// Read the list of pods contained in default namespace // Read the list of pods contained in the default namespace
var podList = this.kubernetesClient.CoreV1.ListNamespacedPod("default"); var podList = this.kubernetesClient.CoreV1.ListNamespacedPod("default");
// Return names of pods // Return names of pods

View File

@@ -10,11 +10,13 @@ namespace webApiDependencyInjection.Controllers
/// <summary> /// <summary>
/// Example using the kubernetes client injected directly into the method ([FromServices] IKubernetes kubernetesClient). /// Example using the kubernetes client injected directly into the method ([FromServices] IKubernetes kubernetesClient).
/// </summary> /// </summary>
/// <param name="kubernetes"></param> /// <param name="kubernetesClient">The Kubernetes client instance injected via dependency injection.</param>
/// <returns></returns> /// <returns>A collection of pod names in the default namespace.</returns>
[HttpGet()] [HttpGet]
public IEnumerable<string> GetPods([FromServices] IKubernetes kubernetesClient) public IEnumerable<string> GetPods([FromServices] IKubernetes kubernetesClient)
{ {
ArgumentNullException.ThrowIfNull(kubernetesClient);
// Read the list of pods contained in default namespace // Read the list of pods contained in default namespace
var podList = kubernetesClient.CoreV1.ListNamespacedPod("default"); var podList = kubernetesClient.CoreV1.ListNamespacedPod("default");

View File

@@ -2,14 +2,7 @@ using k8s;
using k8s.Models; using k8s.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace yaml
{
internal class Program
{
private static async Task Main(string[] args)
{
var typeMap = new Dictionary<string, Type> var typeMap = new Dictionary<string, Type>
{ {
{ "v1/Pod", typeof(V1Pod) }, { "v1/Pod", typeof(V1Pod) },
@@ -23,6 +16,3 @@ namespace yaml
{ {
Console.WriteLine(obj); Console.WriteLine(obj);
} }
}
}
}