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>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<LangVersion>11.0</LangVersion>
<LangVersion>13.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">

View File

@@ -3,23 +3,16 @@ using k8s.Models;
using System;
using System.Threading.Tasks;
namespace attach
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var list = client.CoreV1.ListNamespacedPod("default");
var pod = list.Items[0];
await AttachToPod(client, pod).ConfigureAwait(false);
async Task AttachToPod(IKubernetes client, V1Pod pod)
{
internal class Attach
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var list = client.CoreV1.ListNamespacedPod("default");
var pod = list.Items[0];
await AttachToPod(client, pod).ConfigureAwait(false);
}
private static async Task AttachToPod(IKubernetes client, V1Pod pod)
{
var webSocket =
await client.WebSocketNamespacedPodAttachAsync(pod.Metadata.Name, "default",
pod.Spec.Containers[0].Name).ConfigureAwait(false);
@@ -35,6 +28,4 @@ namespace attach
var str = System.Text.Encoding.Default.GetString(buff);
Console.WriteLine(str);
}
}
}
}

View File

@@ -21,7 +21,7 @@ string GenerateCertificate(string name)
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 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());
var csr = request.CreateSigningRequest();
var pemKey = "-----BEGIN CERTIFICATE REQUEST-----\r\n" +
@@ -67,7 +67,7 @@ var old = JsonSerializer.SerializeToDocument(readCert, serializeOptions);
var replace = new List<V1CertificateSigningRequestCondition>
{
new("True", "Approved", DateTime.UtcNow, DateTime.UtcNow, "This certificate was approved by k8s client", "Approve"),
new ("True", "Approved", DateTime.UtcNow, DateTime.UtcNow, "This certificate was approved by k8s client", "Approve"),
};
readCert.Status.Conditions = replace;

View File

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

View File

@@ -1,26 +1,16 @@
using k8s;
using k8s.Models;
using System;
using System.Threading.Tasks;
namespace exec
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
var generic = new GenericClient(client, "", "v1", "nodes");
var node = await generic.ReadAsync<V1Node>("kube0").ConfigureAwait(false);
Console.WriteLine(node.Metadata.Name);
var genericPods = new GenericClient(client, "", "v1", "pods");
var pods = await genericPods.ListNamespacedAsync<V1PodList>("default").ConfigureAwait(false);
foreach (var pod in pods.Items)
{
internal class Generic
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
var generic = new GenericClient(client, "", "v1", "nodes");
var node = await generic.ReadAsync<V1Node>("kube0").ConfigureAwait(false);
Console.WriteLine(node.Metadata.Name);
var genericPods = new GenericClient(client, "", "v1", "pods");
var pods = await genericPods.ListNamespacedAsync<V1PodList>("default").ConfigureAwait(false);
foreach (var pod in pods.Items)
{
Console.WriteLine(pod.Metadata.Name);
}
}
}
}

View File

@@ -2,19 +2,13 @@ using k8s;
using System;
using System.Collections.Generic;
namespace simple
{
internal class PodList
{
private static void Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var list = client.CoreV1.ListNamespacedService("default");
foreach (var item in list.Items)
{
var list = client.CoreV1.ListNamespacedService("default");
foreach (var item in list.Items)
{
Console.WriteLine("Pods for service: " + item.Metadata.Name);
Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=");
if (item.Spec == null || item.Spec.Selector == null)
@@ -42,7 +36,4 @@ namespace simple
}
Console.WriteLine();
}
}
}
}

View File

@@ -1,31 +1,21 @@
using k8s;
using System;
using System.Threading.Tasks;
namespace logs
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var list = client.CoreV1.ListNamespacedPod("default");
if (list.Items.Count == 0)
{
internal class Logs
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var list = client.CoreV1.ListNamespacedPod("default");
if (list.Items.Count == 0)
{
Console.WriteLine("No pods!");
return;
}
}
var pod = list.Items[0];
var pod = list.Items[0];
var response = await client.CoreV1.ReadNamespacedPodLogWithHttpMessagesAsync(
var response = await client.CoreV1.ReadNamespacedPodLogWithHttpMessagesAsync(
pod.Metadata.Name,
pod.Metadata.NamespaceProperty, container: pod.Spec.Containers[0].Name, follow: true).ConfigureAwait(false);
var stream = response.Body;
stream.CopyTo(Console.OpenStandardOutput());
}
}
}
var stream = response.Body;
stream.CopyTo(Console.OpenStandardOutput());

View File

@@ -3,12 +3,8 @@ using System;
using System.Linq;
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);
foreach (var item in nodesMetrics.Items)
@@ -20,10 +16,10 @@ namespace metrics
Console.WriteLine($"{metric.Key}: {metric.Value}");
}
}
}
}
private static async Task PodsMetrics(IKubernetes client)
{
async Task PodsMetrics(IKubernetes client)
{
var podsMetrics = await client.GetKubernetesPodsMetricsAsync().ConfigureAwait(false);
if (!podsMetrics.Items.Any())
@@ -45,16 +41,11 @@ namespace metrics
Console.Write(Environment.NewLine);
}
}
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
var client = new Kubernetes(config);
await NodesMetrics(client).ConfigureAwait(false);
Console.WriteLine(Environment.NewLine);
await PodsMetrics(client).ConfigureAwait(false);
}
}
}
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
var client = new Kubernetes(config);
await NodesMetrics(client).ConfigureAwait(false);
Console.WriteLine(Environment.NewLine);
await PodsMetrics(client).ConfigureAwait(false);

View File

@@ -4,12 +4,8 @@ using System;
using System.Net;
using System.Threading.Tasks;
namespace @namespace
void ListNamespaces(IKubernetes client)
{
internal class NamespaceExample
{
private static void ListNamespaces(IKubernetes client)
{
var list = client.CoreV1.ListNamespace();
foreach (var item in list.Items)
{
@@ -20,10 +16,10 @@ namespace @namespace
{
Console.WriteLine("Empty!");
}
}
}
private static async Task DeleteAsync(IKubernetes client, string name, int delayMillis)
{
async Task DeleteAsync(IKubernetes client, string name, int delayMillis)
{
while (true)
{
await Task.Delay(delayMillis).ConfigureAwait(false);
@@ -57,42 +53,37 @@ namespace @namespace
throw;
}
}
}
}
private static void Delete(IKubernetes client, string name, int delayMillis)
{
void Delete(IKubernetes client, string name, int delayMillis)
{
DeleteAsync(client, name, delayMillis).Wait();
}
}
private static void Main(string[] args)
{
var k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(k8SClientConfig);
var k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(k8SClientConfig);
ListNamespaces(client);
ListNamespaces(client);
var ns = new V1Namespace { Metadata = new V1ObjectMeta { Name = "test" } };
var ns = new V1Namespace { Metadata = new V1ObjectMeta { Name = "test" } };
var result = client.CoreV1.CreateNamespace(ns);
Console.WriteLine(result);
var result = client.CoreV1.CreateNamespace(ns);
Console.WriteLine(result);
ListNamespaces(client);
ListNamespaces(client);
var status = client.CoreV1.DeleteNamespace(ns.Metadata.Name, new V1DeleteOptions());
var status = client.CoreV1.DeleteNamespace(ns.Metadata.Name, new V1DeleteOptions());
if (status.HasObject)
{
if (status.HasObject)
{
var obj = status.ObjectView<V1Namespace>();
Console.WriteLine(obj.Status.Phase);
Delete(client, ns.Metadata.Name, 3 * 1000);
}
else
{
Console.WriteLine(status.Message);
}
ListNamespaces(client);
}
}
}
else
{
Console.WriteLine(status.Message);
}
ListNamespaces(client);

View File

@@ -3,21 +3,15 @@ using k8s.Models;
using System;
using System.Linq;
namespace patch
{
internal class Program
{
private static void Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var pod = client.CoreV1.ListNamespacedPod("default").Items.First();
var name = pod.Metadata.Name;
PrintLabels(pod);
var pod = client.CoreV1.ListNamespacedPod("default").Items.First();
var name = pod.Metadata.Name;
PrintLabels(pod);
var patchStr = @"
var patchStr = @"
{
""metadata"": {
""labels"": {
@@ -26,12 +20,11 @@ namespace patch
}
}";
client.CoreV1.PatchNamespacedPod(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), name, "default");
PrintLabels(client.CoreV1.ReadNamespacedPod(name, "default"));
}
client.CoreV1.PatchNamespacedPod(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), 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}");
foreach (var (k, v) in pod.Metadata.Labels)
{
@@ -39,6 +32,4 @@ namespace patch
}
Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=");
}
}
}

View File

@@ -6,23 +6,16 @@ using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace portforward
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting port forward!");
var list = client.CoreV1.ListNamespacedPod("default");
var pod = list.Items[0];
await Forward(client, pod).ConfigureAwait(false);
async Task Forward(IKubernetes client, V1Pod pod)
{
internal class Portforward
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting port forward!");
var list = client.CoreV1.ListNamespacedPod("default");
var pod = list.Items[0];
await Forward(client, pod).ConfigureAwait(false);
}
private static async Task Forward(IKubernetes client, V1Pod pod)
{
// 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 demux = new StreamDemuxer(webSocket, StreamType.PortForward);
@@ -75,6 +68,4 @@ namespace portforward
}
listener.Close();
}
}
}

View File

@@ -1,26 +1,17 @@
using k8s;
using System;
namespace simple
var config = KubernetesClientConfiguration.BuildDefaultConfig();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var list = client.CoreV1.ListNamespacedPod("default");
foreach (var item in list.Items)
{
internal class PodList
{
private static void Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildDefaultConfig();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting Request!");
var list = client.CoreV1.ListNamespacedPod("default");
foreach (var item in list.Items)
{
Console.WriteLine(item.Metadata.Name);
}
if (list.Items.Count == 0)
{
Console.WriteLine("Empty!");
}
}
}
}
if (list.Items.Count == 0)
{
Console.WriteLine("Empty!");
}

View File

@@ -4,34 +4,24 @@ using System;
using System.Threading;
using System.Threading.Tasks;
namespace watch
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);
// C# 8 required https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8
await foreach (var (type, item) in podlistResp.WatchAsync<V1Pod, V1PodList>().ConfigureAwait(false))
{
internal class Program
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);
// C# 8 required https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8
await foreach (var (type, item) in podlistResp.WatchAsync<V1Pod, V1PodList>().ConfigureAwait(false))
{
Console.WriteLine("==on watch event==");
Console.WriteLine(type);
Console.WriteLine(item.Metadata.Name);
Console.WriteLine("==on watch event==");
}
}
// uncomment if you prefer callback api
// WatchUsingCallback(client);
}
#pragma warning disable IDE0051 // Remove unused private members
private static void WatchUsingCallback(IKubernetes client)
#pragma warning restore IDE0051 // Remove unused private members
{
#pragma warning disable CS8321 // Remove unused private members
void WatchUsingCallback(IKubernetes client)
#pragma warning restore CS8321 // Remove unused private members
{
var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);
using (podlistResp.Watch<V1Pod, V1PodList>((type, item) =>
{
@@ -47,6 +37,4 @@ namespace watch
Console.CancelKeyPress += (sender, eventArgs) => ctrlc.Set();
ctrlc.Wait();
}
}
}
}

View File

@@ -10,22 +10,23 @@ namespace webApiDependencyInjection.Controllers
private readonly IKubernetes kubernetesClient;
/// <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>
/// <param name="kubernetesClient"></param>
/// <param name="kubernetesClient">The Kubernetes client to interact with the Kubernetes API.</param>
public ExampleDependencyInjectionOnConstructorController(IKubernetes kubernetesClient)
{
this.kubernetesClient = kubernetesClient;
}
/// <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>
/// <returns></returns>
[HttpGet()]
/// <returns>A collection of pod names in the default namespace.</returns>
[HttpGet]
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");
// Return names of pods

View File

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

View File

@@ -2,27 +2,17 @@ using k8s;
using k8s.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace yaml
var typeMap = new Dictionary<string, Type>
{
internal class Program
{
private static async Task Main(string[] args)
{
var typeMap = new Dictionary<string, Type>
{
{ "v1/Pod", typeof(V1Pod) },
{ "v1/Service", typeof(V1Service) },
{ "apps/v1/Deployment", typeof(V1Deployment) },
};
};
var objects = await KubernetesYaml.LoadAllFromFileAsync(args[0], typeMap).ConfigureAwait(false);
var objects = await KubernetesYaml.LoadAllFromFileAsync(args[0], typeMap).ConfigureAwait(false);
foreach (var obj in objects)
{
foreach (var obj in objects)
{
Console.WriteLine(obj);
}
}
}
}