diff --git a/.editorconfig b/.editorconfig
index 4b5d3660e0..f75d0db029 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -10,6 +10,7 @@ insert_final_newline = true
# C# files
[*.cs]
+dotnet_diagnostic.IDE0055.severity = none
#### Core EditorConfig Options ####
@@ -123,7 +124,7 @@ csharp_style_expression_bodied_properties = when_on_single_line:silent
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
-csharp_style_prefer_pattern_matching = true:silent
+csharp_style_prefer_pattern_matching = true:none
csharp_style_prefer_switch_expression = false:suggestion
csharp_style_prefer_method_group_conversion = true:silent
@@ -158,7 +159,7 @@ csharp_style_prefer_index_operator = true:suggestion
csharp_style_prefer_range_operator = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_unused_value_assignment_preference = discard_variable:silent
-csharp_style_unused_value_expression_statement_preference = discard_variable:silent
+csharp_style_unused_value_expression_statement_preference = discard_variable:none
# 'using' directive preferences
csharp_using_directive_placement = inside_namespace:suggestion
@@ -467,7 +468,7 @@ dotnet_diagnostic.xUnit1044.severity = silent
# CA1716: Identifiers should not match keywords
dotnet_diagnostic.CA1716.severity = none
-csharp_style_prefer_primary_constructors = true:suggestion
+csharp_style_prefer_primary_constructors = false:suggestion
# CA1861: Avoid constant arrays as arguments
dotnet_diagnostic.CA1861.severity = silent
@@ -490,6 +491,13 @@ csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimenta
dotnet_diagnostic.RCS1055.severity = suggestion
dotnet_diagnostic.RCS1039.severity = suggestion
csharp_prefer_static_anonymous_function = true:suggestion
+csharp_prefer_system_threading_lock = true:suggestion
+
+# IDE0058: Expression value is never used
+dotnet_diagnostic.IDE0058.severity = none
+
+# IDE0078: Use pattern matching
+dotnet_diagnostic.IDE0078.severity = none
[*.{cs,vb}]
dotnet_style_coalesce_expression = true:silent
@@ -536,7 +544,7 @@ dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
-dotnet_style_namespace_match_folder = true:suggestion
+dotnet_style_namespace_match_folder = false:suggestion
dotnet_style_readonly_field = true:warning
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 53b6701db8..eb4f40f343 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -26,6 +26,10 @@ jobs:
- language: csharp
build-mode: autobuild
steps:
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v3
+ with:
+ dotnet-version: 9.0.x
- name: Checkout repository
uses: actions/checkout@v4
with:
diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
index ceab386b30..1e262fe988 100644
--- a/.github/workflows/dotnet.yml
+++ b/.github/workflows/dotnet.yml
@@ -19,7 +19,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
- dotnet-version: 8.0.x
+ dotnet-version: 9.0.x
- name: Restore dependencies
run: dotnet restore ${{ matrix.solution }}
- name: Build
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 508891e643..6180bfed74 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -17,7 +17,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
- dotnet-version: 8.0.x
+ dotnet-version: 9.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
diff --git a/common.props b/common.props
index 13c352e712..ebbe3fac0a 100644
--- a/common.props
+++ b/common.props
@@ -15,7 +15,7 @@
Industrial;Industrial IoT;Manufacturing;Azure;IoT;.NET
true
en-US
- 11.0
+ 13.0
false
disable
false
@@ -34,18 +34,20 @@
-
+
true
true
All
preview
+ default
+ false
-
-
+
+
diff --git a/deploy/kubernetes/cluster-setup.ps1 b/deploy/kubernetes/cluster-setup.ps1
new file mode 100644
index 0000000000..82748e01ce
--- /dev/null
+++ b/deploy/kubernetes/cluster-setup.ps1
@@ -0,0 +1,771 @@
+
+<#
+ .SYNOPSIS
+ Setup local AIO cluster and connect to Arc (must run as admin)
+ .DESCRIPTION
+ Setup local AIO cluster and connect to Arc. This script installs
+ the cluster type chosen and all other required dependencies and
+ connect it to the cloud via Arc. Then it will install AIO on it.
+ .NOTES
+ DO NOT USE FOR PRODUCTION SYSTEMS. This script is intended for
+ development and testing purposes only.
+
+ .PARAMETER Name
+ The name of the cluster
+ .PARAMETER SharedFolderPath
+ The shared folder path on the host system to mount into the guest.
+ .PARAMETER TenantId
+ The tenant id to use when logging into Azure.
+ .PARAMETER SubscriptionId
+ The subscription id to scope all activity to.
+ .PARAMETER Location
+ The location of the cluster.
+ .PARAMETER ClusterType
+ The type of cluster to create. Default is kind.
+ .PARAMETER Force
+ Force reinstall.
+#>
+
+param(
+ [string] [Parameter(Mandatory = $true)] $Name,
+ [string] $SharedFolderPath,
+ [string] $ResourceGroup,
+ [string] $TenantId,
+ [string] $SubscriptionId,
+ [string] $Location,
+ [string] [ValidateSet("kind", "minikube", "k3d")] $ClusterType = "k3d",
+ [switch] $Force
+)
+
+$forceReinstall = $Force.IsPresent
+$forceReinstall = $true
+$TenantId = "6e54c408-5edd-4f87-b3bb-360788b7ca18"
+
+#Requires -RunAsAdministrator
+
+$ErrorActionPreference = 'Stop'
+# $path = Split-Path $script:MyInvocation.MyCommand.Path
+
+if (! [Environment]::Is64BitProcess) {
+ Write-Host "Error: Run this in 64bit Powershell session" -ForegroundColor Red
+ exit -1
+}
+
+if ([string]::IsNullOrWhiteSpace($ResourceGroup)) {
+ $ResourceGroup = $Name
+}
+if ([string]::IsNullOrWhiteSpace($TenantId)) {
+ $TenantId = $env:AZURE_TENANT_ID
+}
+if ([string]::IsNullOrWhiteSpace($Location)) {
+ $Location = "eastus2"
+}
+
+$mountPath = "C:\Shared"
+if (![string]::IsNullOrWhiteSpace($SharedFolderPath)) {
+ $mountPath = $SharedFolderPath
+}
+
+Write-Host "Ensuring all required dependencies are installed..." -ForegroundColor Cyan
+[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+
+$errOut = $($docker = & {docker version --format json | ConvertFrom-Json}) 2>&1
+if ($LASTEXITCODE -ne 0 -or !$docker.Server) {
+ $docker | Out-Host
+ throw "Docker not installed or running : $errOut"
+}
+Write-Host "Found $($docker.Server.Platform.Name)..." -ForegroundColor Green
+$installAz = $false
+try {
+ $azVersion = (az version)[1].Split(":")[1].Split('"')[1]
+ if ($azVersion -lt "2.64.0" -or !$azVersion) {
+ $installAz = $true
+ }
+}
+catch {
+ $installAz = $true
+}
+
+# install az
+if ($installAz) {
+ Write-Host "Installing Az CLI..." -ForegroundColor Cyan
+
+ Set-ExecutionPolicy Bypass -Scope Process -Force
+ $ProgressPreference = 'SilentlyContinue'
+ Invoke-WebRequest -Uri https://aka.ms/installazurecliwindowsx64 -OutFile .\AzureCLI.msi
+ Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'
+ Remove-Item .\AzureCLI.msi
+}
+
+# install required az extensions
+az config set extension.dynamic_install_allow_preview=true 2>&1 | Out-Null
+$extensions =
+@(
+ "connectedk8s",
+ "azure-iot-ops",
+ "k8s-configuration"
+)
+foreach ($p in $extensions) {
+ $errOut = $($stdout = & {az extension add `
+ --upgrade `
+ --name $p `
+ --allow-preview true}) 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ $stdout | Out-Host
+ throw "Error installing az extension $p : $errOut"
+ }
+}
+if (![string]::IsNullOrWhiteSpace($SubscriptionId)) {
+ az account set --subscription $SubscriptionId 2>&1 | Out-Null
+}
+
+# install choco
+$errout = $($version = & {choco --version}) 2>&1
+if (!$version -or $errout) {
+ Write-Host "Installing Choco CLI..." -ForegroundColor Cyan
+ [System.Net.ServicePointManager]::SecurityProtocol = `
+ [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
+ $scriptLoc = 'https://community.chocolatey.org/install.ps1'
+ Invoke-Expression ((New-Object System.Net.WebClient).DownloadString($scriptLoc))
+}
+
+# install kind, helm and kubectl
+$packages =
+@(
+ "kubernetes-cli",
+ "kubernetes-helm",
+ "k9s"
+)
+if ($ClusterType -ne "none") {
+ $packages += $ClusterType
+}
+foreach($p in $packages) {
+ $errOut = $($stdout = & {choco install $p --yes}) 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ $stdout | Out-Host
+ throw "Error choco installing package $p : $errOut"
+ }
+}
+
+#
+# Log into azure
+#
+Write-Host "Log into Azure..." -ForegroundColor Cyan
+$loginparams = @()
+if (![string]::IsNullOrWhiteSpace($TenantId)) {
+ $loginparams += @("--tenant", $TenantId)
+}
+$session = (az login @loginparams) | ConvertFrom-Json
+if (-not $session) {
+ Write-Host "Error: Login failed." -ForegroundColor Red
+ exit -1
+}
+$SubscriptionId = $session.id
+$TenantId = $session.tenantId
+
+#
+# Create the cluster
+#
+$distro = "K8s"
+if ($ClusterType -eq "none") {
+ Write-Host "Skipping cluster creation..." -ForegroundColor Green
+}
+elseif ($ClusterType -eq "k3d") {
+ $distro = "K3s"
+ $errOut = $($table = & {k3d cluster list --no-headers} -split "`n") 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error querying k3d clusters - $errOut" -ForegroundColor Red
+ exit -1
+ }
+ $clusters = $table | ForEach-Object { $($_ -split " ")[0].Trim() }
+ if (($clusters -contains $Name) -and (!$forceReinstall)) {
+ Write-Host "Cluster $Name exists..." -ForegroundColor Green
+ }
+ else {
+ foreach ($cluster in $clusters) {
+ if (!$forceReinstall) {
+ if ($(Read-Host "Delete existing cluster $cluster? [Y/N]") -ne "Y") {
+ continue
+ }
+ }
+ Write-Host "Deleting existing cluster $cluster..." -ForegroundColor Yellow
+ k3d cluster delete $cluster 2>&1 | Out-Null
+ }
+ Write-Host "Creating k3d cluster $Name..." -ForegroundColor Cyan
+
+ $fullPath1 = Join-Path $mountPath "system"
+ if (!(Test-Path $fullPath1)) {
+ New-Item -ItemType Directory -Path $fullPath1 | Out-Null
+ }
+ $volumeMapping1 = "$($fullPath1):/var/lib/rancher/k3s/storage@all"
+ $fullPath2 = Join-Path $mountPath "user"
+ if (!(Test-Path $fullPath2)) {
+ New-Item -ItemType Directory -Path $fullPath2 | Out-Null
+ }
+ $volumeMapping2 = "$($fullPath2):/storage/user@all"
+ $env:K3D_FIX_MOUNTS=1
+ k3d cluster create $Name `
+ --agents 3 `
+ --servers 1 `
+ --volume $volumeMapping1 `
+ --volume $volumeMapping2 `
+ --env K3D_FIX_MOUNTS=1@all `
+ --wait
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error creating k3d cluster - $errOut" -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Cluster created..." -ForegroundColor Green
+ }
+}
+elseif ($ClusterType -eq "minikube") {
+ $errOut = $($clusters = & {minikube profile list -o json} | ConvertFrom-Json) 2>&1
+ if (($clusters.valid.Name -contains $Name) -and (!$forceReinstall)) {
+ Write-Host "Valid minikube cluster $Name exists..." -ForegroundColor Green
+ # Start the cluster
+ if ($stat.Host -Contains "Stopped" -or
+ $stat.APIServer -Contains "Stopped"-or
+ $stat.Kubelet -Contains "Stopped") {
+ Write-Host "Minikube cluster $Name stopped. Starting..." -ForegroundColor Cyan
+ minikube start -p $Name
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error starting minikube cluster." -ForegroundColor Red
+ minikube logs --file=$($Name).log
+ exit -1
+ }
+ Write-Host "Minikube cluster $Name started." -ForegroundColor Green
+ }
+ else {
+ Write-Host "Minikube cluster $Name running." -ForegroundColor Green
+ }
+ }
+ elseif ($LASTEXITCODE -ne 0) {
+ Write-Host "Error querying minikube clusters - $errOut" -ForegroundColor Red
+ exit -1
+ }
+ else {
+ if ($forceReinstall) {
+ Write-Host "Deleting other clusters..." -ForegroundColor Yellow
+ minikube delete --all --purge
+ }
+ elseif ($clusters.invalid.Name -contains $Name) {
+ Write-Host "Delete bad minikube cluster $Name..." -ForegroundColor Yellow
+ minikube delete -p $Name
+ }
+ Write-Host "Creating new minikube cluster $Name..." -ForegroundColor Cyan
+
+ if (Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All) {
+ Write-Host "Hyper-V is enabled..." -ForegroundColor Green
+ }
+ else {
+ Write-Host "Enabling Hyper-V..." -ForegroundColor Cyan
+ $hv = Enable-WindowsOptionalFeature -Online `
+ -FeatureName Microsoft-Hyper-V-All
+ if ($hv.RestartNeeded) {
+ Write-Host "Restarting..." -ForegroundColor Yellow
+ Restart-Computer -Force
+ }
+ }
+
+ if (Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Management-PowerShell) {
+ Write-Host "Hyper-V commands installed..." -ForegroundColor Green
+ }
+ else {
+ $hv = Enable-WindowsOptionalFeature -Online `
+ -FeatureName Microsoft-Hyper-V-Management-PowerShell
+ if ($hv.RestartNeeded) {
+ Write-Host "Restarting..." -ForegroundColor Yellow
+ Restart-Computer -Force
+ }
+ }
+
+ & {minikube start -p $Name --cpus=4 --memory=4096 --nodes=4 --driver=hyperv}
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error creating minikube cluster - $errOut" -ForegroundColor Red
+ minikube logs --file=$($Name).log
+ exit -1
+ }
+ Write-Host "Cluster created..." -ForegroundColor Green
+ }
+}
+elseif ($ClusterType -eq "kind") {
+ $errOut = $($clusters = & {kind get clusters} -split "`n") 2>&1
+ if (($clusters -contains $Name) -and (!$forceReinstall)) {
+ Write-Host "Cluster $Name exists..." -ForegroundColor Green
+ }
+ elseif ($LASTEXITCODE -ne 0) {
+ Write-Host "Error querying kind clusters - $errOut" -ForegroundColor Red
+ exit -1
+ }
+ else {
+ foreach ($cluster in $clusters) {
+ if (!$forceReinstall) {
+ if ($(Read-Host "Delete existing cluster $cluster? [Y/N]") -ne "Y") {
+ continue
+ }
+ }
+ Write-Host "Deleting existing cluster $cluster..." -ForegroundColor Yellow
+ kind delete cluster --name $cluster 2>&1 | Out-Null
+ }
+ Write-Host "Creating kind cluster $Name..." -ForegroundColor Cyan
+
+ $clusterConfig = @"
+kind: Cluster
+apiVersion: kind.x-k8s.io/v1alpha4
+nodes:
+- role: control-plane
+ extraPortMappings:
+ - containerPort: 80
+ hostPort: 80
+ listenAddress: "127.0.0.1"
+- role: worker
+- role: worker
+- role: worker
+- role: worker
+- role: worker
+"@
+ $clusterConfig -replace "`r`n", "`n" `
+ | kind create cluster --name $Name --config -
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error creating kind cluster - $errOut" -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Cluster created..." -ForegroundColor Green
+ }
+}
+else {
+ Write-Host "Error: Unsupported cluster type $ClusterType" -ForegroundColor Red
+ exit -1
+}
+
+$errOut = $($stdout = & {kubectl get nodes}) 2>&1
+if ($LASTEXITCODE -ne 0) {
+ $stdout | Out-Host
+ throw "Cluster not reachable : $errOut"
+}
+$stdout | Out-Host
+
+
+Write-Host "Registering the required resource providers..." -ForegroundColor Cyan
+$resourceProviders =
+@(
+ "Microsoft.ExtendedLocation",
+ "Microsoft.Kubernetes",
+ "Microsoft.KubernetesConfiguration",
+ "Microsoft.EventGrid",
+ "Microsoft.EventHub",
+ "Microsoft.KeyVault",
+ "Microsoft.Storage",
+ "Microsoft.IoTOperations",
+ "Microsoft.Kusto"
+)
+foreach ($rp in $resourceProviders) {
+ $errOut = $($obj = & {az provider show -n $rp `
+ --subscription $SubscriptionId | ConvertFrom-Json}) 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ throw "Error querying provider $rp : $errOut"
+ }
+ if ($obj.registrationState -eq "Registered") {
+ continue
+ }
+ $errOut = $($retVal = & {az provider register -n `
+ $rp --subscription $SubscriptionId}) 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ $retVal | Out-Host
+ throw "Error registering provider $rp : $errOut"
+ }
+ Write-Host "Resource provider $p registered." -ForegroundColor Green
+}
+
+$errOut = $($rg = & {az group show `
+ --name $srName `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+if ($rg -and $forceReinstall) {
+ Write-Host "Deleting existing resource group $Name..." `
+ -ForegroundColor Yellow
+ az group delete --name $Name --subscription $SubscriptionId `
+ --yes 2>&1 | Out-Null
+ $rg = $null
+}
+if (!$rg) {
+ Write-Host "Creating resource group $Name..." -ForegroundColor Cyan
+ $errOut = $($rg = & {az group create `
+ --name $Name `
+ --location $Location `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+ if ($LASTEXITCODE -ne 0 -or !$rg) {
+ Write-Host "Error creating resource group - $errOut." -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Resource group $($rg.id) created." -ForegroundColor Green
+}
+else {
+ Write-Host "Resource group $($rg.id) exists." -ForegroundColor Green
+}
+
+#
+# Create Azure resources
+#
+
+# Managed identity
+$errOut = $($mi = & {az identity show `
+ --name $Name `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+if (!$mi) {
+ Write-Host "Creating managed identity $Name..." -ForegroundColor Cyan
+ $errOut = $($mi = & {az identity create `
+ --name $Name `
+ --location $Location `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+ if ($LASTEXITCODE -ne 0 -or !$mi) {
+ Write-Host "Error creating managed identity - $errOut." -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Managed identity $($mi.id) created." -ForegroundColor Green
+}
+else {
+ Write-Host "Managed identity $($mi.id) exists." -ForegroundColor Green
+}
+
+# Storage account
+$storageAccountName = $Name.Replace("-", "")
+$errOut = $($stg = & {az storage account show `
+ --name $storageAccountName `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+if (!$stg) {
+ Write-Host "Creating Storage account $storageAccountName" -ForegroundColor Cyan
+ $errOut = $($stg = & {az storage account create `
+ --name $storageAccountName `
+ --location $Location `
+ --resource-group $ResourceGroup `
+ --allow-shared-key-access false `
+ --enable-hierarchical-namespace `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+ if ($LASTEXITCODE -ne 0 -or !$stg) {
+ Write-Host "Error creating storage $storageAccountName - $errOut." `
+ -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Storage account $($stg.id) created." -ForegroundColor Green
+}
+else {
+ Write-Host "Storage account $($stg.id) exists." -ForegroundColor Green
+}
+
+# Keyvault
+$keyVaultName = $Name + "kv"
+$errOut = $($kv = & {az keyvault show `
+ --name $keyVaultName `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+if (!$kv) {
+ Write-Host "Creating Key vault $keyVaultName" -ForegroundColor Cyan
+ az keyvault purge --name $keyVaultName --location $Location `
+ --subscription $SubscriptionId 2>&1 | Out-Null
+ $errOut = $($kv = & {az keyvault create `
+ --enable-rbac-authorization true `
+ --name $keyVaultName `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+ if ($LASTEXITCODE -ne 0 -or !$kv) {
+ Write-Host "Error creating Azure Keyvault - $errOut." `
+ -ForegroundColor Red
+ exit -1
+ }
+ if ($kv.properties.enableSoftDelete) {
+ az keyvault update `
+ --name $keyVaultName `
+ --enable-soft-delete false `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId 2>&1 | Out-Null
+ }
+ Write-Host "Key vault $($kv.id) created..." -ForegroundColor Green
+}
+else {
+ Write-Host "Key vault $($kv.id) exists." -ForegroundColor Green
+}
+
+# Azure IoT Operations schema registry
+$srName = "$($Name.ToLowerInvariant())sr"
+$errOut = $($sr = & {az iot ops schema registry show `
+ --name $srName `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+if (!$sr) {
+ Write-Host "Creating Azure IoT Operations schema registry..." -ForegroundColor Cyan
+ $errOut = $($sr = & {az iot ops schema registry create `
+ --name $srName `
+ --resource-group $ResourceGroup `
+ --registry-namespace $srName `
+ --location $Location `
+ --sa-resource-id $stg.id `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+ if ($LASTEXITCODE -ne 0 -or !$sr) {
+ Write-Host "Error creating Azure IoT Operations schema registry - $errOut." `
+ -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Azure IoT Operations schema registry $($sr.id) created." `
+ -ForegroundColor Green
+}
+else {
+ Write-Host "Azure IoT Operations schema registry $($sr.id) exists." `
+ -ForegroundColor Green
+}
+
+#
+# Assign roles to the managed identity
+#
+$roleassignments =
+@(
+ @("Contributor", $stg.id, $mi.principalId),
+ @("Storage Blob Data Owner", $stg.id, $mi.principalId),
+ @("Key Vault Administrator", $kv.id, $mi.principalId)
+)
+foreach ($ra in $roleassignments) {
+ Write-Host "Assigning $($ra[0]) role to $($ra[2])..." -ForegroundColor Cyan
+ $errOut = $($obj = & {az role assignment create `
+ --role $ra[0] `
+ --assignee-object-id $ra[2] `
+ --assignee-principal-type ServicePrincipal `
+ --scope $ra[1] | ConvertFrom-Json}) 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error assigning role $($ra[0]) to $($ra[2]) : $errOut" `
+ -ForegroundColor Red
+ #exit -1
+ }
+ Write-Host "Role $($ra[0]) assigned to $($ra[2])." -ForegroundColor Green
+}
+
+#
+# Connect the cluster to Arc
+#
+$errOut = $($cc = & {az connectedk8s show `
+ --name $Name `
+ --resource-group $Name `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+if (!$cc -or $forceReinstall) {
+ Write-Host "Connecting cluster to Arc in $($rg.Name)..." -ForegroundColor Cyan
+ $cc = az connectedk8s connect -n $Name -g $Name --subscription $SubscriptionId `
+ --correlation-id "d009f5dd-dba8-4ac7-bac9-b54ef3a6671a" 2>&1 | Out-Host
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error: connecting cluster to Arc failed." -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Cluster $Name connected to Arc." -ForegroundColor Green
+}
+else {
+ Write-Host "Cluster $($cc.name) already connected." -ForegroundColor Green
+}
+
+# enable custom location feature
+$errOut = $($objectId = & {az ad sp show `
+ --id bc313c14-388c-4e7d-a58e-70017303ee3b --query id -o tsv}) 2>&1
+az connectedk8s enable-features `
+ --name $Name `
+ --resource-group $Name `
+ --subscription $SubscriptionId `
+ --custom-locations-oid $objectId `
+ --features cluster-connect custom-locations
+if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error: Failed to enable custom location feature." -ForegroundColor Red
+ exit -1
+}
+
+$errOut = $($iotops = & {az iot ops show `
+ --resource-group $ResourceGroup `
+ --name $Name `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+if (!$iotops) {
+ Write-Host "Initializing cluster $Name for deployment of Azure IoT operations..." `
+ -ForegroundColor Cyan
+
+ az iot ops init `
+ --cluster $Name `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId `
+ --ensure-latest `
+ --enable-fault-tolerance false `
+ --only-show-errors
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error initializing cluster $Name for Azure IoT Operations." `
+ -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Cluster ready for Azure IoT Operations deployment..." `
+ -ForegroundColor Green
+ Write-Host "Creating the Azure IoT Operations instance..." -ForegroundColor Cyan
+ az iot ops create `
+ --cluster $Name `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId `
+ --name $Name `
+ --location $Location `
+ --sr-resource-id $sr.id `
+ --kubernetes-distro $distro `
+ --enable-rsync true `
+ --add-insecure-listener true `
+ --only-show-errors
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error creating Azure IoT Operations instance - $errOut." `
+ -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Azure IoT Operations instance $Name created." `
+ -ForegroundColor Green
+}
+else {
+ Write-Host "Upgrading Azure IoT Operations instance $($iotops.id)..." `
+ -ForegroundColor Cyan
+ az iot ops update `
+ --name $iotops.name `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Error upgrading Azure IoT Operations instance - $errOut." `
+ -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Azure IoT Operations $($iotops.id) upgraded..." `
+ -ForegroundColor Green
+}
+
+$errOut = $($mia = & {az iot ops identity show `
+ --name $iotops.name `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId} | ConvertFrom-Json) 2>&1
+if (!$mia) {
+ Write-Host "Assign managed identity $($mi.id) to instance $($iotops.id)..." `
+ -ForegroundColor Cyan
+ $errOut = $($mia = & {az iot ops identity assign `
+ --name $iotops.name `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId `
+ --mi-user-assigned $mi.id} | ConvertFrom-Json) 2>&1
+ if ($LASTEXITCODE -ne 0 -or !$mia) {
+ Write-Host "Error assigning managed identity to instance - $errOut." `
+ -ForegroundColor Red
+ exit -1
+ }
+ $mia | Out-Host
+ Write-Host "Managed identity $($mi.id) assigned to instance $($iotops.id)." `
+ -ForegroundColor Green
+}
+else {
+ Write-Host "Managed identity $($mi.id) already assigned to $($iotops.id)." `
+ -ForegroundColor Green
+}
+
+$errOut = $($ss = & {az iot ops secretsync show `
+ --name $iotops.name `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId } | ConvertFrom-Json) 2>&1
+if (!$ss) {
+ Write-Host "Enabling secret sync with $(kv.id) for instance $($iotops.id)..." `
+ -ForegroundColor Cyan
+ $errOut = $($ss = & {az iot ops secretsync enable `
+ --name $iotops.name `
+ --kv-resource-id $kv.id `
+ --resource-group $ResourceGroup `
+ --subscription $SubscriptionId `
+ --mi-user-assigned $mi.id} | ConvertFrom-Json) 2>&1
+ if ($LASTEXITCODE -ne 0 -or !$ss) {
+ Write-Host "Error enabling secret sync for instance - $errOut." `
+ -ForegroundColor Red
+ exit -1
+ }
+ Write-Host "Secret sync with $(kv.id) enabled for $($iotops.id)." `
+ -ForegroundColor Green
+}
+else {
+ Write-Host "Secret sync with $(kv.id) already enabled in $($iotops.id)." `
+ -ForegroundColor Green
+}
+
+exit 0
+
+Write-Host "Creating eventhub namespace $Name..." -ForegroundColor Cyan
+az eventhubs namespace create --name $Name --resource-group $ResourceGroup `
+ --location $Location `
+ --disable-local-auth true `
+ --subscription $SubscriptionId
+Write-Host "Creating eventhub $Name..." -ForegroundColor Cyan
+az eventhubs eventhub create --name $Name `
+ --resource-group $ResourceGroup `
+ --location $Location `
+ --namespace-name $Name `
+ --retention-time 1 `
+ --partition-count 1 `
+ --cleanup-policy Delete `
+ --enable-capture true `
+ --capture-interval 60 `
+ --destination-name EventHubArchive.AzureBlockBlob `
+ --storage-account $storageAccountName `
+ --blob-container "data" `
+ --subscription $SubscriptionId
+
+Write-Host "Creating data flow to event hub..." -ForegroundColor Cyan
+(Get-Content -Raw dataflow.yml) `
+ -replace "", "$Name" `
+ -replace "", "$Name" | Set-Content -NoNewLine dataflow-$Name.yml
+kubectl apply -f dataflow-$Name.yml --wait
+Remove-Item dataflow-$Name.yml
+
+$runtimeNamespace = "azure-iot-operations"
+$numberOfPlcs = 10
+$numberOfAssets = 90
+Write-Host "Creating $numberOfPlcs OPC PLCs..." -ForegroundColor Cyan
+helm upgrade -i aio-opc-plc ..\..\distrib\helm\microsoft-opc-plc\ `
+ --namespace $runtimeNamespace `
+ --set simulations=$numberOfPlcs `
+ --set deployDefaultIssuerCA=false `
+ --wait
+
+Write-Host "Creating asset endpoint profiles..." -ForegroundColor Cyan
+for ($i = 0; $i -lt $numberOfPlcs; $i++) {
+ az iot ops asset endpoint create -n aep-$i -g $ResourceGroup `
+ -c $Name --target-address "opc.tcp://opcplc-00000$($i%$numberOfPlcs):50000" `
+ --additional-config '{\"applicationName\": \"opcua-connector\", \"defaults\": { \"publishingIntervalMilliseconds\": 100, \"samplingIntervalMilliseconds\": 500, \"queueSize\": 15,}, \"session\": {\"timeout\": 60000}, \"subscription\": {\"maxItems\": 1000}, \"security\": { \"autoAcceptUntrustedServerCertificates\": true}}'
+}
+
+Write-Host "Creating assets..." -ForegroundColor Cyan
+# https://learn.microsoft.com/en-us/cli/azure/iot/ops/asset/data-point?view=azure-cli-latest#az-iot-ops-asset-data-point-add
+for ($i = 0; $i -lt $numberOfAssets; $i++) {
+ Write-Host "Creating asset asset-$i"
+ az iot ops asset create -n asset-$i -g $ResourceGroup `
+ --endpoint aep-$($i%$numberOfPlcs) -c $Name --data capability_id=FastUInt1 data_source="nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt1"
+ Write-Host "Importing data points..."
+ az iot ops asset data-point import --asset asset-$i `
+ --resource-group $ResourceGroup --input-file .\asset_dataPoints.json
+}
+
+Write-Host "Creating asset asset-with-events" -ForegroundColor Cyan
+az iot ops asset create -n asset-with-events -g $ResourceGroup `
+ --endpoint aep-0 -c $Name --event capability_id=Event1 event_notifier="ns=0; i=2253"
+
+helm repo add jetstack https://charts.jetstack.io --force-update
+helm repo update
+helm upgrade cert-manager jetstack/cert-manager --install `
+ --namespace cert-manager `
+ --create-namespace `
+ --set crds.enabled=true `
+ --wait
+helm repo add akri-helm-charts https://project-akri.github.io/akri/
+helm repo update
+helm upgrade --install akri akri-helm-charts/akri `
+ --namespace akri `
+ --create-namespace `
+ --wait
+helm upgrade --install aio-mq oci://mcr.microsoft.com/azureiotoperations/helm/aio-broker `
+ --version $mqVersion `
+ --namespace $mqNamespace `
+ --create-namespace `
+ --wait
+
+kubectl apply -f ..\..\distrib\helm\mq\broker-sat.yaml -n $mqNamespace
+$e4kMqttAddress = 'mqtt://aio-broker.' + $mqNamespace + ':1883'
+helm repo add prometheus-community https://prometheus-community.github.io/helm-charts/
+helm repo update
diff --git a/e2e-tests/IIoTPlatform-E2E-Tests/IIoTPlatform-E2E-Tests.csproj b/e2e-tests/IIoTPlatform-E2E-Tests/IIoTPlatform-E2E-Tests.csproj
index a168c92099..ff898af90a 100644
--- a/e2e-tests/IIoTPlatform-E2E-Tests/IIoTPlatform-E2E-Tests.csproj
+++ b/e2e-tests/IIoTPlatform-E2E-Tests/IIoTPlatform-E2E-Tests.csproj
@@ -1,6 +1,6 @@
- net8.0
+ net9.0
IIoTPlatformE2ETests
false
@@ -10,20 +10,20 @@
-
+
-
-
-
-
-
+
+
+
+
+
-
-
+
+
runtime; build; native; contentfiles; analyzers; buildtransitive
all
-
+
runtime; build; native; contentfiles; analyzers; buildtransitive
all
diff --git a/e2e-tests/OpcPublisher-E2E-Tests/OpcPublisher-AE-E2E-Tests.csproj b/e2e-tests/OpcPublisher-E2E-Tests/OpcPublisher-AE-E2E-Tests.csproj
index d8e11ff03c..e2ad6ce14a 100644
--- a/e2e-tests/OpcPublisher-E2E-Tests/OpcPublisher-AE-E2E-Tests.csproj
+++ b/e2e-tests/OpcPublisher-E2E-Tests/OpcPublisher-AE-E2E-Tests.csproj
@@ -1,6 +1,6 @@
- net8.0
+ net9.0
OpcPublisherAEE2ETests
false
@@ -10,27 +10,27 @@
-
+
-
-
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
+
+
runtime; build; native; contentfiles; analyzers; buildtransitive
all
-
+
runtime; build; native; contentfiles; analyzers; buildtransitive
all
diff --git a/e2e-tests/OpcPublisher-E2E-Tests/Standalone/DynamicAciTestBase.cs b/e2e-tests/OpcPublisher-E2E-Tests/Standalone/DynamicAciTestBase.cs
index 775603bf29..60b29f5aa5 100644
--- a/e2e-tests/OpcPublisher-E2E-Tests/Standalone/DynamicAciTestBase.cs
+++ b/e2e-tests/OpcPublisher-E2E-Tests/Standalone/DynamicAciTestBase.cs
@@ -54,7 +54,7 @@ protected DynamicAciTestBase(IIoTStandaloneTestContext context, ITestOutputHelpe
// Initialize DeviceServiceClient from IoT Hub connection string.
_iotHubClient = TestHelper.DeviceServiceClient(
_context.IoTHubConfig.IoTHubConnectionString,
- TransportType.Amqp_WebSocket_Only
+ Microsoft.Azure.Devices.TransportType.Amqp_WebSocket_Only
);
}
diff --git a/samples/Http/BrowseAll/BrowseAll.csproj b/samples/Http/BrowseAll/BrowseAll.csproj
index c3acc35148..1108806e86 100644
--- a/samples/Http/BrowseAll/BrowseAll.csproj
+++ b/samples/Http/BrowseAll/BrowseAll.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/Http/GetConfiguration/GetConfiguration.csproj b/samples/Http/GetConfiguration/GetConfiguration.csproj
index c3acc35148..1108806e86 100644
--- a/samples/Http/GetConfiguration/GetConfiguration.csproj
+++ b/samples/Http/GetConfiguration/GetConfiguration.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/Http/GetDiagnostics/GetDiagnostics.csproj b/samples/Http/GetDiagnostics/GetDiagnostics.csproj
index c3acc35148..1108806e86 100644
--- a/samples/Http/GetDiagnostics/GetDiagnostics.csproj
+++ b/samples/Http/GetDiagnostics/GetDiagnostics.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/Http/ReadCurrentTime/ReadCurrentTime.csproj b/samples/Http/ReadCurrentTime/ReadCurrentTime.csproj
index c3acc35148..1108806e86 100644
--- a/samples/Http/ReadCurrentTime/ReadCurrentTime.csproj
+++ b/samples/Http/ReadCurrentTime/ReadCurrentTime.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/Http/SetConfiguration/SetConfiguration.csproj b/samples/Http/SetConfiguration/SetConfiguration.csproj
index c3acc35148..1108806e86 100644
--- a/samples/Http/SetConfiguration/SetConfiguration.csproj
+++ b/samples/Http/SetConfiguration/SetConfiguration.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/Http/WriteReadbackValue/WriteReadbackValue.csproj b/samples/Http/WriteReadbackValue/WriteReadbackValue.csproj
index c3acc35148..1108806e86 100644
--- a/samples/Http/WriteReadbackValue/WriteReadbackValue.csproj
+++ b/samples/Http/WriteReadbackValue/WriteReadbackValue.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/IoTHub/ApproveRejected/ApproveRejected.csproj b/samples/IoTHub/ApproveRejected/ApproveRejected.csproj
index c3acc35148..1108806e86 100644
--- a/samples/IoTHub/ApproveRejected/ApproveRejected.csproj
+++ b/samples/IoTHub/ApproveRejected/ApproveRejected.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/IoTHub/BrowseCertificates/BrowseCertificates.csproj b/samples/IoTHub/BrowseCertificates/BrowseCertificates.csproj
index c3acc35148..1108806e86 100644
--- a/samples/IoTHub/BrowseCertificates/BrowseCertificates.csproj
+++ b/samples/IoTHub/BrowseCertificates/BrowseCertificates.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/IoTHub/GetCertificate/GetApplicationCert.csproj b/samples/IoTHub/GetCertificate/GetApplicationCert.csproj
index c3acc35148..1108806e86 100644
--- a/samples/IoTHub/GetCertificate/GetApplicationCert.csproj
+++ b/samples/IoTHub/GetCertificate/GetApplicationCert.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/IoTHub/GetConfiguration/GetConfiguration.csproj b/samples/IoTHub/GetConfiguration/GetConfiguration.csproj
index c3acc35148..1108806e86 100644
--- a/samples/IoTHub/GetConfiguration/GetConfiguration.csproj
+++ b/samples/IoTHub/GetConfiguration/GetConfiguration.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/IoTHub/ManageWriter/ManageWriter.csproj b/samples/IoTHub/ManageWriter/ManageWriter.csproj
index c3acc35148..1108806e86 100644
--- a/samples/IoTHub/ManageWriter/ManageWriter.csproj
+++ b/samples/IoTHub/ManageWriter/ManageWriter.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/IoTHub/MonitorMessages/MonitorMessages.cs b/samples/IoTHub/MonitorMessages/MonitorMessages.cs
index f4d8c38dfe..f8a372333b 100644
--- a/samples/IoTHub/MonitorMessages/MonitorMessages.cs
+++ b/samples/IoTHub/MonitorMessages/MonitorMessages.cs
@@ -64,7 +64,7 @@ static async Task ReceiveMessagesFromDeviceAsync(Parameters parameters, Cancella
//
// More information on the "EventProcessorClient" and its benefits can be found here:
// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventhub/Azure.Messaging.EventHubs.Processor/README.md
- await foreach (PartitionEvent partitionEvent in consumer.ReadEventsAsync(ct))
+ await foreach (PartitionEvent partitionEvent in consumer.ReadEventsAsync(ct).ConfigureAwait(false))
{
Console.WriteLine($"\nMessage received on partition {partitionEvent.Partition.PartitionId}:");
diff --git a/samples/IoTHub/MonitorMessages/MonitorMessages.csproj b/samples/IoTHub/MonitorMessages/MonitorMessages.csproj
index 959c07cdc1..2387a5ae50 100644
--- a/samples/IoTHub/MonitorMessages/MonitorMessages.csproj
+++ b/samples/IoTHub/MonitorMessages/MonitorMessages.csproj
@@ -1,13 +1,13 @@
Exe
- net8.0
+ net9.0
enable
enable
-
-
+
+
diff --git a/samples/IoTHub/ReadCurrentTime/ReadCurrentTime.csproj b/samples/IoTHub/ReadCurrentTime/ReadCurrentTime.csproj
index c3acc35148..1108806e86 100644
--- a/samples/IoTHub/ReadCurrentTime/ReadCurrentTime.csproj
+++ b/samples/IoTHub/ReadCurrentTime/ReadCurrentTime.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/IoTHub/ResetClients/GetAndResetConnections.csproj b/samples/IoTHub/ResetClients/GetAndResetConnections.csproj
index c3acc35148..1108806e86 100644
--- a/samples/IoTHub/ResetClients/GetAndResetConnections.csproj
+++ b/samples/IoTHub/ResetClients/GetAndResetConnections.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/IoTHub/WriteReadbackValue/WriteReadbackValue.csproj b/samples/IoTHub/WriteReadbackValue/WriteReadbackValue.csproj
index c3acc35148..1108806e86 100644
--- a/samples/IoTHub/WriteReadbackValue/WriteReadbackValue.csproj
+++ b/samples/IoTHub/WriteReadbackValue/WriteReadbackValue.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
@@ -9,7 +9,7 @@
-
+
diff --git a/samples/Mqtt/GetConfiguration/GetConfiguration.cs b/samples/Mqtt/GetConfiguration/GetConfiguration.cs
index 1791271b25..155f13000c 100644
--- a/samples/Mqtt/GetConfiguration/GetConfiguration.cs
+++ b/samples/Mqtt/GetConfiguration/GetConfiguration.cs
@@ -3,7 +3,6 @@
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
-using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Formatter;
using MQTTnet;
@@ -12,7 +11,7 @@
using System.Text;
// Connect to mqtt broker
-var mqttFactory = new MqttFactory();
+var mqttFactory = new MqttClientFactory();
using var mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithProtocolVersion(MqttProtocolVersion.V500) // Important!!
diff --git a/samples/Mqtt/GetConfiguration/GetConfiguration.csproj b/samples/Mqtt/GetConfiguration/GetConfiguration.csproj
index 5c783afee5..f678b2bdad 100644
--- a/samples/Mqtt/GetConfiguration/GetConfiguration.csproj
+++ b/samples/Mqtt/GetConfiguration/GetConfiguration.csproj
@@ -1,11 +1,11 @@
Exe
- net8.0
+ net9.0
enable
enable
-
+
diff --git a/samples/Mqtt/ManageWriter/ManageWriter.cs b/samples/Mqtt/ManageWriter/ManageWriter.cs
index 4a6e76c7a3..4146919853 100644
--- a/samples/Mqtt/ManageWriter/ManageWriter.cs
+++ b/samples/Mqtt/ManageWriter/ManageWriter.cs
@@ -3,7 +3,6 @@
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
-using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Formatter;
using MQTTnet;
@@ -12,7 +11,7 @@
using System.Text;
// Connect to mqtt broker
-var mqttFactory = new MqttFactory();
+var mqttFactory = new MqttClientFactory();
using var mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithProtocolVersion(MqttProtocolVersion.V500) // Important!!
diff --git a/samples/Mqtt/ManageWriter/ManageWriter.csproj b/samples/Mqtt/ManageWriter/ManageWriter.csproj
index 5c783afee5..f678b2bdad 100644
--- a/samples/Mqtt/ManageWriter/ManageWriter.csproj
+++ b/samples/Mqtt/ManageWriter/ManageWriter.csproj
@@ -1,11 +1,11 @@
Exe
- net8.0
+ net9.0
enable
enable
-
+
diff --git a/samples/Mqtt/MonitorMessages/MonitorMessages.cs b/samples/Mqtt/MonitorMessages/MonitorMessages.cs
index 15d6abc6bb..b80515b98d 100644
--- a/samples/Mqtt/MonitorMessages/MonitorMessages.cs
+++ b/samples/Mqtt/MonitorMessages/MonitorMessages.cs
@@ -3,13 +3,13 @@
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
-using MQTTnet.Client;
using MQTTnet.Formatter;
using MQTTnet;
using System.Text.Json;
+using System.Buffers;
// Connect to mqtt broker
-var mqttFactory = new MqttFactory();
+var mqttFactory = new MqttClientFactory();
using var mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithProtocolVersion(MqttProtocolVersion.V500) // Important!!
@@ -19,8 +19,8 @@
var indented = new JsonSerializerOptions() { WriteIndented = true };
mqttClient.ApplicationMessageReceivedAsync += args =>
{
- var json = JsonSerializer.Serialize(JsonSerializer.Deserialize(
- args.ApplicationMessage.PayloadSegment), indented);
+ var reader = new Utf8JsonReader(args.ApplicationMessage.Payload);
+ var json = JsonSerializer.Serialize(JsonSerializer.Deserialize(ref reader), indented);
Console.WriteLine($"{args.ApplicationMessage.Topic}:{json}");
return Task.CompletedTask;
};
diff --git a/samples/Mqtt/MonitorMessages/MonitorMessages.csproj b/samples/Mqtt/MonitorMessages/MonitorMessages.csproj
index 5c783afee5..f678b2bdad 100644
--- a/samples/Mqtt/MonitorMessages/MonitorMessages.csproj
+++ b/samples/Mqtt/MonitorMessages/MonitorMessages.csproj
@@ -1,11 +1,11 @@
Exe
- net8.0
+ net9.0
enable
enable
-
+
diff --git a/samples/Mqtt/ReadAttributes/ReadAttributes.cs b/samples/Mqtt/ReadAttributes/ReadAttributes.cs
index cc28a9d679..e5dbd2e672 100644
--- a/samples/Mqtt/ReadAttributes/ReadAttributes.cs
+++ b/samples/Mqtt/ReadAttributes/ReadAttributes.cs
@@ -3,7 +3,6 @@
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
-using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Formatter;
using MQTTnet;
@@ -12,7 +11,7 @@
using System.Text;
// Connect to mqtt broker
-var mqttFactory = new MqttFactory();
+var mqttFactory = new MqttClientFactory();
using var mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithProtocolVersion(MqttProtocolVersion.V500) // Important!!
diff --git a/samples/Mqtt/ReadAttributes/ReadAttributes.csproj b/samples/Mqtt/ReadAttributes/ReadAttributes.csproj
index 5c783afee5..f678b2bdad 100644
--- a/samples/Mqtt/ReadAttributes/ReadAttributes.csproj
+++ b/samples/Mqtt/ReadAttributes/ReadAttributes.csproj
@@ -1,11 +1,11 @@
Exe
- net8.0
+ net9.0
enable
enable
-
+
diff --git a/samples/Mqtt/ReadCurrentTime/ReadCurrentTime.cs b/samples/Mqtt/ReadCurrentTime/ReadCurrentTime.cs
index 2436a1190b..582627998e 100644
--- a/samples/Mqtt/ReadCurrentTime/ReadCurrentTime.cs
+++ b/samples/Mqtt/ReadCurrentTime/ReadCurrentTime.cs
@@ -3,7 +3,6 @@
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
-using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Formatter;
using MQTTnet;
@@ -11,7 +10,7 @@
using System.Text.Json;
// Connect to mqtt broker
-var mqttFactory = new MqttFactory();
+var mqttFactory = new MqttClientFactory();
using var mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithProtocolVersion(MqttProtocolVersion.V500) // Important!!
diff --git a/samples/Mqtt/ReadCurrentTime/ReadCurrentTime.csproj b/samples/Mqtt/ReadCurrentTime/ReadCurrentTime.csproj
index 5c783afee5..f678b2bdad 100644
--- a/samples/Mqtt/ReadCurrentTime/ReadCurrentTime.csproj
+++ b/samples/Mqtt/ReadCurrentTime/ReadCurrentTime.csproj
@@ -1,11 +1,11 @@
Exe
- net8.0
+ net9.0
enable
enable
-
+
diff --git a/samples/Mqtt/WriteReadbackValue/WriteReadbackValue.cs b/samples/Mqtt/WriteReadbackValue/WriteReadbackValue.cs
index de11b31a9b..c4ba8c8ba1 100644
--- a/samples/Mqtt/WriteReadbackValue/WriteReadbackValue.cs
+++ b/samples/Mqtt/WriteReadbackValue/WriteReadbackValue.cs
@@ -3,7 +3,6 @@
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
-using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Formatter;
using MQTTnet;
@@ -11,7 +10,7 @@
using System.Text.Json;
// Connect to mqtt broker
-var mqttFactory = new MqttFactory();
+var mqttFactory = new MqttClientFactory();
using var mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithProtocolVersion(MqttProtocolVersion.V500) // Important!!
diff --git a/samples/Mqtt/WriteReadbackValue/WriteReadbackValue.csproj b/samples/Mqtt/WriteReadbackValue/WriteReadbackValue.csproj
index 5c783afee5..f678b2bdad 100644
--- a/samples/Mqtt/WriteReadbackValue/WriteReadbackValue.csproj
+++ b/samples/Mqtt/WriteReadbackValue/WriteReadbackValue.csproj
@@ -1,11 +1,11 @@
Exe
- net8.0
+ net9.0
enable
enable
-
+
diff --git a/samples/Netcap/src/Extensions.cs b/samples/Netcap/src/Extensions.cs
index 9d10525523..9558d515a7 100644
--- a/samples/Netcap/src/Extensions.cs
+++ b/samples/Netcap/src/Extensions.cs
@@ -9,7 +9,6 @@ namespace Netcap;
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
-using System.Security.Cryptography;
using System.Text.Json;
using System.Text.RegularExpressions;
@@ -100,7 +99,7 @@ public static string FixUpResourceName(string name)
name = AlphaNumOnly().Replace(name, "");
if (name.Length > 24)
{
- name = name.Substring(0, 24);
+ name = name[..24];
}
return name;
}
@@ -165,7 +164,7 @@ public static string FixUpStorageName(string name)
}
else if (containerName.Length > 63)
{
- containerName = containerName.Substring(0, 63);
+ containerName = containerName[..63];
}
#pragma warning disable CA1308 // Normalize strings to uppercase
return containerName.ToLowerInvariant();
@@ -183,7 +182,7 @@ public static async Task CopyAsync(this Stream source, Stream destination,
CancellationToken ct = default)
{
var copied = 0;
- byte[] buffer = ArrayPool.Shared.Rent(8 * 1024);
+ var buffer = ArrayPool.Shared.Rent(8 * 1024);
try
{
while (!ct.IsCancellationRequested)
diff --git a/samples/Netcap/src/Gateway.cs b/samples/Netcap/src/Gateway.cs
index 1ad469469f..332352fb6d 100644
--- a/samples/Netcap/src/Gateway.cs
+++ b/samples/Netcap/src/Gateway.cs
@@ -106,7 +106,7 @@ await Task.Delay(TimeSpan.FromSeconds(5),
{
Console.WriteLine($"{index + 1}: {deployments[index]}");
}
- var i = 0;
+ int i;
Console.WriteLine("Select publisher index: ");
while (true)
{
@@ -378,14 +378,14 @@ private async IAsyncEnumerable GetPublisherDeploymentsAsync
[EnumeratorCancellation] CancellationToken ct = default)
{
_logger.LogInformation("Finding publishers...");
- await foreach (var sub in _client.GetSubscriptions().GetAllAsync(ct))
+ await foreach (var sub in _client.GetSubscriptions().GetAllAsync(ct).ConfigureAwait(false))
{
if (subscriptionId != null && sub.Data.DisplayName != subscriptionId
&& sub.Id.SubscriptionId != subscriptionId)
{
continue;
}
- await foreach (var hub in sub.GetIotHubDescriptionsAsync(cancellationToken: ct))
+ await foreach (var hub in sub.GetIotHubDescriptionsAsync(cancellationToken: ct).ConfigureAwait(false))
{
Response keys;
try
diff --git a/samples/Netcap/src/Netcap.cs b/samples/Netcap/src/Netcap.cs
index 35844ca62f..b3920e2506 100644
--- a/samples/Netcap/src/Netcap.cs
+++ b/samples/Netcap/src/Netcap.cs
@@ -16,7 +16,6 @@ namespace Netcap;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
-using Microsoft.Win32;
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
@@ -155,9 +154,7 @@ public void ConfigureFromTwin(Twin twin)
}
[Verb("sidecar", HelpText = "Run netcap as capture host.")]
- public sealed class SidecarOptions
- {
- }
+ public sealed class SidecarOptions;
[Verb("install", HelpText = "Install netcap into a publisher.")]
public sealed class InstallOptions
@@ -495,7 +492,7 @@ await moduleClient.UpdateReportedPropertiesAsync(new TwinCollection
var twin = await moduleClient.GetTwinAsync(ct).ConfigureAwait(false);
var deviceId = twin.DeviceId ?? Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
- var moduleId = twin.ModuleId ?? Environment.GetEnvironmentVariable("IOTEDGE_MODULEID");
+ // var moduleId = twin.ModuleId ?? Environment.GetEnvironmentVariable("IOTEDGE_MODULEID");
_run.PublisherModuleId = twin.GetProperty(nameof(_run.PublisherModuleId),
_run.PublisherModuleId);
_run.PublisherDeviceId = deviceId; // Override as we must be in the same device
@@ -561,7 +558,7 @@ await moduleClient.UpdateReportedPropertiesAsync(new TwinCollection
var apiKey = twin.GetProperty("__apikey__", desired: false);
if (cert != null && apiKey != null)
{
- _sidecarCertificate = new X509Certificate2(
+ _sidecarCertificate = X509CertificateLoader.LoadPkcs12(
Convert.FromBase64String(cert.Trim()), apiKey);
}
else
@@ -761,10 +758,8 @@ private void CreateSidecarHttpClientIfRequired()
return;
}
- var cert = Convert.FromBase64String(
- _run.HostCaptureCertificate.Trim());
- _sidecarCertificate = new X509Certificate2(
- cert!, _run.HostCaptureApiKey);
+ var cert = Convert.FromBase64String(_run.HostCaptureCertificate.Trim());
+ _sidecarCertificate = X509CertificateLoader.LoadPkcs12(cert, _run.HostCaptureApiKey);
_sidecarHttpClient?.Dispose();
#pragma warning disable CA2000 // Dispose objects before losing scope
@@ -781,9 +776,11 @@ private void CreateSidecarHttpClientIfRequired()
}
return true;
}
- });
+ })
+ {
+ BaseAddress = new Uri(_run.HostCaptureEndpointUrl)
+ };
#pragma warning restore CA2000 // Dispose objects before losing scope
- _sidecarHttpClient.BaseAddress = new Uri(_run.HostCaptureEndpointUrl);
_sidecarHttpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("ApiKey", _run?.HostCaptureApiKey);
}
@@ -809,7 +806,7 @@ private async ValueTask CreatePublisherHttpClientAsync()
{
var cert = Convert.FromBase64String(
_run.PublisherRestCertificate.Trim());
- _publisherCertificate = new X509Certificate2(
+ _publisherCertificate = X509CertificateLoader.LoadPkcs12(
cert!, _run.PublisherRestApiKey);
}
}
@@ -829,10 +826,12 @@ private async ValueTask CreatePublisherHttpClientAsync()
}
return true;
}
- });
+ })
+ {
#pragma warning restore CA2000 // Dispose objects before losing scope
- _publisherHttpClient.BaseAddress =
- await GetOpcPublisherRestEndpoint().ConfigureAwait(false);
+ BaseAddress =
+ await GetOpcPublisherRestEndpoint().ConfigureAwait(false)
+ };
_publisherHttpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("ApiKey", _run?.PublisherRestApiKey);
}
@@ -856,7 +855,9 @@ async ValueTask GetOpcPublisherRestEndpoint()
{
var result = await Dns.GetHostEntryAsync(host).ConfigureAwait(false);
if (result.AddressList.Length == 0)
+ {
host = null;
+ }
}
catch { host = null; }
}
@@ -892,7 +893,7 @@ private ILogger UpdateLogger()
/// Create module client
///
///
- private async static ValueTask CreateModuleClientAsync()
+ private static async ValueTask CreateModuleClientAsync()
{
var edgeHubConnectionString = Environment.GetEnvironmentVariable("EdgeHubConnectionString");
if (!string.IsNullOrWhiteSpace(edgeHubConnectionString))
@@ -913,27 +914,21 @@ public sealed record class ApiKeyProvider(string ApiKey);
///
/// Api key authentication handler
///
- internal sealed class ApiKeyHandler : AuthenticationHandler
+ ///
+ /// Create authentication handler
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ internal sealed class ApiKeyHandler(IOptionsMonitor options,
+ ILoggerFactory logger, UrlEncoder encoder, IHttpContextAccessor context,
+ App.ApiKeyProvider apiKeyProvider) :
+ AuthenticationHandler(options, logger, encoder)
{
public const string SchemeName = "ApiKey";
- ///
- /// Create authentication handler
- ///
- ///
- ///
- ///
- ///
- ///
- public ApiKeyHandler(IOptionsMonitor options,
- ILoggerFactory logger, UrlEncoder encoder, IHttpContextAccessor context,
- ApiKeyProvider apiKeyProvider) :
- base(options, logger, encoder)
- {
- _context = context;
- _apiKeyProvider = apiKeyProvider;
- }
-
///
protected override Task HandleAuthenticateAsync()
{
@@ -979,8 +974,8 @@ protected override Task HandleAuthenticateAsync()
}
}
- private readonly IHttpContextAccessor _context;
- private readonly ApiKeyProvider _apiKeyProvider;
+ private readonly IHttpContextAccessor _context = context;
+ private readonly ApiKeyProvider _apiKeyProvider = apiKeyProvider;
}
private static TokenCredential GetAzureCredentials(string? tenantId,
diff --git a/samples/Netcap/src/Netcap.csproj b/samples/Netcap/src/Netcap.csproj
index 0ad8f4f9a7..e762e169aa 100644
--- a/samples/Netcap/src/Netcap.csproj
+++ b/samples/Netcap/src/Netcap.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
enable
enable
true
@@ -18,18 +18,18 @@
-
-
+
+
-
+
-
+
-
+
-
+
\ No newline at end of file
diff --git a/samples/Netcap/src/Pcap.cs b/samples/Netcap/src/Pcap.cs
index 2981582adf..2e1dcd550f 100644
--- a/samples/Netcap/src/Pcap.cs
+++ b/samples/Netcap/src/Pcap.cs
@@ -15,10 +15,6 @@ namespace Netcap;
using System;
using System.Threading.Channels;
using System.Collections.Concurrent;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Collections;
-using System.Text.RegularExpressions;
internal abstract class Pcap
{
@@ -86,7 +82,7 @@ public static void Merge(string folder, string outputFile)
LinkLayerType = reader.LinkType
});
}
- while ((reader.GetNextPacket(out var packet))
+ while (reader.GetNextPacket(out var packet)
== GetPacketStatus.PacketRead)
{
writer.Write(packet.GetPacket());
@@ -145,7 +141,7 @@ protected Base(ILogger logger, CaptureConfiguration configuration)
throw new NetcapException("Cannot run capture without devices.");
}
- _devices = LibPcapLiveDeviceList.New().ToList();
+ _devices = [.. LibPcapLiveDeviceList.New()];
// Open devices
var open = _devices
@@ -253,7 +249,7 @@ LibPcapLiveDevice[] Capture(IEnumerable candidates)
device.Name, device.Description, ex.Message);
}
}
- return capturing.ToArray();
+ return [.. capturing];
}
}
@@ -384,8 +380,8 @@ private CaptureFileWriterDevice CreateWriter(int index)
private static int _handles;
private int _index;
private long _captureCount;
- private readonly Stopwatch _captureWatch = new Stopwatch();
- private readonly object _lock = new();
+ private readonly Stopwatch _captureWatch = new ();
+ private readonly Lock _lock = new();
private readonly CaptureConfiguration _configuration;
private List? _devices;
private CaptureFileWriterDevice _writer;
@@ -443,7 +439,7 @@ protected override void Dispose(bool disposing)
///
private async Task RunAsync(CancellationToken ct = default)
{
- await foreach (var index in Reader.ReadAllAsync(ct))
+ await foreach (var index in Reader.ReadAllAsync(ct).ConfigureAwait(false))
{
var file = GetFilePath(_folder, index);
await _storage.UploadAsync(file, ct).ConfigureAwait(false);
@@ -529,7 +525,7 @@ private async Task RunAsync(CancellationToken ct)
try
{
await foreach (var index in _client
- .GetFromJsonAsAsyncEnumerable(new Uri($"/{_handle}"), ct))
+ .GetFromJsonAsAsyncEnumerable(new Uri($"/{_handle}"), ct).ConfigureAwait(false))
{
var s = await _client.GetStreamAsync(new Uri($"/{_handle}/{index}"),
ct).ConfigureAwait(false);
@@ -677,13 +673,11 @@ internal void Stop(int handle)
///
/// Remote capture
///
- private sealed class CaptureAdapter : Base
+ ///
+ ///
+ private sealed class CaptureAdapter(ILogger logger,
+ Pcap.CaptureConfiguration configuration) : Base(logger, configuration)
{
- public CaptureAdapter(ILogger logger, CaptureConfiguration configuration) :
- base(logger, configuration)
- {
- }
-
///
/// Download
///
@@ -705,7 +699,9 @@ public IResult Download(int index)
///
///
public IAsyncEnumerable ReadAllAsync(CancellationToken ct = default)
- => Reader.ReadAllAsync(ct);
+ {
+ return Reader.ReadAllAsync(ct);
+ }
}
private readonly ConcurrentDictionary _captures = new();
diff --git a/samples/Netcap/src/Publisher.cs b/samples/Netcap/src/Publisher.cs
index 289e1d9f3f..74da3cb9e0 100644
--- a/samples/Netcap/src/Publisher.cs
+++ b/samples/Netcap/src/Publisher.cs
@@ -9,7 +9,6 @@ namespace Netcap;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
-using System.Runtime.CompilerServices;
using System.Text.Json;
///
@@ -20,12 +19,12 @@ internal sealed class Publisher : IDisposable
///
/// Endpoint urls
///
- public HashSet Endpoints { get; } = new();
+ public HashSet Endpoints { get; } = [];
///
/// Addresses of the publisher on the network
///
- public HashSet Addresses { get; } = new();
+ public HashSet Addresses { get; } = [];
///
/// Create publisher
@@ -191,7 +190,7 @@ private async Task UploadSessionKeysFromDiagnosticsAsync(Storage storage,
if (diagnostic.TryGetProperty("connection", out var conn) &&
conn.TryGetProperty("endpoint", out var ep) &&
- ep.TryGetProperty("url", out var url) &&
+ ep.TryGetProperty("url", out _) &&
diagnostic.TryGetProperty("sessionCreated", out var sessionCreatedToken) &&
sessionCreatedToken.TryGetDateTimeOffset(out var sessionCreated) &&
diagnostic.TryGetProperty("sessionId", out var sessionId) &&
@@ -243,23 +242,21 @@ static async ValueTask AddSessionKeysAsync(string fileName, uint channelId,
CancellationToken ct = default)
{
var keysets = File.AppendText(fileName);
- await using (var _ = keysets.ConfigureAwait(false))
- {
- await keysets.WriteLineAsync(
- $"client_iv_{channelId}_{tokenId}: {Convert.ToHexString(clientIv)}").ConfigureAwait(false);
- await keysets.WriteLineAsync(
- $"client_key_{channelId}_{tokenId}: {Convert.ToHexString(clientKey)}").ConfigureAwait(false);
- await keysets.WriteLineAsync(
- $"client_siglen_{channelId}_{tokenId}: {clientSigLen}").ConfigureAwait(false);
- await keysets.WriteLineAsync(
- $"server_iv_{channelId}_{tokenId}: {Convert.ToHexString(serverIv)}").ConfigureAwait(false);
- await keysets.WriteLineAsync(
- $"server_key_{channelId}_{tokenId}: {Convert.ToHexString(serverKey)}").ConfigureAwait(false);
- await keysets.WriteLineAsync(
- $"server_siglen_{channelId}_{tokenId}: {serverSigLen}").ConfigureAwait(false);
+ await using var _ = keysets.ConfigureAwait(false);
+ await keysets.WriteLineAsync(
+$"client_iv_{channelId}_{tokenId}: {Convert.ToHexString(clientIv)}").ConfigureAwait(false);
+ await keysets.WriteLineAsync(
+$"client_key_{channelId}_{tokenId}: {Convert.ToHexString(clientKey)}").ConfigureAwait(false);
+ await keysets.WriteLineAsync(
+$"client_siglen_{channelId}_{tokenId}: {clientSigLen}").ConfigureAwait(false);
+ await keysets.WriteLineAsync(
+$"server_iv_{channelId}_{tokenId}: {Convert.ToHexString(serverIv)}").ConfigureAwait(false);
+ await keysets.WriteLineAsync(
+$"server_key_{channelId}_{tokenId}: {Convert.ToHexString(serverKey)}").ConfigureAwait(false);
+ await keysets.WriteLineAsync(
+$"server_siglen_{channelId}_{tokenId}: {serverSigLen}").ConfigureAwait(false);
- await keysets.FlushAsync(ct).ConfigureAwait(false);
- }
+ await keysets.FlushAsync(ct).ConfigureAwait(false);
}
}
else
diff --git a/samples/Netcap/src/Storage.cs b/samples/Netcap/src/Storage.cs
index d25db240ab..793f51aa57 100644
--- a/samples/Netcap/src/Storage.cs
+++ b/samples/Netcap/src/Storage.cs
@@ -19,27 +19,17 @@ namespace Netcap;
///
/// Upload and download files
///
-internal sealed class Storage
+///
+/// Create capture sync
+///
+///
+///
+///
+///
+///
+internal sealed class Storage(string deviceId, string moduleId, string connectionString,
+ ILogger logger, string? runName = null)
{
- ///
- /// Create capture sync
- ///
- ///
- ///
- ///
- ///
- ///
- public Storage(string deviceId, string moduleId, string connectionString,
- ILogger logger, string? runName = null)
- {
- _logger = logger;
- _connectionString = connectionString;
- _deviceId = deviceId;
- _moduleId = moduleId;
- _runName = runName ?? DateTime.UtcNow.ToBinary()
- .ToString(CultureInfo.InvariantCulture);
- }
-
///
/// Download files
///
@@ -267,9 +257,10 @@ public void Report(long value)
internal sealed record class Notification(Uri ContainerUri, Uri BlobUri,
string ContainerName, string BlobName);
- private readonly string _deviceId;
- private readonly string _moduleId;
- private readonly string _runName;
- private readonly string _connectionString;
- private readonly ILogger _logger;
+ private readonly string _deviceId = deviceId;
+ private readonly string _moduleId = moduleId;
+ private readonly string _runName = runName ?? DateTime.UtcNow.ToBinary()
+ .ToString(CultureInfo.InvariantCulture);
+ private readonly string _connectionString = connectionString;
+ private readonly ILogger _logger = logger;
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Models/src/Azure.IIoT.OpcUa.Publisher.Models.csproj b/src/Azure.IIoT.OpcUa.Publisher.Models/src/Azure.IIoT.OpcUa.Publisher.Models.csproj
index f7955c6c78..821748e526 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Models/src/Azure.IIoT.OpcUa.Publisher.Models.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Models/src/Azure.IIoT.OpcUa.Publisher.Models.csproj
@@ -1,6 +1,6 @@
- net8.0
+ net9.0
true
true
true
@@ -8,7 +8,7 @@
enable
-
+
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Models/tests/Azure.IIoT.OpcUa.Publisher.Models.Tests.csproj b/src/Azure.IIoT.OpcUa.Publisher.Models/tests/Azure.IIoT.OpcUa.Publisher.Models.Tests.csproj
index 72c24ba465..09ebbcaf5a 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Models/tests/Azure.IIoT.OpcUa.Publisher.Models.Tests.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Models/tests/Azure.IIoT.OpcUa.Publisher.Models.Tests.csproj
@@ -1,25 +1,25 @@
- net8.0
+ net9.0
-
-
-
+
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
+
+
all
runtime; build; native; contentfiles; analyzers
-
-
-
+
+
+
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Models/tests/PublishNodesEndpointApiModelTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Models/tests/PublishNodesEndpointApiModelTests.cs
index 9403ef2f02..939f84b8e9 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Models/tests/PublishNodesEndpointApiModelTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Models/tests/PublishNodesEndpointApiModelTests.cs
@@ -8,7 +8,6 @@ namespace Azure.IIoT.OpcUa.Publisher.Models.Tests
using Furly.Extensions.Serializers;
using Furly.Extensions.Serializers.Newtonsoft;
using System;
- using System.Collections.Generic;
using Xunit;
public class PublishedNodesEntryModelTests
@@ -70,11 +69,11 @@ public void UseSecuritySerializationTest()
var model = new PublishedNodesEntryModel
{
EndpointUrl = "opc.tcp://localhost:50000",
- OpcNodes = new List {
+ OpcNodes = [
new() {
Id = "i=2258"
}
- }
+ ]
};
var modeJson = newtonSoftJsonSerializer.SerializeToString(model);
@@ -84,11 +83,11 @@ public void UseSecuritySerializationTest()
{
EndpointUrl = "opc.tcp://localhost:50000",
UseSecurity = false,
- OpcNodes = new List {
+ OpcNodes = [
new() {
Id = "i=2258"
}
- }
+ ]
};
modeJson = newtonSoftJsonSerializer.SerializeToString(model);
@@ -98,11 +97,11 @@ public void UseSecuritySerializationTest()
{
EndpointUrl = "opc.tcp://localhost:50000",
UseSecurity = true,
- OpcNodes = new List {
+ OpcNodes = [
new() {
Id = "i=2258"
}
- }
+ ]
};
modeJson = newtonSoftJsonSerializer.SerializeToString(model);
@@ -167,11 +166,11 @@ public void OpcAuthenticationModeSerializationTest()
var model = new PublishedNodesEntryModel
{
EndpointUrl = "opc.tcp://localhost:50000",
- OpcNodes = new List {
+ OpcNodes = [
new() {
Id = "i=2258"
}
- }
+ ]
};
var modeJson = newtonSoftJsonSerializer.SerializeToString(model);
@@ -181,11 +180,11 @@ public void OpcAuthenticationModeSerializationTest()
{
EndpointUrl = "opc.tcp://localhost:50000",
OpcAuthenticationMode = OpcAuthenticationMode.Anonymous,
- OpcNodes = new List {
+ OpcNodes = [
new() {
Id = "i=2258"
}
- }
+ ]
};
modeJson = newtonSoftJsonSerializer.SerializeToString(model);
@@ -195,11 +194,11 @@ public void OpcAuthenticationModeSerializationTest()
{
EndpointUrl = "opc.tcp://localhost:50000",
OpcAuthenticationMode = OpcAuthenticationMode.UsernamePassword,
- OpcNodes = new List {
+ OpcNodes = [
new() {
Id = "i=2258"
}
- }
+ ]
};
modeJson = newtonSoftJsonSerializer.SerializeToString(model);
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/cli/Azure.IIoT.OpcUa.Publisher.Module.Cli.csproj b/src/Azure.IIoT.OpcUa.Publisher.Module/cli/Azure.IIoT.OpcUa.Publisher.Module.Cli.csproj
index eb974914e7..d8077080be 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/cli/Azure.IIoT.OpcUa.Publisher.Module.Cli.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/cli/Azure.IIoT.OpcUa.Publisher.Module.Cli.csproj
@@ -1,14 +1,14 @@
Exe
- net8.0
+ net9.0
true
enable
true
-
-
+
+
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/cli/Program.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/cli/Program.cs
index a73d956a3f..8447e35d74 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/cli/Program.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/cli/Program.cs
@@ -223,7 +223,7 @@ public static void Main(string[] args)
moduleId = "publisher";
logger.LogInformation("Using '{ModuleId}'", moduleId);
- args = unknownArgs.ToArray();
+ args = [.. unknownArgs];
}
catch (Exception e)
{
@@ -300,12 +300,12 @@ public static void Main(string[] args)
case 'P':
case 'p':
Console.WriteLine("Restarting publisher...");
- _restartPublisher.Set();
+ kRestartPublisher.Set();
break;
case 'S':
case 's':
Console.WriteLine("Restarting server...");
- _restartServer.Set();
+ kRestartServer.Set();
break;
}
}
@@ -319,8 +319,8 @@ public static void Main(string[] args)
}
}
- private static readonly AsyncAutoResetEvent _restartServer = new(false);
- private static readonly AsyncAutoResetEvent _restartPublisher = new(false);
+ private static readonly AsyncAutoResetEvent kRestartServer = new(false);
+ private static readonly AsyncAutoResetEvent kRestartPublisher = new(false);
///
/// Host the module with connection string loaded from iot hub
@@ -374,7 +374,7 @@ private static async Task HostAsync(string? connectionString, ILoggerFactory log
reverseConnectPort, publishedNodesFilePath, publishInitFile, cts.Token);
Console.WriteLine("Publisher running (Press P to restart)...");
- await _restartPublisher.WaitAsync(ct).ConfigureAwait(false);
+ await kRestartPublisher.WaitAsync(ct).ConfigureAwait(false);
try
{
await cts.CancelAsync().ConfigureAwait(false);
@@ -423,7 +423,7 @@ static async Task RunAsync(ILogger logger, string deviceId, string moduleId, str
// default the profile to use reverse connect
arguments.Add("--urc");
}
- await Publisher.Module.Program.RunAsync(arguments.ToArray(), ct).ConfigureAwait(false);
+ await Publisher.Module.Program.RunAsync([.. arguments], ct).ConfigureAwait(false);
logger.LogInformation("Publisher module {DeviceId} {ModuleId} exited.",
deviceId, moduleId);
}
@@ -450,26 +450,24 @@ private static async Task WithServerAsync(string? connectionString, ILoggerFacto
try
{
// Start test server
- using (var server = new ServerWrapper(scaleunits, loggerFactory, reverseConnectPort))
- {
- var endpointUrl = $"opc.tcp://localhost:{server.Port}/UA/SampleServer";
+ using var server = new ServerWrapper(scaleunits, loggerFactory, reverseConnectPort);
+ var endpointUrl = $"opc.tcp://localhost:{server.Port}/UA/SampleServer";
- var publishInitFile = await LoadInitFile(server, publishInitProfile,
- endpointUrl, ct).ConfigureAwait(false);
+ var publishInitFile = await LoadInitFileAsync(publishInitProfile, endpointUrl,
+ ct).ConfigureAwait(false);
- if (publishInitFile != null && publishProfile == null)
- {
- publishProfile = "Empty";
- }
+ if (publishInitFile != null && publishProfile == null)
+ {
+ publishProfile = "Empty";
+ }
- var publishedNodesFilePath = await LoadPnJson(server, publishProfile,
- endpointUrl, ct).ConfigureAwait(false);
+ var publishedNodesFilePath = await LoadPnJsonAsync(server, publishProfile,
+ endpointUrl, ct).ConfigureAwait(false);
- // Start publisher module
- await HostAsync(connectionString, loggerFactory, deviceId, moduleId,
- args, reverseConnectPort, acceptAll, publishInitFile, publishedNodesFilePath,
- ct).ConfigureAwait(false);
- }
+ // Start publisher module
+ await HostAsync(connectionString, loggerFactory, deviceId, moduleId,
+ args, reverseConnectPort, acceptAll, publishInitFile, publishedNodesFilePath,
+ ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
}
@@ -587,35 +585,33 @@ static async Task RunAsync(ILoggerFactory loggerFactory, string publishProfile,
string? publishInitProfile, CancellationToken ct)
{
// Start test server
- using (var server = new ServerWrapper(scaleunits, loggerFactory, null))
+ using var server = new ServerWrapper(scaleunits, loggerFactory, null);
+ var name = Path.GetFileNameWithoutExtension(publishProfile);
+ var endpointUrl = $"opc.tcp://localhost:{server.Port}/UA/SampleServer";
+
+ var publishedNodesFilePath = await LoadPnJsonAsync(server, name, endpointUrl,
+ ct).ConfigureAwait(false);
+ if (publishedNodesFilePath == null)
{
- var name = Path.GetFileNameWithoutExtension(publishProfile);
- var endpointUrl = $"opc.tcp://localhost:{server.Port}/UA/SampleServer";
+ return;
+ }
- var publishedNodesFilePath = await LoadPnJson(server, name, endpointUrl,
- ct).ConfigureAwait(false);
- if (publishedNodesFilePath == null)
- {
- return;
- }
+ var publishInitFile = await LoadInitFileAsync(name, endpointUrl, ct).ConfigureAwait(false);
- var publishInitFile = await LoadInitFile(server, name, endpointUrl,
- ct).ConfigureAwait(false);
-
- //
- // Check whether the profile overrides the messaging mode, then set it to the desired
- // one regardless of whether it will work or not
- //
- var check = await File.ReadAllTextAsync(publishedNodesFilePath, ct).ConfigureAwait(false);
- if (check.Contains("\"MessagingMode\":", StringComparison.InvariantCulture) &&
- !check.Contains($"\"MessagingMode\": \"{messageProfile.MessagingMode}\"",
- StringComparison.InvariantCulture))
- {
- check = ReplacePropertyValue(check, "MessagingMode", messageProfile.MessagingMode.ToString());
- await File.WriteAllTextAsync(publishedNodesFilePath, check, ct).ConfigureAwait(false);
- }
+ //
+ // Check whether the profile overrides the messaging mode, then set it to the desired
+ // one regardless of whether it will work or not
+ //
+ var check = await File.ReadAllTextAsync(publishedNodesFilePath, ct).ConfigureAwait(false);
+ if (check.Contains("\"MessagingMode\":", StringComparison.InvariantCulture) &&
+ !check.Contains($"\"MessagingMode\": \"{messageProfile.MessagingMode}\"",
+ StringComparison.InvariantCulture))
+ {
+ check = ReplacePropertyValue(check, "MessagingMode", messageProfile.MessagingMode.ToString());
+ await File.WriteAllTextAsync(publishedNodesFilePath, check, ct).ConfigureAwait(false);
+ }
- var arguments = new HashSet
+ var arguments = new HashSet
{
"-c",
"--ps",
@@ -628,17 +624,16 @@ static async Task RunAsync(ILoggerFactory loggerFactory, string publishProfile,
$"-o={outputFolder}",
"--aa"
};
- if (publishInitFile != null)
- {
- arguments.Add($"--pi={publishInitFile}");
- }
- args.ForEach(a => arguments.Add(a));
- await Publisher.Module.Program.RunAsync(arguments.ToArray(), ct).ConfigureAwait(false);
+ if (publishInitFile != null)
+ {
+ arguments.Add($"--pi={publishInitFile}");
}
+ args.ForEach(a => arguments.Add(a));
+ await Publisher.Module.Program.RunAsync([.. arguments], ct).ConfigureAwait(false);
}
}
- private static async Task LoadPnJson(ServerWrapper server, string? publishProfile,
+ private static async Task LoadPnJsonAsync(ServerWrapper server, string? publishProfile,
string endpointUrl, CancellationToken ct)
{
const string publishedNodesFilePath = "profile.json";
@@ -671,8 +666,8 @@ await File.WriteAllTextAsync(publishedNodesFilePath,
return null;
}
- private static async Task LoadInitFile(ServerWrapper server, string? initProfile,
- string endpointUrl, CancellationToken ct)
+ private static async Task LoadInitFileAsync(string? initProfile, string endpointUrl,
+ CancellationToken ct)
{
const string initFile = "profile.init";
if (!string.IsNullOrEmpty(initProfile))
@@ -818,14 +813,14 @@ await server.AddReverseConnectionAsync(
new Uri($"opc.tcp://localhost:{reverseConnectPort}"),
1).ConfigureAwait(false);
}
- await _restartServer.WaitAsync(ct).ConfigureAwait(false);
+ await kRestartServer.WaitAsync(ct).ConfigureAwait(false);
logger.LogInformation("Stopping server...");
Server = new TaskCompletionSource();
}
logger.LogInformation("Server stopped.");
logger.LogInformation("Waiting to restarting server (Press S to restart)...");
- await _restartServer.WaitAsync(ct).ConfigureAwait(false);
+ await kRestartServer.WaitAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
catch (Exception ex)
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Azure.IIoT.OpcUa.Publisher.Module.csproj b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Azure.IIoT.OpcUa.Publisher.Module.csproj
index f6bd9f0d20..14e6903725 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Azure.IIoT.OpcUa.Publisher.Module.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Azure.IIoT.OpcUa.Publisher.Module.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
true
true
true
@@ -33,23 +33,23 @@
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Controllers/ConfigurationController.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Controllers/ConfigurationController.cs
index f274bcae7f..954aeaa0cd 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Controllers/ConfigurationController.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Controllers/ConfigurationController.cs
@@ -16,7 +16,6 @@ namespace Azure.IIoT.OpcUa.Publisher.Module.Controllers
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
- using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -353,7 +352,7 @@ public async Task SetConfiguredEndpointsAsync(
{
ArgumentNullException.ThrowIfNull(request);
await _configServices.SetConfiguredEndpointsAsync(new List(
- request.Endpoints ?? Enumerable.Empty()),
+ request.Endpoints ?? []),
ct).ConfigureAwait(false);
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Controllers/FileSystemController.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Controllers/FileSystemController.cs
index 5c25427f31..9546e2fcef 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Controllers/FileSystemController.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Controllers/FileSystemController.cs
@@ -486,17 +486,15 @@ public async Task UploadAsync(
throw new NotSupportedException("Upload not supported");
}
- await using (var _ = HttpContext.Request.Body.ConfigureAwait(false))
- {
- var result = await _files.CopyFromAsync(connection,
- fileObject, HttpContext.Request.Body, options, ct).ConfigureAwait(false);
+ await using var _ = HttpContext.Request.Body.ConfigureAwait(false);
+ var result = await _files.CopyFromAsync(connection,
+ fileObject, HttpContext.Request.Body, options, ct).ConfigureAwait(false);
- if (result?.StatusCode != 0)
- {
- HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
- HttpContext.Response.Headers.Append("errorInfo",
- new StringValues(_serializer.SerializeObjectToString(result)));
- }
+ if (result?.StatusCode != 0)
+ {
+ HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
+ HttpContext.Response.Headers.Append("errorInfo",
+ new StringValues(_serializer.SerializeObjectToString(result)));
}
}
private readonly IFileSystemServices _files;
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Filters/ControllerExceptionFilterAttribute.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Filters/ControllerExceptionFilterAttribute.cs
index 4ad0c78982..bc9823463f 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Filters/ControllerExceptionFilterAttribute.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Filters/ControllerExceptionFilterAttribute.cs
@@ -58,47 +58,47 @@ public override void OnException(ExceptionContext context)
.GetService();
switch (context.Exception)
{
- case ResourceNotFoundException re:
+ case ResourceNotFoundException:
context.Result = GetResponse(HttpStatusCode.NotFound,
context.Exception, summarizer);
break;
- case ResourceInvalidStateException ri:
+ case ResourceInvalidStateException:
context.Result = GetResponse(HttpStatusCode.Forbidden,
context.Exception, summarizer);
break;
- case ResourceConflictException ce:
+ case ResourceConflictException:
context.Result = GetResponse(HttpStatusCode.Conflict,
context.Exception, summarizer);
break;
- case UnauthorizedAccessException ue:
- case SecurityException se:
+ case UnauthorizedAccessException:
+ case SecurityException:
context.Result = GetResponse(HttpStatusCode.Unauthorized,
context.Exception, summarizer);
break;
case MethodCallStatusException mcs:
context.Result = new ObjectResult(mcs.Details.ToProblemDetails());
break;
- case SerializerException sre:
- case MethodCallException mce:
- case BadRequestException br:
- case ArgumentException are:
+ case SerializerException:
+ case MethodCallException:
+ case BadRequestException:
+ case ArgumentException:
context.Result = GetResponse(HttpStatusCode.BadRequest,
context.Exception, summarizer);
break;
- case NotSupportedException ns:
+ case NotSupportedException:
context.Result = GetResponse(HttpStatusCode.MethodNotAllowed,
context.Exception, summarizer);
break;
- case NotImplementedException ne:
+ case NotImplementedException:
context.Result = GetResponse(HttpStatusCode.NotImplemented,
context.Exception, summarizer);
break;
- case TimeoutException te:
+ case TimeoutException:
context.Result = GetResponse(HttpStatusCode.RequestTimeout,
context.Exception, summarizer);
break;
- case SocketException sex:
- case IOException ce:
+ case SocketException:
+ case IOException:
context.Result = GetResponse(HttpStatusCode.BadGateway,
context.Exception, summarizer);
break;
@@ -121,15 +121,15 @@ public override void OnException(ExceptionContext context)
// one of the above.
//
- case ServerBusyException se:
+ case ServerBusyException:
context.Result = GetResponse(HttpStatusCode.TooManyRequests,
context.Exception, summarizer);
break;
- case ResourceOutOfDateException re:
+ case ResourceOutOfDateException:
context.Result = GetResponse(HttpStatusCode.PreconditionFailed,
context.Exception, summarizer);
break;
- case ExternalDependencyException ex:
+ case ExternalDependencyException:
context.Result = GetResponse(HttpStatusCode.ServiceUnavailable,
context.Exception, summarizer);
break;
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/CommandLine.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/CommandLine.cs
index 5646bc3187..3307f567eb 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/CommandLine.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/CommandLine.cs
@@ -106,10 +106,10 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
"Use strict OPC UA standard compliance. It is recommended to run the publisher in compliant mode for best interoperability.\nBe aware that explicitly specifying other command line options can result in non-comnpliance despite this option being set.\nDefault: `false` for backwards compatibility (2.5.x - 2.8.x)\n",
(bool? b) => this[PublisherConfig.UseStandardsCompliantEncodingKey] = b?.ToString() ?? "True" },
{ $"nf|namespaceformat=|{PublisherConfig.DefaultNamespaceFormatKey}=",
- $"The format to use when serializing node ids and qualified names containing a namespace uri into a string.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(NamespaceFormat)))}`\nDefault: `{nameof(NamespaceFormat.Expanded)}` if `-c` is specified, otherwise `{nameof(NamespaceFormat.Uri)}` for backwards compatibility.\n",
+ $"The format to use when serializing node ids and qualified names containing a namespace uri into a string.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(NamespaceFormat.Expanded)}` if `-c` is specified, otherwise `{nameof(NamespaceFormat.Uri)}` for backwards compatibility.\n",
(NamespaceFormat m) => this[PublisherConfig.DefaultNamespaceFormatKey] = m.ToString() },
{ $"mm|messagingmode=|{PublisherConfig.MessagingModeKey}=",
- $"The messaging mode for messages\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(MessagingMode)))}`\nDefault: `{nameof(MessagingMode.PubSub)}` if `-c` is specified, otherwise `{nameof(MessagingMode.Samples)}` for backwards compatibility.\n",
+ $"The messaging mode for messages\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(MessagingMode.PubSub)}` if `-c` is specified, otherwise `{nameof(MessagingMode.Samples)}` for backwards compatibility.\n",
(MessagingMode m) => this[PublisherConfig.MessagingModeKey] = m.ToString() },
{ $"ode|optimizeddatasetencoding:|{PublisherConfig.WriteValueWhenDataSetHasSingleEntryKey}:",
"When a data set has a single entry the encoder will write only the value of a data set entry and omit the key.\nThis is not compliant with OPC UA Part 14.\nDefault: `false`.\n",
@@ -122,7 +122,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
// TODO: Allow overriding schema
{ $"me|messageencoding=|{PublisherConfig.MessageEncodingKey}=",
- $"The message encoding for messages\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(MessageEncoding)))}`\nDefault: `{nameof(MessageEncoding.Json)}`.\n",
+ $"The message encoding for messages\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(MessageEncoding.Json)}`.\n",
(MessageEncoding m) => this[PublisherConfig.MessageEncodingKey] = m.ToString() },
{ $"fm|fullfeaturedmessage=|{PublisherConfig.FullFeaturedMessageKey}=",
"The full featured mode for messages (all fields filled in) for backwards compatibilty. \nDefault: `false` for legacy compatibility.\n",
@@ -143,7 +143,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
"The maximum size of the messages to emit. In case the encoder cannot encode a message because the size would be exceeded, the message is dropped. Otherwise the encoder will aim to chunk messages if possible. \nDefault: `256k` in case of IoT Hub messages, `0` otherwise.\n",
(uint i) => this[PublisherConfig.IoTHubMaxMessageSizeKey] = i.ToString(CultureInfo.CurrentCulture) },
{ $"qos|{PublisherConfig.DefaultQualityOfServiceKey}=",
- $"The default quality of service to use for data set messages.\nThis does not apply to metadata messages which are always sent with `AtLeastOnce` semantics.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(QoS)))}`\nDefault: `{nameof(QoS.AtLeastOnce)}`.\n",
+ $"The default quality of service to use for data set messages.\nThis does not apply to metadata messages which are always sent with `AtLeastOnce` semantics.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(QoS.AtLeastOnce)}`.\n",
(QoS q) => this[PublisherConfig.DefaultQualityOfServiceKey] = q.ToString() },
{ $"ttl|{PublisherConfig.DefaultMessageTimeToLiveKey}=",
"The default time to live for all network message published in milliseconds if the transport supports it.\nThis does not apply to metadata messages which are always sent with a ttl of the metadata update interval or infinite ttl.\nDefault: `not set` (infinite).\n",
@@ -155,7 +155,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
// TODO: Add ConfiguredMessageSize
{ $"mts|messagetimestamp=|{PublisherConfig.MessageTimestampKey}=",
- $"The value to set as as the timestamp property of messages during encoding (if the encoding supports writing message timestamps).\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(MessageTimestamp)))}`\nDefault: `{nameof(MessageTimestamp.CurrentTimeUtc)}` to use the time when the message was created in OPC Publisher.\n",
+ $"The value to set as as the timestamp property of messages during encoding (if the encoding supports writing message timestamps).\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(MessageTimestamp.CurrentTimeUtc)}` to use the time when the message was created in OPC Publisher.\n",
(MessageTimestamp m) => this[PublisherConfig.MessageTimestampKey] = m.ToString() },
{ $"npd|maxnodesperdataset=|{PublisherConfig.MaxNodesPerDataSetKey}=",
"Maximum number of nodes within a Subscription. When there are more nodes configured for a data set writer, they will be added to new subscriptions. This also affects metadata message size. \nDefault: `1000`.\n",
@@ -196,7 +196,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
"The number of partitions to split the writer group into. Each partition represents a data flow to the transport sink. The partition is selected by topic hash.\nDefault: `0` (partitioning is disabled)\n",
(ushort i) => this[PublisherConfig.DefaultWriterGroupPartitionCountKey] = i.ToString(CultureInfo.InvariantCulture) },
{ $"t|dmt=|defaultmessagetransport=|{PublisherConfig.DefaultTransportKey}=",
- $"The desired transport to use to publish network messages with.\nRequires the transport to be properly configured (see transport settings).\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(WriterGroupTransport)))}`\nDefault: `{nameof(WriterGroupTransport.IoTHub)}` or the first configured transport of the allowed value list.\n",
+ $"The desired transport to use to publish network messages with.\nRequires the transport to be properly configured (see transport settings).\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(WriterGroupTransport.IoTHub)}` or the first configured transport of the allowed value list.\n",
(WriterGroupTransport p) => this[PublisherConfig.DefaultTransportKey] = p.ToString() },
"",
@@ -210,7 +210,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
$"A edge hub or iot hub connection string to use if you run OPC Publisher outside of IoT Edge. The connection string can be obtained from the IoT Hub portal. It is not required to use this option if running inside IoT Edge. To publish through IoT Edge by default specify `-t={nameof(WriterGroupTransport.IoTHub)}`.\nDefault: `not set`.\n",
dc => this[Configuration.IoTEdge.EdgeHubConnectionString] = dc },
{ $"ht|ih=|iothubprotocol=|{Configuration.IoTEdge.HubTransport}=",
- $"Protocol to use for communication with EdgeHub.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(TransportOption)))}`\nDefault: `{nameof(TransportOption.Mqtt)}` if device or edge hub connection string is provided, ignored otherwise.\n",
+ $"Protocol to use for communication with EdgeHub.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(TransportOption.Mqtt)}` if device or edge hub connection string is provided, ignored otherwise.\n",
(TransportOption p) => this[Configuration.IoTEdge.HubTransport] = p.ToString() },
{ $"eh=|eventhubnamespaceconnectionstring=|{Configuration.EventHubs.EventHubNamespaceConnectionString}=",
"The connection string of an existing event hub namespace to use for the Azure EventHub transport.\nDefault: `not set`.\n",
@@ -267,7 +267,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
"The topic that schemas should be sent to if schema publishing is configured.\nIn case of MQTT schemas will not be sent with .\nOnly valid if schema publishing is enabled (`--ps`).\nThe template variables\n `{{RootTopic}}`\n `{{SiteId}}`\n `{{PublisherId}}`\n `{{TelemetryTopic}}`\ncan be used as variables inside the template. \nDefault: `{{TelemetryTopic}}/schema` which means the schema is sent to a sub topic where the telemetry message is sent to.\n",
s => this[PublisherConfig.SchemaTopicTemplateKey] = !string.IsNullOrEmpty(s) ? s : PublisherConfig.SchemaTopicTemplateDefault },
{ $"uns|datasetrouting=|{PublisherConfig.DefaultDataSetRoutingKey}=",
- $"Configures whether messages should automatically be routed using the browse path of the monitored item inside the address space starting from the RootFolder.\nThe browse path is appended as topic structure to the telemetry topic root which can be configured using `--ttt`. Reserved characters in browse names are escaped with their hex ASCII code.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(DataSetRoutingMode)))}`\nDefault: `{nameof(DataSetRoutingMode.None)}` (Topics must be configured).\n",
+ $"Configures whether messages should automatically be routed using the browse path of the monitored item inside the address space starting from the RootFolder.\nThe browse path is appended as topic structure to the telemetry topic root which can be configured using `--ttt`. Reserved characters in browse names are escaped with their hex ASCII code.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(DataSetRoutingMode.None)}` (Topics must be configured).\n",
(DataSetRoutingMode m) => this[PublisherConfig.DefaultDataSetRoutingKey] = m.ToString() },
{ $"ri|enableroutinginfo:|{PublisherConfig.EnableDataSetRoutingInfoKey}:",
$"Add routing information to messages. The name of the property is `{Constants.MessagePropertyRoutingKey}` and the value is the `DataSetWriterGroup` from which the particular message is emitted.\nDefault: `{PublisherConfig.EnableDataSetRoutingInfoDefault}`.\n",
@@ -314,16 +314,16 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
"The publisher is using this as default value for the discard old setting of monitored item queue configuration. Setting to true will ensure that new values are dropped before older ones are drained. \nDefault: `false` (which is the OPC UA default).\n",
(bool? b) => this[OpcUaSubscriptionConfig.DefaultDiscardNewKey] = b?.ToString() ?? "True" },
{ $"mc|monitoreditemdatachangetrigger=|{OpcUaSubscriptionConfig.DefaultDataChangeTriggerKey}=",
- $"Default data change trigger for all monitored items configured in the published nodes configuration unless explicitly overridden.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(DataChangeTriggerType)))}`\nDefault: `{nameof(DataChangeTriggerType.StatusValue)}` (which is the OPC UA default).\n",
+ $"Default data change trigger for all monitored items configured in the published nodes configuration unless explicitly overridden.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(DataChangeTriggerType.StatusValue)}` (which is the OPC UA default).\n",
(DataChangeTriggerType t) => this[OpcUaSubscriptionConfig.DefaultDataChangeTriggerKey] = t.ToString() },
{ $"mwt|monitoreditemwatchdog=|{OpcUaSubscriptionConfig.DefaultMonitoredItemWatchdogSecondsKey}=",
"The subscription and monitored item watchdog timeout in seconds the subscription uses to check on late reporting monitored items unless overridden in the published nodes configuration explicitly.\nDefault: `not set` (watchdog disabled).\n",
(uint u) => this[OpcUaSubscriptionConfig.DefaultMonitoredItemWatchdogSecondsKey] = u.ToString(CultureInfo.CurrentCulture) },
{ $"mwc|monitoreditemwatchdogcondition=|{OpcUaSubscriptionConfig.DefaultMonitoredItemWatchdogConditionKey}=",
- $"The default condition when to run the action configured as the watchdog behavior. The condition can be overridden in the published nodes configuration.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(MonitoredItemWatchdogCondition)))}`\nDefault: `{nameof(MonitoredItemWatchdogCondition.WhenAllAreLate)}` (if enabled).\n",
+ $"The default condition when to run the action configured as the watchdog behavior. The condition can be overridden in the published nodes configuration.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(MonitoredItemWatchdogCondition.WhenAllAreLate)}` (if enabled).\n",
(MonitoredItemWatchdogCondition b) => this[OpcUaSubscriptionConfig.DefaultMonitoredItemWatchdogConditionKey] = b.ToString() },
{ $"dwb|watchdogbehavior=|{OpcUaSubscriptionConfig.DefaultWatchdogBehaviorKey}=",
- $"Default behavior of the subscription and monitored item watchdog mechanism unless overridden in the published nodes configuration explicitly.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(SubscriptionWatchdogBehavior)))}`\nDefault: `{nameof(SubscriptionWatchdogBehavior.Diagnostic)}` (if enabled).\n",
+ $"Default behavior of the subscription and monitored item watchdog mechanism unless overridden in the published nodes configuration explicitly.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{nameof(SubscriptionWatchdogBehavior.Diagnostic)}` (if enabled).\n",
(SubscriptionWatchdogBehavior b) => this[OpcUaSubscriptionConfig.DefaultWatchdogBehaviorKey] = b.ToString() },
{ $"sf|skipfirst:|{OpcUaSubscriptionConfig.DefaultSkipFirstKey}:",
$"The publisher is using this as default value for the skip first setting of nodes configured without a skip first setting. A value of True will skip sending the first notification received when the monitored item is added to the subscription.\nDefault: `{OpcUaSubscriptionConfig.DefaultSkipFirstDefault}` (disabled).\n",
@@ -334,7 +334,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
$"Configure whether publisher republishes missed subscription notifications still in the server queue after transferring a subscription during reconnect handling.\nThis can result in out of order notifications after a reconnect but minimizes data loss.\nDefault: `{OpcUaSubscriptionConfig.DefaultRepublishAfterTransferDefault}` (disabled).\n",
(bool? b) => this[OpcUaSubscriptionConfig.DefaultRepublishAfterTransferKey] = b?.ToString() ?? "True" },
{ $"hbb|heartbeatbehavior=|{OpcUaSubscriptionConfig.DefaultHeartbeatBehaviorKey}=",
- $"Default behavior of the heartbeat mechanism unless overridden in the published nodes configuration explicitly.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(HeartbeatBehavior)).Where(n => !n.StartsWith(nameof(HeartbeatBehavior.Reserved), StringComparison.InvariantCulture)))}`\nDefault: `{nameof(HeartbeatBehavior.WatchdogLKV)}` (Sending LKV in a watchdog fashion).\n",
+ $"Default behavior of the heartbeat mechanism unless overridden in the published nodes configuration explicitly.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames().Where(n => !n.StartsWith(nameof(HeartbeatBehavior.Reserved), StringComparison.InvariantCulture)))}`\nDefault: `{nameof(HeartbeatBehavior.WatchdogLKV)}` (Sending LKV in a watchdog fashion).\n",
(HeartbeatBehavior b) => this[OpcUaSubscriptionConfig.DefaultHeartbeatBehaviorKey] = b.ToString() },
{ $"hb|heartbeatinterval=|{OpcUaSubscriptionConfig.DefaultHeartbeatIntervalKey}=",
"The publisher is using this as default value in seconds for the heartbeat interval setting of nodes that were configured without a heartbeat interval setting. A heartbeat is sent at this interval if no value has been received.\nDefault: `0` (disabled)\nAlso can be set using `DefaultHeartbeatInterval` environment variable in the form of a duration string in the form `[d.]hh:mm:ss[.fffffff]`.\n",
@@ -542,7 +542,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
"",
{ $"ll|loglevel=|{Configuration.LoggingLevel.LogLevelKey}=",
- $"The loglevel to use.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(LogLevel)))}`\nDefault: `{LogLevel.Information}`.\n",
+ $"The loglevel to use.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{LogLevel.Information}`.\n",
(LogLevel l) => this[Configuration.LoggingLevel.LogLevelKey] = l.ToString() },
{ $"lfm|logformat=|{Configuration.LoggingFormat.LogFormatKey}=",
$"The log format to use when writing to the console.\nAllowed values:\n `{string.Join("`\n `", Configuration.LoggingFormat.LogFormatsSupported)}`\nDefault: `{Configuration.LoggingFormat.LogFormatDefault}`.\n",
@@ -551,7 +551,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
"Produce publisher diagnostic information at this specified interval in seconds.\nBy default diagnostics are written to the OPC Publisher logger (which requires at least --loglevel `information`) unless configured differently using `--pd`.\n`0` disables diagnostic output.\nDefault:60000 (60 seconds).\nAlso can be set using `DiagnosticsInterval` environment variable in the form of a duration string in the form `[d.]hh:mm:ss[.fffffff]`\".\n",
(uint i) => this[PublisherConfig.DiagnosticsIntervalKey] = TimeSpan.FromSeconds(i).ToString() },
{ $"pd|diagnosticstarget=|{PublisherConfig.DiagnosticsTargetKey}=",
- $"Configures how to emit diagnostics information at the `--di` configured interval.\nUse this to for example emit diagnostics as events to the event topic template instead of the console.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames(typeof(PublisherDiagnosticTargetType)))}`\nDefault: `{PublisherDiagnosticTargetType.Logger}`.\n",
+ $"Configures how to emit diagnostics information at the `--di` configured interval.\nUse this to for example emit diagnostics as events to the event topic template instead of the console.\nAllowed values:\n `{string.Join("`\n `", Enum.GetNames())}`\nDefault: `{PublisherDiagnosticTargetType.Logger}`.\n",
(PublisherDiagnosticTargetType d) => this[PublisherConfig.DiagnosticsTargetKey] = d.ToString() },
{ $"dr|disableresourcemonitoring:|{PublisherConfig.DisableResourceMonitoringKey}:",
"Disable resource monitoring as part of the diagnostics output and metrics.\nDefault: `false` (enabled).\n",
@@ -581,7 +581,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
"Specifiy the OpenTelemetry collector grpc endpoint url to export diagnostics to.\nDefault: `disabled`.\n",
s => this[Configuration.Otlp.OtlpCollectorEndpointKey] = s },
{ $"oxi|otlpexportinterval=|{Configuration.Otlp.OtlpExportIntervalMillisecondsKey}=",
- $"The interval in milliseconds when OpenTelemetry is exported to the collector endpoint.\nDefault: `{Configuration.Otlp.OtlpExportIntervalMillisecondsDefault}` ({(int)(Configuration.Otlp.OtlpExportIntervalMillisecondsDefault / 1000)} seconds).\n",
+ $"The interval in milliseconds when OpenTelemetry is exported to the collector endpoint.\nDefault: `{Configuration.Otlp.OtlpExportIntervalMillisecondsDefault}` ({Configuration.Otlp.OtlpExportIntervalMillisecondsDefault / 1000} seconds).\n",
(uint i) => this[Configuration.Otlp.OtlpExportIntervalMillisecondsKey] = TimeSpan.FromMilliseconds(i).ToString() },
{ $"mms|maxmetricstreams=|{Configuration.Otlp.OtlpMaxMetricStreamsKey}=",
$"Specifiy the max number of streams to collect in the default view.\nDefault: `{Configuration.Otlp.OtlpMaxMetricDefault}`.\n",
@@ -679,7 +679,7 @@ public CommandLine(string[] args, CommandLineLogger? logger = null)
try
{
// Throws if the messaging profile configuration is invalid
- new PublisherConfig(configuration).ToOptions();
+ _ = new PublisherConfig(configuration).ToOptions();
}
catch (Exception ex)
{
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/Configuration.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/Configuration.cs
index 42d9993727..dd209780e9 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/Configuration.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/Configuration.cs
@@ -642,12 +642,12 @@ internal class LoggingFormat : PostConfigureOptionBase
///
/// Supported formats
///
- public static readonly string[] LogFormatsSupported = new[]
- {
+ public static readonly string[] LogFormatsSupported =
+ [
ConsoleFormatterNames.Simple,
Syslog.FormatterName,
ConsoleFormatterNames.Systemd
- };
+ ];
///
/// Configuration
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/Syslog.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/Syslog.cs
index 62478603ba..1ef3f98c53 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/Syslog.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/src/Runtime/Syslog.cs
@@ -56,8 +56,8 @@ public override void Write(in LogEntry logEntry,
{
return;
}
- var messageBuilder = new StringBuilder(_initialLength)
- .Append(_syslogMap[(int)logEntry.LogLevel])
+ var messageBuilder = new StringBuilder(kInitialLength)
+ .Append(kSyslogMap[(int)logEntry.LogLevel])
.Append(DateTimeOffset.UtcNow.ToString(_timestampFormat, CultureInfo.InvariantCulture));
if (_includeScopes && scopeProvider != null && !string.IsNullOrEmpty(_serviceId))
{
@@ -81,20 +81,20 @@ public void Dispose()
_optionsReloadToken?.Dispose();
}
- private const int _initialLength = 256;
+ private const int kInitialLength = 256;
///
/// Map of to syslog severity.
///
- private static readonly string[] _syslogMap = new[]
- {
+ private static readonly string[] kSyslogMap =
+ [
/* Trace */ "<7>",
/* Debug */ "<7>",
/* Info */ "<6>",
/* Warn */ "<4>",
/* Error */ "<3>",
/* Crit */ "<3>"
- };
+ ];
private readonly IDisposable? _optionsReloadToken;
private readonly string _timestampFormat;
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Azure.IIoT.OpcUa.Publisher.Module.Tests.csproj b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Azure.IIoT.OpcUa.Publisher.Module.Tests.csproj
index 96a47a06d5..ac394032fa 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Azure.IIoT.OpcUa.Publisher.Module.Tests.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Azure.IIoT.OpcUa.Publisher.Module.Tests.csproj
@@ -1,21 +1,21 @@
- net8.0
+ net9.0
-
-
-
-
+
+
+
+
-
-
-
+
+
+
all
runtime; build; native; contentfiles; analyzers
-
-
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Clients/ConfigurationServicesRestClient.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Clients/ConfigurationServicesRestClient.cs
index 82d3fd11d1..5d456543c1 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Clients/ConfigurationServicesRestClient.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Clients/ConfigurationServicesRestClient.cs
@@ -16,7 +16,6 @@ namespace Azure.IIoT.OpcUa.Publisher.Module.Tests.Clients
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
- using static Grpc.Core.Metadata;
///
/// Implementation of file system services over http
@@ -92,7 +91,7 @@ public async Task> CreateOrUpdateAsset
Entry = request.Entry,
Header = request.Header,
WaitTime = request.WaitTime,
- Configuration = buffer.ToArray()
+ Configuration = [.. buffer]
};
return await _httpClient.PostAsync>(uri,
requestWithBuffer, _serializer, ct: ct).ConfigureAwait(false);
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Clients/FileSystemServicesRestClient.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Clients/FileSystemServicesRestClient.cs
index 9c2c7703d7..016ebb0610 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Clients/FileSystemServicesRestClient.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Clients/FileSystemServicesRestClient.cs
@@ -332,7 +332,7 @@ internal sealed class UploadStream : Stream
///
public override bool CanWrite => true;
///
- public override long Length { get => _length; }
+ public override long Length => _length;
///
public override long Position { get; set; }
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Controller/DmApiPublisherControllerTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Controller/DmApiPublisherControllerTests.cs
index c6e3965abb..5625d38d9f 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Controller/DmApiPublisherControllerTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Controller/DmApiPublisherControllerTests.cs
@@ -60,12 +60,10 @@ public DmApiPublisherControllerTests(ITestOutputHelper output)
_loggerFactory.CreateLogger());
_publishedNodesProvider = new PublishedNodesProvider(factory, _options,
_loggerFactory.CreateLogger());
- _triggerMock = new Mock();
+ _triggerMock = new Mock();
var factoryMock = new Mock();
- var writerGroup = new Mock();
- writerGroup.SetupGet(l => l.Source).Returns(_triggerMock.Object);
var lifetime = new Mock();
- lifetime.SetupGet(l => l.WriterGroup).Returns(writerGroup.Object);
+ lifetime.SetupGet(l => l.WriterGroup).Returns(_triggerMock.Object);
factoryMock
.Setup(factory => factory.Create(It.IsAny()))
.Returns(lifetime.Object);
@@ -346,7 +344,7 @@ public async Task DmApiGetConfiguredNodesOnEndpointAsyncDataSetWriterIdTestAsync
DataSetWriterId = i != 0
? $"DataSetWriterId{i}"
: null,
- OpcNodes = opcNodes.GetRange(0, i + 1).ToList()
+ OpcNodes = [.. opcNodes.GetRange(0, i + 1)]
})
.ToList();
@@ -584,11 +582,9 @@ private static void CopyContent(string sourcePath, string destinationPath)
{
var content = GetFileContent(sourcePath);
- using (var fileStream = new FileStream(destinationPath, FileMode.OpenOrCreate,
- FileAccess.Write, FileShare.ReadWrite))
- {
- fileStream.Write(Encoding.UTF8.GetBytes(content));
- }
+ using var fileStream = new FileStream(destinationPath, FileMode.OpenOrCreate,
+ FileAccess.Write, FileShare.ReadWrite);
+ fileStream.Write(Encoding.UTF8.GetBytes(content));
static string GetFileContent(string path)
{
@@ -602,8 +598,8 @@ static string GetFileContent(string path)
private readonly PublishedNodesConverter _publishedNodesJobConverter;
private readonly IOptions _options;
private readonly PublishedNodesProvider _publishedNodesProvider;
- private readonly Mock _triggerMock;
- private readonly IPublisher _publisher;
+ private readonly Mock _triggerMock;
+ private readonly PublisherService _publisher;
private readonly Mock _diagnostic;
}
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Fixtures/PublisherIntegrationTestBase.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Fixtures/PublisherIntegrationTestBase.cs
index 14f7c8aeec..8f5637582c 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Fixtures/PublisherIntegrationTestBase.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Fixtures/PublisherIntegrationTestBase.cs
@@ -319,28 +319,34 @@ protected void StartPublisher(string test, string publishedNodesFile = null,
var sw = Stopwatch.StartNew();
_logger = _logFactory.CreateLogger(test);
- arguments ??= Array.Empty();
+ arguments ??= [];
_publishedNodesFilePath = Path.GetTempFileName();
WritePublishedNodes(test, publishedNodesFile, reverseConnectPort != null, securityMode);
- arguments = arguments.Concat(
- new[]
+ arguments =
+ [
+ .. arguments,
+ .. new[]
{
$"--pf={_publishedNodesFilePath}"
- }).ToArray();
+ },
+ ];
if (OperatingSystem.IsLinux())
{
- arguments = arguments.Append("--pol").ToArray();
+ arguments = [.. arguments, "--pol"];
}
if (reverseConnectPort != null)
{
- arguments = arguments.Concat(
- new[]
+ arguments =
+ [
+ .. arguments,
+ .. new[]
{
$"--rcp={reverseConnectPort.Value}"
- }).ToArray();
+ },
+ ];
}
_publisher = new PublisherModule(null, null, null, null,
@@ -360,11 +366,12 @@ protected void WritePublishedNodes(string test, string publishedNodesFile, bool
{
if (!string.IsNullOrEmpty(publishedNodesFile))
{
- File.WriteAllText(_publishedNodesFilePath, File.ReadAllText(publishedNodesFile)
+ var pnJson = File.ReadAllText(publishedNodesFile)
.Replace("\"{{UseReverseConnect}}\"", useReverseConnect ? "true" : "false", StringComparison.Ordinal)
.Replace("{{EndpointUrl}}", EndpointUrl, StringComparison.Ordinal)
.Replace("{{SecurityMode}}", (securityMode ?? SecurityMode.None).ToString(), StringComparison.Ordinal)
- .Replace("{{DataSetWriterGroup}}", test, StringComparison.Ordinal));
+ .Replace("{{DataSetWriterGroup}}", test, StringComparison.Ordinal);
+ File.WriteAllText(_publishedNodesFilePath, pnJson);
}
}
@@ -417,7 +424,7 @@ protected PublishedNodesEntryModel[] GetEndpointsFromFile(string test, string pu
private static readonly TimeSpan kTotalTestTimeout = TimeSpan.FromMinutes(5);
private readonly CancellationTokenSource _cts;
private readonly ITestOutputHelper _testOutputHelper;
- private readonly HashSet _messageIds = new();
+ private readonly HashSet _messageIds = [];
private readonly ILoggerFactory _logFactory;
private ILogger _logger;
private PublisherModule _publisher;
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Fixtures/PublisherModule.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Fixtures/PublisherModule.cs
index cabf7c4413..9466ac173e 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Fixtures/PublisherModule.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Fixtures/PublisherModule.cs
@@ -113,7 +113,7 @@ public PublisherModule(IMessageSink messageSink, IEnumerable de
// Create module identitity
deviceId ??= Utils.GetHostName();
moduleId ??= Guid.NewGuid().ToString();
- arguments ??= Array.Empty();
+ arguments ??= [];
var publisherModule = new DeviceTwinModel
{
@@ -158,22 +158,25 @@ public PublisherModule(IMessageSink messageSink, IEnumerable de
$"KeepAlivePeriod={mqttOptions.Value.KeepAlivePeriod}"
;
var publisherId = Guid.NewGuid().ToString();
- arguments = arguments.Concat(
- new[]
+ arguments =
+ [
+ .. arguments,
+ .. new[]
{
$"--id={publisherId}",
$"--ec={edgeHubCs}",
$"--mqc={mqttCs}",
$"--ki={keepAliveInterval}",
"--aa"
- }).ToArray();
+ },
+ ];
if (OperatingSystem.IsLinux())
{
- arguments = arguments.Append("--pol").ToArray();
+ arguments = [.. arguments, "--pol"];
}
if (_useMqtt)
{
- arguments = arguments.Append("-t=Mqtt").ToArray();
+ arguments = [.. arguments, "-t=Mqtt"];
}
if (!arguments.Any(a =>
@@ -181,8 +184,13 @@ public PublisherModule(IMessageSink messageSink, IEnumerable de
a.StartsWith("--pf=", StringComparison.Ordinal) ||
a.StartsWith("--publishfile=", StringComparison.Ordinal)))
{
- arguments = arguments.Append("--cf").Append("--pf=" +
- Path.Combine(CurrentDirectory, "publishednodes.json")).ToArray();
+ arguments =
+ [
+ .. arguments,
+ "--cf",
+ "--pf=" +
+ Path.Combine(CurrentDirectory, "publishednodes.json"),
+ ];
}
var configBuilder = new ConfigurationBuilder()
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttConfigurationIntegrationTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttConfigurationIntegrationTests.cs
index 231e391fa1..c94a100592 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttConfigurationIntegrationTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttConfigurationIntegrationTests.cs
@@ -12,7 +12,6 @@ namespace Azure.IIoT.OpcUa.Publisher.Module.Tests.Mqtt.ReferenceServer
using Json.More;
using System;
using System.Collections.Generic;
- using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
@@ -43,11 +42,11 @@ protected override void Dispose(bool disposing)
[Theory]
[InlineData(true)]
[InlineData(false)]
- public async Task CanSendDataItemToTopicConfiguredWithMethod(bool useMqtt5)
+ public async Task CanSendDataItemToTopicConfiguredWithMethodAsync(bool useMqtt5)
{
- var name = nameof(CanSendDataItemToTopicConfiguredWithMethod) + (useMqtt5 ? "v5" : "v311");
+ var name = nameof(CanSendDataItemToTopicConfiguredWithMethodAsync) + (useMqtt5 ? "v5" : "v311");
var testInput = GetEndpointsFromFile(name, "./Resources/DataItems.json");
- StartPublisher(name, arguments: new string[] { "--mm=FullSamples" }, // Alternative to --fm=True
+ StartPublisher(name, arguments: ["--mm=FullSamples"], // Alternative to --fm=True
version: useMqtt5 ? MqttVersion.v5 : MqttVersion.v311);
try
{
@@ -85,9 +84,9 @@ public async Task CanSendDataItemToTopicConfiguredWithMethod(bool useMqtt5)
[Theory]
[InlineData(true)]
[InlineData(false)]
- public async Task CanSendEventToTopicConfiguredWithMethod(bool useMqtt5)
+ public async Task CanSendEventToTopicConfiguredWithMethodAsync(bool useMqtt5)
{
- var name = nameof(CanSendEventToTopicConfiguredWithMethod) + (useMqtt5 ? "v5" : "v311");
+ var name = nameof(CanSendEventToTopicConfiguredWithMethodAsync) + (useMqtt5 ? "v5" : "v311");
var testInput = GetEndpointsFromFile(name, "./Resources/SimpleEvents.json");
StartPublisher(name, version: useMqtt5 ? MqttVersion.v5 : MqttVersion.v311);
try
@@ -125,9 +124,9 @@ public async Task CanSendEventToTopicConfiguredWithMethod(bool useMqtt5)
[Theory]
[InlineData(true)]
[InlineData(false)]
- public async Task CanSendPendingConditionsToTopicConfiguredWithMethod(bool useMqtt5)
+ public async Task CanSendPendingConditionsToTopicConfiguredWithMethodAsync(bool useMqtt5)
{
- var name = nameof(CanSendPendingConditionsToTopicConfiguredWithMethod) + (useMqtt5 ? "v5" : "v311");
+ var name = nameof(CanSendPendingConditionsToTopicConfiguredWithMethodAsync) + (useMqtt5 ? "v5" : "v311");
var testInput = GetEndpointsFromFile(name, "./Resources/PendingAlarms.json");
StartPublisher(name, version: useMqtt5 ? MqttVersion.v5 : MqttVersion.v311);
try
@@ -173,9 +172,9 @@ public async Task CanSendPendingConditionsToTopicConfiguredWithMethod(bool useMq
[Theory]
[InlineData(true)]
[InlineData(false)]
- public async Task CanSendDataItemToTopicConfiguredWithMethod2(bool useMqtt5)
+ public async Task CanSendDataItemToTopicConfiguredWithMethod2Async(bool useMqtt5)
{
- var name = nameof(CanSendDataItemToTopicConfiguredWithMethod2) + (useMqtt5 ? "v5" : "v311");
+ var name = nameof(CanSendDataItemToTopicConfiguredWithMethod2Async) + (useMqtt5 ? "v5" : "v311");
var testInput1 = GetEndpointsFromFile(name, "./Resources/DataItems.json");
var testInput2 = GetEndpointsFromFile(name, "./Resources/SimpleEvents.json");
var testInput3 = GetEndpointsFromFile(name, "./Resources/PendingAlarms.json");
@@ -201,7 +200,7 @@ public async Task CanSendDataItemToTopicConfiguredWithMethod2(bool useMqtt5)
await PublisherApi.AddOrUpdateEndpointsAsync(new List
{
new() {
- OpcNodes = nodes.OpcNodes.ToList(),
+ OpcNodes = [.. nodes.OpcNodes],
EndpointUrl = e.EndpointUrl,
UseSecurity = e.UseSecurity,
DataSetWriterGroup = name
@@ -241,9 +240,9 @@ await PublisherApi.AddOrUpdateEndpointsAsync(new List
[Theory]
[InlineData(true)]
[InlineData(false)]
- public async Task CanSendPendingConditionsToTopicConfiguredWithMethod2(bool useMqtt5)
+ public async Task CanSendPendingConditionsToTopicConfiguredWithMethod2Async(bool useMqtt5)
{
- var name = nameof(CanSendPendingConditionsToTopicConfiguredWithMethod2) + (useMqtt5 ? "v5" : "v311");
+ var name = nameof(CanSendPendingConditionsToTopicConfiguredWithMethod2Async) + (useMqtt5 ? "v5" : "v311");
var testInput = GetEndpointsFromFile(name, "./Resources/PendingAlarms.json");
StartPublisher(name, version: useMqtt5 ? MqttVersion.v5 : MqttVersion.v311);
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttPubSubIntegrationTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttPubSubIntegrationTests.cs
index 3373f902a0..91a777a946 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttPubSubIntegrationTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttPubSubIntegrationTests.cs
@@ -39,13 +39,13 @@ protected override void Dispose(bool disposing)
}
[Fact]
- public async Task CanSendDataItemToMqttBrokerTest()
+ public async Task CanSendDataItemToMqttBrokerTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemToMqttBrokerTest), "./Resources/DataItems.json",
- messageType: "ua-data", arguments: new string[] { "--mm=PubSub", "--mdt={TelemetryTopic}/metadatamessage", "--dm=False" },
+ nameof(CanSendDataItemToMqttBrokerTestAsync), "./Resources/DataItems.json",
+ messageType: "ua-data", arguments: ["--mm=PubSub", "--mdt={TelemetryTopic}/metadatamessage", "--dm=False"],
version: MqttVersion.v311);
// Assert
@@ -59,13 +59,13 @@ public async Task CanSendDataItemToMqttBrokerTest()
}
[Fact]
- public async Task CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTest()
+ public async Task CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTest), "./Resources/DataItems.json",
- arguments: new string[] { "--dm", "--mm=DataSetMessages" },
+ nameof(CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTestAsync), "./Resources/DataItems.json",
+ arguments: ["--dm", "--mm=DataSetMessages"],
version: MqttVersion.v5);
// Assert
@@ -78,14 +78,14 @@ public async Task CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTest()
}
[Fact]
- public async Task CanSendDataItemAsDataSetMessagesToMqttBrokerWithCompliantEncodingTest()
+ public async Task CanSendDataItemAsDataSetMessagesToMqttBrokerWithCompliantEncodingTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemAsDataSetMessagesToMqttBrokerWithCompliantEncodingTest),
+ nameof(CanSendDataItemAsDataSetMessagesToMqttBrokerWithCompliantEncodingTestAsync),
"./Resources/DataItems.json", messageType: "ua-deltaframe",
- arguments: new string[] { "-c", "--mm=DataSetMessages" },
+ arguments: ["-c", "--mm=DataSetMessages"],
version: MqttVersion.v311);
// Assert
@@ -98,14 +98,14 @@ public async Task CanSendDataItemAsDataSetMessagesToMqttBrokerWithCompliantEncod
}
[Fact]
- public async Task CanSendDataItemAsRawDataSetsToMqttBrokerWithCompliantEncodingTest()
+ public async Task CanSendDataItemAsRawDataSetsToMqttBrokerWithCompliantEncodingTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemAsRawDataSetsToMqttBrokerWithCompliantEncodingTest),
+ nameof(CanSendDataItemAsRawDataSetsToMqttBrokerWithCompliantEncodingTestAsync),
"./Resources/DataItems.json", messageType: "ua-deltaframe",
- arguments: new string[] { "-c", "--dm=False", "--mm=RawDataSets", "--mdt" },
+ arguments: ["-c", "--dm=False", "--mm=RawDataSets", "--mdt"],
version: MqttVersion.v5);
// Assert
@@ -120,12 +120,12 @@ public async Task CanSendDataItemAsRawDataSetsToMqttBrokerWithCompliantEncodingT
}
[Fact]
- public async Task CanEncodeWithoutReversibleEncodingTest()
+ public async Task CanEncodeWithoutReversibleEncodingTestAsync()
{
// Arrange
// Act
- var (metadata, result) = await ProcessMessagesAndMetadataAsync(nameof(CanEncodeWithoutReversibleEncodingTest),
- "./Resources/SimpleEvents.json", messageType: "ua-data", arguments: new[] { "--mm=PubSub", "--me=Json", "--dm=false" },
+ var (metadata, result) = await ProcessMessagesAndMetadataAsync(nameof(CanEncodeWithoutReversibleEncodingTestAsync),
+ "./Resources/SimpleEvents.json", messageType: "ua-data", arguments: ["--mm=PubSub", "--me=Json", "--dm=false"],
version: MqttVersion.v5);
Assert.Single(result);
@@ -141,10 +141,10 @@ public async Task CanEncodeWithoutReversibleEncodingTest()
var value = m.GetProperty("Payload");
// Variant encoding is the default
- var eventId = value.GetProperty(BasicPubSubIntegrationTests.kEventId).GetProperty("Value");
- var message = value.GetProperty(BasicPubSubIntegrationTests.kMessage).GetProperty("Value");
- var cycleId = value.GetProperty(BasicPubSubIntegrationTests.kCycleIdUri).GetProperty("Value");
- var currentStep = value.GetProperty(BasicPubSubIntegrationTests.kCurrentStepUri).GetProperty("Value");
+ var eventId = value.GetProperty(BasicPubSubIntegrationTests.EventId).GetProperty("Value");
+ var message = value.GetProperty(BasicPubSubIntegrationTests.Message).GetProperty("Value");
+ var cycleId = value.GetProperty(BasicPubSubIntegrationTests.CycleIdUri).GetProperty("Value");
+ var currentStep = value.GetProperty(BasicPubSubIntegrationTests.CurrentStepUri).GetProperty("Value");
Assert.Equal(JsonValueKind.String, eventId.ValueKind);
Assert.Equal(JsonValueKind.String, message.ValueKind);
@@ -158,13 +158,13 @@ public async Task CanEncodeWithoutReversibleEncodingTest()
}
[Fact]
- public async Task CanEncodeWithReversibleEncodingTest()
+ public async Task CanEncodeWithReversibleEncodingTestAsync()
{
// Arrange
// Act
- var (metadata, result) = await ProcessMessagesAndMetadataAsync(nameof(CanEncodeWithReversibleEncodingTest),
+ var (metadata, result) = await ProcessMessagesAndMetadataAsync(nameof(CanEncodeWithReversibleEncodingTestAsync),
"./Resources/SimpleEvents.json", TimeSpan.FromMinutes(2), 4, messageType: "ua-data",
- arguments: new[] { "--mm=PubSub", "--me=JsonReversible", "--dm=False" },
+ arguments: ["--mm=PubSub", "--me=JsonReversible", "--dm=False"],
version: MqttVersion.v311);
var messages = result
@@ -176,20 +176,20 @@ public async Task CanEncodeWithReversibleEncodingTest()
Assert.All(messages, m =>
{
var body = m.GetProperty("Payload");
- var eventId = body.GetProperty(BasicPubSubIntegrationTests.kEventId).GetProperty("Value");
+ var eventId = body.GetProperty(BasicPubSubIntegrationTests.EventId).GetProperty("Value");
Assert.Equal("ByteString", eventId.GetProperty("Type").GetString());
Assert.Equal(JsonValueKind.String, eventId.GetProperty("Body").ValueKind);
- var message = body.GetProperty(BasicPubSubIntegrationTests.kMessage).GetProperty("Value");
+ var message = body.GetProperty(BasicPubSubIntegrationTests.Message).GetProperty("Value");
Assert.Equal("LocalizedText", message.GetProperty("Type").GetString());
Assert.Equal(JsonValueKind.String, message.GetProperty("Body").GetProperty("Text").ValueKind);
Assert.Equal("en-US", message.GetProperty("Body").GetProperty("Locale").GetString());
- var cycleId = body.GetProperty(BasicPubSubIntegrationTests.kCycleIdUri).GetProperty("Value");
+ var cycleId = body.GetProperty(BasicPubSubIntegrationTests.CycleIdUri).GetProperty("Value");
Assert.Equal("String", cycleId.GetProperty("Type").GetString());
Assert.Equal(JsonValueKind.String, cycleId.GetProperty("Body").ValueKind);
- var currentStep = body.GetProperty(BasicPubSubIntegrationTests.kCurrentStepUri).GetProperty("Value");
+ var currentStep = body.GetProperty(BasicPubSubIntegrationTests.CurrentStepUri).GetProperty("Value");
body = currentStep.GetProperty("Body");
Assert.Equal("ExtensionObject", currentStep.GetProperty("Type").GetString());
Assert.Equal("http://opcfoundation.org/SimpleEvents#i=183", body.GetProperty("TypeId").GetString());
@@ -203,12 +203,12 @@ public async Task CanEncodeWithReversibleEncodingTest()
}
[Fact]
- public async Task CanEncodeEventWithCompliantEncodingTest()
+ public async Task CanEncodeEventWithCompliantEncodingTestAsync()
{
// Arrange
// Act
- var (metadata, result) = await ProcessMessagesAndMetadataAsync(nameof(CanEncodeEventWithCompliantEncodingTest),
- "./Resources/SimpleEvents.json", messageType: "ua-data", arguments: new[] { "-c", "--mm=PubSub", "--me=Json" },
+ var (metadata, result) = await ProcessMessagesAndMetadataAsync(nameof(CanEncodeEventWithCompliantEncodingTestAsync),
+ "./Resources/SimpleEvents.json", messageType: "ua-data", arguments: ["-c", "--mm=PubSub", "--me=Json"],
version: MqttVersion.v5);
Assert.Single(result);
@@ -224,10 +224,10 @@ public async Task CanEncodeEventWithCompliantEncodingTest()
var value = m.GetProperty("Payload");
// Variant encoding is the default
- var eventId = value.GetProperty(BasicPubSubIntegrationTests.kEventId).GetProperty("Value");
- var message = value.GetProperty(BasicPubSubIntegrationTests.kMessage).GetProperty("Value");
- var cycleId = value.GetProperty(BasicPubSubIntegrationTests.kCycleIdExpanded).GetProperty("Value");
- var currentStep = value.GetProperty(BasicPubSubIntegrationTests.kCurrentStepExpanded).GetProperty("Value");
+ var eventId = value.GetProperty(BasicPubSubIntegrationTests.EventId).GetProperty("Value");
+ var message = value.GetProperty(BasicPubSubIntegrationTests.Message).GetProperty("Value");
+ var cycleId = value.GetProperty(BasicPubSubIntegrationTests.CycleIdExpanded).GetProperty("Value");
+ var currentStep = value.GetProperty(BasicPubSubIntegrationTests.CurrentStepExpanded).GetProperty("Value");
Assert.Equal(JsonValueKind.String, eventId.ValueKind);
Assert.Equal(JsonValueKind.String, message.ValueKind);
@@ -241,13 +241,13 @@ public async Task CanEncodeEventWithCompliantEncodingTest()
}
[Fact]
- public async Task CanEncodeWithReversibleEncodingAndWithCompliantEncodingTest()
+ public async Task CanEncodeWithReversibleEncodingAndWithCompliantEncodingTestAsync()
{
// Arrange
// Act
- var (metadata, result) = await ProcessMessagesAndMetadataAsync(nameof(CanEncodeWithReversibleEncodingAndWithCompliantEncodingTest),
+ var (metadata, result) = await ProcessMessagesAndMetadataAsync(nameof(CanEncodeWithReversibleEncodingAndWithCompliantEncodingTestAsync),
"./Resources/SimpleEvents.json", TimeSpan.FromMinutes(2), 4, messageType: "ua-data",
- arguments: new[] { "-c", "--mm=PubSub", "--me=JsonReversible" },
+ arguments: ["-c", "--mm=PubSub", "--me=JsonReversible"],
version: MqttVersion.v311);
var messages = result
@@ -259,20 +259,20 @@ public async Task CanEncodeWithReversibleEncodingAndWithCompliantEncodingTest()
Assert.All(messages, m =>
{
var body = m.GetProperty("Payload");
- var eventId = body.GetProperty(BasicPubSubIntegrationTests.kEventId).GetProperty("Value");
+ var eventId = body.GetProperty(BasicPubSubIntegrationTests.EventId).GetProperty("Value");
Assert.Equal(15, eventId.GetProperty("Type").GetInt32());
Assert.Equal(JsonValueKind.String, eventId.GetProperty("Body").ValueKind);
- var message = body.GetProperty(BasicPubSubIntegrationTests.kMessage).GetProperty("Value");
+ var message = body.GetProperty(BasicPubSubIntegrationTests.Message).GetProperty("Value");
Assert.Equal(21, message.GetProperty("Type").GetInt32());
Assert.Equal(JsonValueKind.String, message.GetProperty("Body").GetProperty("Text").ValueKind);
Assert.Equal("en-US", message.GetProperty("Body").GetProperty("Locale").GetString());
- var cycleId = body.GetProperty(BasicPubSubIntegrationTests.kCycleIdExpanded).GetProperty("Value");
+ var cycleId = body.GetProperty(BasicPubSubIntegrationTests.CycleIdExpanded).GetProperty("Value");
Assert.Equal(12, cycleId.GetProperty("Type").GetInt32());
Assert.Equal(JsonValueKind.String, cycleId.GetProperty("Body").ValueKind);
- var currentStep = body.GetProperty(BasicPubSubIntegrationTests.kCurrentStepExpanded).GetProperty("Value");
+ var currentStep = body.GetProperty(BasicPubSubIntegrationTests.CurrentStepExpanded).GetProperty("Value");
body = currentStep.GetProperty("Body");
Assert.Equal(22, currentStep.GetProperty("Type").GetInt32());
Assert.Equal(183, body.GetProperty("TypeId").GetProperty("Id").GetInt32());
@@ -285,13 +285,13 @@ public async Task CanEncodeWithReversibleEncodingAndWithCompliantEncodingTest()
}
[Fact]
- public async Task CanSendPendingConditionsToMqttBrokerTest()
+ public async Task CanSendPendingConditionsToMqttBrokerTestAsync()
{
// Arrange
// Act
- var (metadata, messages) = await ProcessMessagesAndMetadataAsync(nameof(CanSendPendingConditionsToMqttBrokerTest),
+ var (metadata, messages) = await ProcessMessagesAndMetadataAsync(nameof(CanSendPendingConditionsToMqttBrokerTestAsync),
"./Resources/PendingAlarms.json", BasicPubSubIntegrationTests.GetAlarmCondition, messageType: "ua-data",
- arguments: new string[] { "--mm=PubSub", "--dm=False" }, version: MqttVersion.v311);
+ arguments: ["--mm=PubSub", "--dm=False"], version: MqttVersion.v311);
// Assert
var message = Assert.Single(messages);
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttUnifiedNamespaceTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttUnifiedNamespaceTests.cs
index fb3db70837..1527f88b3c 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttUnifiedNamespaceTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Mqtt/ReferenceServer/MqttUnifiedNamespaceTests.cs
@@ -37,22 +37,22 @@ protected override void Dispose(bool disposing)
}
[Fact]
- public async Task CanSendAddressSpaceDataToUnifiedNamespace()
+ public async Task CanSendAddressSpaceDataToUnifiedNamespaceAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendAddressSpaceDataToUnifiedNamespace), "./Resources/DataItems1.json",
+ nameof(CanSendAddressSpaceDataToUnifiedNamespaceAsync), "./Resources/DataItems1.json",
messageCollectionTimeout: TimeSpan.FromMinutes(1), messageCount: 10,
- arguments: new string[] { "--mm=SingleRawDataSet", "--uns=UseBrowseNamesWithNamespaceIndex" }, version: MqttVersion.v5);
+ arguments: ["--mm=SingleRawDataSet", "--uns=UseBrowseNamesWithNamespaceIndex"], version: MqttVersion.v5);
// Assert
Assert.NotEmpty(messages);
var currentTimes = messages.Where(m => m.Topic
- .EndsWith("CanSendAddressSpaceDataToUnifiedNamespace/Objects/Server/ServerStatus/CurrentTime",
+ .EndsWith(nameof(CanSendAddressSpaceDataToUnifiedNamespaceAsync) + "/Objects/Server/ServerStatus/CurrentTime",
StringComparison.InvariantCulture)).ToList();
var outputs = messages.Where(m => m.Topic
- .EndsWith("CanSendAddressSpaceDataToUnifiedNamespace/Objects/23:Boilers/23:Boiler \\x231/23:DrumX001/23:LIX001/23:Output",
+ .EndsWith(nameof(CanSendAddressSpaceDataToUnifiedNamespaceAsync) + "/Objects/23:Boilers/23:Boiler \\x231/23:DrumX001/23:LIX001/23:Output",
StringComparison.InvariantCulture)).ToList();
Assert.NotEmpty(currentTimes);
Assert.NotEmpty(outputs);
@@ -74,22 +74,22 @@ public async Task CanSendAddressSpaceDataToUnifiedNamespace()
}
[Fact]
- public async Task CanSendAddressSpaceDataToUnifiedNamespaceRaw()
+ public async Task CanSendAddressSpaceDataToUnifiedNamespaceRawAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendAddressSpaceDataToUnifiedNamespaceRaw), "./Resources/DataItems1.json",
+ nameof(CanSendAddressSpaceDataToUnifiedNamespaceRawAsync), "./Resources/DataItems1.json",
messageCollectionTimeout: TimeSpan.FromMinutes(1), messageCount: 10,
- arguments: new string[] { "--mm=SingleRawDataSet", "--uns=UseBrowseNames" }, version: MqttVersion.v311);
+ arguments: ["--mm=SingleRawDataSet", "--uns=UseBrowseNames"], version: MqttVersion.v311);
// Assert
Assert.NotEmpty(messages);
var currentTimes = messages.Where(m => m.Topic
- .EndsWith("CanSendAddressSpaceDataToUnifiedNamespaceRaw/Objects/Server/ServerStatus/CurrentTime",
+ .EndsWith(nameof(CanSendAddressSpaceDataToUnifiedNamespaceRawAsync) + "/Objects/Server/ServerStatus/CurrentTime",
StringComparison.InvariantCulture)).ToList();
var outputs = messages.Where(m => m.Topic
- .EndsWith("CanSendAddressSpaceDataToUnifiedNamespaceRaw/Objects/Boilers/Boiler \\x231/DrumX001/LIX001/Output",
+ .EndsWith(nameof(CanSendAddressSpaceDataToUnifiedNamespaceRawAsync) + "/Objects/Boilers/Boiler \\x231/DrumX001/LIX001/Output",
StringComparison.InvariantCulture)).ToList();
Assert.NotEmpty(currentTimes);
Assert.NotEmpty(outputs);
@@ -111,21 +111,21 @@ public async Task CanSendAddressSpaceDataToUnifiedNamespaceRaw()
}
[Fact]
- public async Task CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataSets()
+ public async Task CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataSetsAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataSets), "./Resources/UnifiedNamespace.json",
+ nameof(CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataSetsAsync), "./Resources/UnifiedNamespace.json",
messageCollectionTimeout: TimeSpan.FromMinutes(1), messageCount: 10, version: MqttVersion.v5);
// Assert
Assert.NotEmpty(messages);
var currentTimes = messages.Where(m => m.Topic
- .EndsWith("CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataSets/Objects/Server/ServerStatus/CurrentTime",
+ .EndsWith(nameof(CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataSetsAsync) + "/Objects/Server/ServerStatus/CurrentTime",
StringComparison.InvariantCulture)).ToList();
var outputs = messages.Where(m => m.Topic
- .EndsWith("CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataSets/Objects/Boilers/Boiler \\x231/DrumX001/LIX001/Output",
+ .EndsWith(nameof(CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataSetsAsync) + "/Objects/Boilers/Boiler \\x231/DrumX001/LIX001/Output",
StringComparison.InvariantCulture)).ToList();
Assert.NotEmpty(currentTimes);
Assert.NotEmpty(outputs);
@@ -148,7 +148,7 @@ public async Task CanSendAddressSpaceDataToUnifiedNamespacePerWriterWithRawDataS
}
[Fact]
- public async Task CanSendModelChangeEventsToUnifiedNamespace()
+ public async Task CanSendModelChangeEventsToUnifiedNamespaceAsync()
{
// TODO: Fix
await Task.Delay(1);
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/CommandLineTest.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/CommandLineTest.cs
index 25bf293d06..dea4b8df95 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/CommandLineTest.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/CommandLineTest.cs
@@ -21,7 +21,7 @@ public class CommandLineTest : CommandLineLogger
///
/// Warnings reported by StandaloneCliOptions.
///
- public IList Warnings = new List();
+ public IList Warnings { get; } = [];
public CommandLine CommandLine { get; }
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/PublisherCliTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/PublisherCliTests.cs
index df713f8676..313a80fa18 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/PublisherCliTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/PublisherCliTests.cs
@@ -181,10 +181,10 @@ public void MissingOptionParameterTest(params string[] param)
///
///
[Theory]
- [InlineData(new object[] { new string[] { "-h" } })]
- [InlineData(new object[] { new string[] { "--h" } })]
- [InlineData(new object[] { new string[] { "-help" } })]
- [InlineData(new object[] { new string[] { "--help" } })]
+ [InlineData([new string[] { "-h" }])]
+ [InlineData([new string[] { "--h" }])]
+ [InlineData([new string[] { "-help" }])]
+ [InlineData([new string[] { "--help" }])]
public void HelpOptionParameterTest(string[] param)
{
var result = new CommandLineTest(param);
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/PublisherControllerTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/PublisherControllerTests.cs
index 66ddd12035..546cf3ea0a 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/PublisherControllerTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Runtime/PublisherControllerTests.cs
@@ -22,10 +22,10 @@ public PublisherControllerTests(ITestOutputHelper output) : base(output)
}
[Fact]
- public async Task GetApiKeyAndCertificateTest()
+ public async Task GetApiKeyAndCertificateTestAsync()
{
- const string name = nameof(GetApiKeyAndCertificateTest);
- StartPublisher(name, "./Resources/empty_pn.json", arguments: new string[] { "--mm=PubSub" });
+ const string name = nameof(GetApiKeyAndCertificateTestAsync);
+ StartPublisher(name, "./Resources/empty_pn.json", arguments: ["--mm=PubSub"]);
try
{
var apiKey = await PublisherApi.GetApiKeyAsync();
@@ -44,9 +44,9 @@ public async Task GetApiKeyAndCertificateTest()
}
[Fact]
- public async Task ShutdownTest()
+ public async Task ShutdownTestAsync()
{
- const string name = nameof(ShutdownTest);
+ const string name = nameof(ShutdownTestAsync);
StartPublisher(name, "./Resources/empty_pn.json");
try
{
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/AdvancedPubSubIntegrationTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/AdvancedPubSubIntegrationTests.cs
index a0af3647e0..cbaf4b50e5 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/AdvancedPubSubIntegrationTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/AdvancedPubSubIntegrationTests.cs
@@ -8,7 +8,6 @@ namespace Azure.IIoT.OpcUa.Publisher.Module.Tests.Sdk.ReferenceServer
using Azure.IIoT.OpcUa.Publisher.Module.Tests.Fixtures;
using Azure.IIoT.OpcUa.Publisher.Testing.Fixtures;
using Json.More;
- using Microsoft.VisualStudio.TestPlatform.Utilities;
using System;
using System.Linq;
using System.Text.Json;
@@ -27,13 +26,13 @@ public AdvancedPubSubIntegrationTests(ITestOutputHelper output) : base(output)
}
[Fact]
- public async Task RestartServerTest()
+ public async Task RestartServerTestAsync()
{
var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
- const string name = nameof(RestartServerTest);
+ const string name = nameof(RestartServerTestAsync);
StartPublisher(name, "./Resources/Fixedvalue.json",
- arguments: new string[] { "--mm=PubSub", "--dm=false" }, keepAliveInterval: 1);
+ arguments: ["--mm=PubSub", "--dm=false"], keepAliveInterval: 1);
try
{
// Arrange
@@ -46,7 +45,7 @@ public async Task RestartServerTest()
AssertFixedValueMessage(message);
Assert.NotNull(metadata);
- await server.RestartAsync(WaitUntilDisconnected);
+ await server.RestartAsync(WaitUntilDisconnectedAsync);
_output.WriteLine("Restarted server");
(metadata, messages) = await WaitForMessagesAndMetadataAsync(TimeSpan.FromMinutes(2), 1,
@@ -64,13 +63,13 @@ public async Task RestartServerTest()
}
[Fact]
- public async Task RestartServerWithHeartbeatTest()
+ public async Task RestartServerWithHeartbeatTestAsync()
{
var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
- const string name = nameof(RestartServerWithHeartbeatTest);
+ const string name = nameof(RestartServerWithHeartbeatTestAsync);
StartPublisher(name, "./Resources/Heartbeat2.json",
- arguments: new string[] { "--mm=PubSub", "--dm=false", "--bs=1" }, keepAliveInterval: 1);
+ arguments: ["--mm=PubSub", "--dm=false", "--bs=1"], keepAliveInterval: 1);
try
{
// Arrange
@@ -82,7 +81,7 @@ public async Task RestartServerWithHeartbeatTest()
var message = Assert.Single(messages).Message;
Assert.NotNull(metadata);
- await server.RestartAsync(WaitUntilDisconnected);
+ await server.RestartAsync(WaitUntilDisconnectedAsync);
_output.WriteLine("Restarted server");
(metadata, messages) = await WaitForMessagesAndMetadataAsync(TimeSpan.FromSeconds(10), 1000,
@@ -104,13 +103,13 @@ public async Task RestartServerWithHeartbeatTest()
}
[Fact]
- public async Task RestartServerWithCyclicReadTest()
+ public async Task RestartServerWithCyclicReadTestAsync()
{
var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
- const string name = nameof(RestartServerWithCyclicReadTest);
+ const string name = nameof(RestartServerWithCyclicReadTestAsync);
StartPublisher(name, "./Resources/CyclicRead.json",
- arguments: new string[] { "--mm=PubSub", "--dm=false" }, keepAliveInterval: 1);
+ arguments: ["--mm=PubSub", "--dm=false"], keepAliveInterval: 1);
try
{
// Arrange
@@ -122,7 +121,7 @@ public async Task RestartServerWithCyclicReadTest()
var message = Assert.Single(messages).Message;
Assert.NotNull(metadata);
- await server.RestartAsync(WaitUntilDisconnected);
+ await server.RestartAsync(WaitUntilDisconnectedAsync);
_output.WriteLine("Restarted server");
(metadata, messages) = await WaitForMessagesAndMetadataAsync(TimeSpan.FromSeconds(10), 1000,
@@ -140,13 +139,13 @@ public async Task RestartServerWithCyclicReadTest()
}
[Fact]
- public async Task SwitchServerWithSameWriterGroupTest()
+ public async Task SwitchServerWithSameWriterGroupTestAsync()
{
var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
- const string name = nameof(SwitchServerWithSameWriterGroupTest);
- StartPublisher(name, "./Resources/DataItems.json", arguments: new string[] { "--mm=PubSub", "--dm=false" });
+ const string name = nameof(SwitchServerWithSameWriterGroupTestAsync);
+ StartPublisher(name, "./Resources/DataItems.json", arguments: ["--mm=PubSub", "--dm=false"]);
try
{
// Arrange
@@ -205,12 +204,12 @@ public async Task SwitchServerWithSameWriterGroupTest()
}
[Fact]
- public async Task SwitchServerWithDifferentWriterGroupTest()
+ public async Task SwitchServerWithDifferentWriterGroupTestAsync()
{
var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
- const string name = nameof(SwitchServerWithDifferentWriterGroupTest);
- StartPublisher(name, "./Resources/DataItems2.json", arguments: new string[] { "--mm=PubSub", "--dm=false" });
+ const string name = nameof(SwitchServerWithDifferentWriterGroupTestAsync);
+ StartPublisher(name, "./Resources/DataItems2.json", arguments: ["--mm=PubSub", "--dm=false"]);
try
{
// Arrange
@@ -236,7 +235,7 @@ public async Task SwitchServerWithDifferentWriterGroupTest()
old.Dispose();
// Point to new server
- const string name2 = nameof(SwitchServerWithDifferentWriterGroupTest) + "new";
+ const string name2 = nameof(SwitchServerWithDifferentWriterGroupTestAsync) + "new";
WritePublishedNodes(name2, "./Resources/DataItems2.json");
// Now we should have torn down the other subscription
@@ -275,12 +274,12 @@ public async Task SwitchServerWithDifferentWriterGroupTest()
[InlineData(true, 100)]
[InlineData(false, 1)]
[InlineData(true, 1)]
- public async Task AddNodeToDataSetWriterGroupWithNodeUsingDeviceMethod(bool differentPublishingInterval,
+ public async Task AddNodeToDataSetWriterGroupWithNodeUsingDeviceMethodAsync(bool differentPublishingInterval,
int maxMonitoredItems)
{
var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
- const string name = nameof(AddNodeToDataSetWriterGroupWithNodeUsingDeviceMethod);
+ const string name = nameof(AddNodeToDataSetWriterGroupWithNodeUsingDeviceMethodAsync);
var testInput1 = GetEndpointsFromFile(name, "./Resources/DataItems.json");
var testInput2 = GetEndpointsFromFile(name, "./Resources/DataItems2.json");
if (!differentPublishingInterval)
@@ -288,7 +287,7 @@ public async Task AddNodeToDataSetWriterGroupWithNodeUsingDeviceMethod(bool diff
// Set both to the same so that there is a single writer instead of 2
testInput2[0].OpcNodes[0].OpcPublishingInterval = testInput1[0].OpcNodes[0].OpcPublishingInterval;
}
- StartPublisher(name, arguments: new string[] { "--mm=PubSub", "--dm=false", "--xmi=" + maxMonitoredItems });
+ StartPublisher(name, arguments: ["--mm=PubSub", "--dm=false", "--xmi=" + maxMonitoredItems]);
try
{
var endpoints = await PublisherApi.GetConfiguredEndpointsAsync();
@@ -348,12 +347,12 @@ public async Task AddNodeToDataSetWriterGroupWithNodeUsingDeviceMethod(bool diff
}
[Fact]
- public async Task SwitchServerWithDifferentDataTest()
+ public async Task SwitchServerWithDifferentDataTestAsync()
{
var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
- const string name = nameof(SwitchServerWithDifferentDataTest);
- StartPublisher(name, "./Resources/DataItems.json", arguments: new string[] { "--mm=PubSub", "--dm=false" });
+ const string name = nameof(SwitchServerWithDifferentDataTestAsync);
+ StartPublisher(name, "./Resources/DataItems.json", arguments: ["--mm=PubSub", "--dm=false"]);
try
{
// Arrange
@@ -414,12 +413,12 @@ public async Task SwitchServerWithDifferentDataTest()
}
[Fact]
- public async Task SwitchSecuritySettingsTest()
+ public async Task SwitchSecuritySettingsTestAsync()
{
var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
- const string name = nameof(SwitchSecuritySettingsTest);
- StartPublisher(name, "./Resources/Fixedvalue.json", arguments: new string[] { "--mm=PubSub", "--dm=false", "--aa" },
+ const string name = nameof(SwitchSecuritySettingsTestAsync);
+ StartPublisher(name, "./Resources/Fixedvalue.json", arguments: ["--mm=PubSub", "--dm=false", "--aa"],
securityMode: Models.SecurityMode.SignAndEncrypt);
try
{
@@ -471,21 +470,21 @@ public async Task SwitchSecuritySettingsTest()
}
[Fact]
- public async Task RestartConfigurationTest()
+ public async Task RestartConfigurationTestAsync()
{
using var server = new ReferenceServer();
EndpointUrl = server.EndpointUrl;
for (var cycles = 0; cycles < 3; cycles++)
{
- const string name = nameof(RestartConfigurationTest);
- StartPublisher(name, "./Resources/DataItems.json", arguments: new string[] { "--mm=PubSub", "--dm=false" });
+ const string name = nameof(RestartConfigurationTestAsync);
+ StartPublisher(name, "./Resources/DataItems.json", arguments: ["--mm=PubSub", "--dm=false"]);
try
{
// Arrange
// Act
await WaitForMessagesAndMetadataAsync(TimeSpan.FromSeconds(5), 1, messageType: "ua-data");
- const string name2 = nameof(RestartConfigurationTest) + "new";
+ const string name2 = nameof(RestartConfigurationTestAsync) + "new";
WritePublishedNodes(name2, "./Resources/DataItems2.json");
var diagnostics = await PublisherApi.GetDiagnosticInfoAsync();
for (var i = 0; i < 60 &&
@@ -519,7 +518,7 @@ internal static JsonElement WaitUntilOutput2(JsonElement jsonElement)
return default;
}
- private async Task WaitUntilDisconnected()
+ private async Task WaitUntilDisconnectedAsync()
{
using var cts = new CancellationTokenSource(60000);
while (true)
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/BasicPubSubIntegrationTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/BasicPubSubIntegrationTests.cs
index cc48374dea..a2c7da7570 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/BasicPubSubIntegrationTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/BasicPubSubIntegrationTests.cs
@@ -5,12 +5,9 @@
namespace Azure.IIoT.OpcUa.Publisher.Module.Tests.Sdk.ReferenceServer
{
- using Autofac.Features.Indexed;
- using Azure.IIoT.OpcUa.Publisher.Models;
using Azure.IIoT.OpcUa.Publisher.Module.Tests.Fixtures;
using Azure.IIoT.OpcUa.Publisher.Testing.Fixtures;
using FluentAssertions;
- using Google.Protobuf.WellKnownTypes;
using Json.More;
using System;
using System.Collections.Generic;
@@ -23,12 +20,12 @@ namespace Azure.IIoT.OpcUa.Publisher.Module.Tests.Sdk.ReferenceServer
public class BasicPubSubIntegrationTests : PublisherIntegrationTestBase
{
- internal const string kEventId = "EventId";
- internal const string kMessage = "Message";
- internal const string kCycleIdExpanded = "nsu=http://opcfoundation.org/SimpleEvents;CycleId";
- internal const string kCurrentStepExpanded = "nsu=http://opcfoundation.org/SimpleEvents;CurrentStep";
- internal const string kCycleIdUri = "http://opcfoundation.org/SimpleEvents#CycleId";
- internal const string kCurrentStepUri = "http://opcfoundation.org/SimpleEvents#CurrentStep";
+ internal const string EventId = "EventId";
+ internal const string Message = "Message";
+ internal const string CycleIdExpanded = "nsu=http://opcfoundation.org/SimpleEvents;CycleId";
+ internal const string CurrentStepExpanded = "nsu=http://opcfoundation.org/SimpleEvents;CurrentStep";
+ internal const string CycleIdUri = "http://opcfoundation.org/SimpleEvents#CycleId";
+ internal const string CurrentStepUri = "http://opcfoundation.org/SimpleEvents#CurrentStep";
private readonly ITestOutputHelper _output;
private readonly ReferenceServer _fixture;
@@ -50,13 +47,13 @@ protected override void Dispose(bool disposing)
}
[Fact]
- public async Task CanSendDataItemToIoTHubTest()
+ public async Task CanSendDataItemToIoTHubTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemToIoTHubTest), "./Resources/DataItems.json",
- messageType: "ua-data", arguments: new string[] { "--mm=PubSub", "--dm=false" });
+ nameof(CanSendDataItemToIoTHubTestAsync), "./Resources/DataItems.json",
+ messageType: "ua-data", arguments: ["--mm=PubSub", "--dm=false"]);
// Assert
var message = Assert.Single(messages).Message;
@@ -68,12 +65,12 @@ public async Task CanSendDataItemToIoTHubTest()
}
[Fact]
- public async Task CanSendModelChangeEventsToIoTHubTest()
+ public async Task CanSendModelChangeEventsToIoTHubTestAsync()
{
// Arrange
// Act
- var messages = await ProcessMessagesAsync(nameof(CanSendModelChangeEventsToIoTHubTest), "./Resources/ModelChanges.json",
- TimeSpan.FromMinutes(2), 5, messageType: "ua-data", arguments: new[] { "--mm=PubSub", "--dm=false" });
+ var messages = await ProcessMessagesAsync(nameof(CanSendModelChangeEventsToIoTHubTestAsync), "./Resources/ModelChanges.json",
+ TimeSpan.FromMinutes(2), 5, messageType: "ua-data", arguments: ["--mm=PubSub", "--dm=false"]);
// Assert
Assert.NotEmpty(messages);
@@ -103,14 +100,14 @@ public async Task CanSendModelChangeEventsToIoTHubTest()
}
[Fact]
- public async Task CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTest()
+ public async Task CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTest),
+ nameof(CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTestAsync),
"./Resources/DataItems.json",
- arguments: new string[] { "-c", "--dm", "--mm=DataSetMessages" });
+ arguments: ["-c", "--dm", "--mm=DataSetMessages"]);
// Assert
var message = Assert.Single(messages).Message;
@@ -122,14 +119,14 @@ public async Task CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTest()
}
[Fact]
- public async Task CanSendDataItemButNotMetaDataWhenComplexTypeSystemIsDisabledTest()
+ public async Task CanSendDataItemButNotMetaDataWhenComplexTypeSystemIsDisabledTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemButNotMetaDataWhenMetaDataIsDisabledTest),
+ nameof(CanSendDataItemButNotMetaDataWhenComplexTypeSystemIsDisabledTestAsync),
"./Resources/DataItems.json",
- arguments: new string[] { "-c", "--dct", "--mm=DataSetMessages" });
+ arguments: ["-c", "--dct", "--mm=DataSetMessages"]);
// Assert
var message = Assert.Single(messages).Message;
@@ -141,13 +138,13 @@ public async Task CanSendDataItemButNotMetaDataWhenComplexTypeSystemIsDisabledTe
}
[Fact]
- public async Task CanSendDataItemAsDataSetMessagesToIoTHubWithCompliantEncodingTest()
+ public async Task CanSendDataItemAsDataSetMessagesToIoTHubWithCompliantEncodingTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemAsDataSetMessagesToIoTHubWithCompliantEncodingTest), "./Resources/DataItems.json",
- messageType: "ua-deltaframe", arguments: new string[] { "-c", "--mm=DataSetMessages" });
+ nameof(CanSendDataItemAsDataSetMessagesToIoTHubWithCompliantEncodingTestAsync), "./Resources/DataItems.json",
+ messageType: "ua-deltaframe", arguments: ["-c", "--mm=DataSetMessages"]);
// Assert
var message = Assert.Single(messages).Message;
@@ -159,13 +156,13 @@ public async Task CanSendDataItemAsDataSetMessagesToIoTHubWithCompliantEncodingT
}
[Fact]
- public async Task CanSendDataItemAsRawDataSetsToIoTHubWithCompliantEncodingTest()
+ public async Task CanSendDataItemAsRawDataSetsToIoTHubWithCompliantEncodingTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemAsRawDataSetsToIoTHubWithCompliantEncodingTest), "./Resources/DataItems.json",
- messageType: "ua-deltaframe", arguments: new string[] { "-c", "--dm=False", "--mm=RawDataSets" });
+ nameof(CanSendDataItemAsRawDataSetsToIoTHubWithCompliantEncodingTestAsync), "./Resources/DataItems.json",
+ messageType: "ua-deltaframe", arguments: ["-c", "--dm=False", "--mm=RawDataSets"]);
// Assert
var output = Assert.Single(messages).Message;
@@ -177,14 +174,14 @@ public async Task CanSendDataItemAsRawDataSetsToIoTHubWithCompliantEncodingTest(
}
[Fact]
- public async Task CanEncodeWithoutReversibleEncodingTest()
+ public async Task CanEncodeWithoutReversibleEncodingTestAsync()
{
// Arrange
// Act
var (metadata, result) = await ProcessMessagesAndMetadataAsync(
- nameof(CanEncodeWithoutReversibleEncodingTest),
+ nameof(CanEncodeWithoutReversibleEncodingTestAsync),
"./Resources/SimpleEvents.json", messageType: "ua-data",
- arguments: new[] { "--mm=PubSub", "--me=Json", "--dm=false" }
+ arguments: ["--mm=PubSub", "--me=Json", "--dm=false"]
);
Assert.Single(result);
@@ -200,10 +197,10 @@ public async Task CanEncodeWithoutReversibleEncodingTest()
var value = m.GetProperty("Payload");
// Variant encoding is the default
- var eventId = value.GetProperty(kEventId).GetProperty("Value");
- var message = value.GetProperty(kMessage).GetProperty("Value");
- var cycleId = value.GetProperty(kCycleIdUri).GetProperty("Value");
- var currentStep = value.GetProperty(kCurrentStepUri).GetProperty("Value");
+ var eventId = value.GetProperty(EventId).GetProperty("Value");
+ var message = value.GetProperty(Message).GetProperty("Value");
+ var cycleId = value.GetProperty(CycleIdUri).GetProperty("Value");
+ var currentStep = value.GetProperty(CurrentStepUri).GetProperty("Value");
Assert.Equal(JsonValueKind.String, eventId.ValueKind);
Assert.Equal(JsonValueKind.String, message.ValueKind);
@@ -216,14 +213,14 @@ public async Task CanEncodeWithoutReversibleEncodingTest()
}
[Fact]
- public async Task CanEncodeWithReversibleEncodingTest()
+ public async Task CanEncodeWithReversibleEncodingTestAsync()
{
// Arrange
// Act
var (metadata, result) = await ProcessMessagesAndMetadataAsync(
- nameof(CanEncodeWithReversibleEncodingTest),
+ nameof(CanEncodeWithReversibleEncodingTestAsync),
"./Resources/SimpleEvents.json", TimeSpan.FromMinutes(2), 4, messageType: "ua-data",
- arguments: new[] { "--mm=PubSub", "--me=JsonReversible", "--dm=false" }
+ arguments: ["--mm=PubSub", "--me=JsonReversible", "--dm=false"]
);
var messages = result
@@ -235,20 +232,20 @@ public async Task CanEncodeWithReversibleEncodingTest()
Assert.All(messages, m =>
{
var body = m.GetProperty("Payload");
- var eventId = body.GetProperty(kEventId).GetProperty("Value");
+ var eventId = body.GetProperty(EventId).GetProperty("Value");
Assert.Equal("ByteString", eventId.GetProperty("Type").GetString());
Assert.Equal(JsonValueKind.String, eventId.GetProperty("Body").ValueKind);
- var message = body.GetProperty(kMessage).GetProperty("Value");
+ var message = body.GetProperty(Message).GetProperty("Value");
Assert.Equal("LocalizedText", message.GetProperty("Type").GetString());
Assert.Equal(JsonValueKind.String, message.GetProperty("Body").GetProperty("Text").ValueKind);
Assert.Equal("en-US", message.GetProperty("Body").GetProperty("Locale").GetString());
- var cycleId = body.GetProperty(kCycleIdUri).GetProperty("Value");
+ var cycleId = body.GetProperty(CycleIdUri).GetProperty("Value");
Assert.Equal("String", cycleId.GetProperty("Type").GetString());
Assert.Equal(JsonValueKind.String, cycleId.GetProperty("Body").ValueKind);
- var currentStep = body.GetProperty(kCurrentStepUri).GetProperty("Value");
+ var currentStep = body.GetProperty(CurrentStepUri).GetProperty("Value");
body = currentStep.GetProperty("Body");
Assert.Equal("ExtensionObject", currentStep.GetProperty("Type").GetString());
Assert.Equal("http://opcfoundation.org/SimpleEvents#i=183", body.GetProperty("TypeId").GetString());
@@ -261,14 +258,14 @@ public async Task CanEncodeWithReversibleEncodingTest()
}
[Fact]
- public async Task CanEncodeEventWithCompliantEncodingTestTest()
+ public async Task CanEncodeEventWithCompliantEncodingTestAsync()
{
// Arrange
// Act
var (metadata, result) = await ProcessMessagesAndMetadataAsync(
- nameof(CanEncodeEventWithCompliantEncodingTestTest),
+ nameof(CanEncodeEventWithCompliantEncodingTestAsync),
"./Resources/SimpleEvents.json", messageType: "ua-data",
- arguments: new[] { "-c", "--mm=PubSub", "--me=Json" });
+ arguments: ["-c", "--mm=PubSub", "--me=Json"]);
Assert.Single(result);
@@ -283,10 +280,10 @@ public async Task CanEncodeEventWithCompliantEncodingTestTest()
var value = m.GetProperty("Payload");
// Variant encoding is the default
- var eventId = value.GetProperty(kEventId).GetProperty("Value");
- var message = value.GetProperty(kMessage).GetProperty("Value");
- var cycleId = value.GetProperty(kCycleIdExpanded).GetProperty("Value");
- var currentStep = value.GetProperty(kCurrentStepExpanded).GetProperty("Value");
+ var eventId = value.GetProperty(EventId).GetProperty("Value");
+ var message = value.GetProperty(Message).GetProperty("Value");
+ var cycleId = value.GetProperty(CycleIdExpanded).GetProperty("Value");
+ var currentStep = value.GetProperty(CurrentStepExpanded).GetProperty("Value");
Assert.Equal(JsonValueKind.String, eventId.ValueKind);
Assert.Equal(JsonValueKind.String, message.ValueKind);
@@ -299,14 +296,14 @@ public async Task CanEncodeEventWithCompliantEncodingTestTest()
}
[Fact]
- public async Task CanEncodeWithReversibleEncodingAndWithCompliantEncodingTestTest()
+ public async Task CanEncodeWithReversibleEncodingAndWithCompliantEncodingTestAsync()
{
// Arrange
// Act
var (metadata, result) = await ProcessMessagesAndMetadataAsync(
- nameof(CanEncodeWithReversibleEncodingAndWithCompliantEncodingTestTest),
+ nameof(CanEncodeWithReversibleEncodingAndWithCompliantEncodingTestAsync),
"./Resources/SimpleEvents.json", TimeSpan.FromMinutes(2), 4, messageType: "ua-data",
- arguments: new[] { "-c", "--mm=PubSub", "--me=JsonReversible" });
+ arguments: ["-c", "--mm=PubSub", "--me=JsonReversible"]);
var messages = result
.SelectMany(x => x.Message.GetProperty("Messages").EnumerateArray())
@@ -317,20 +314,20 @@ public async Task CanEncodeWithReversibleEncodingAndWithCompliantEncodingTestTes
Assert.All(messages, m =>
{
var body = m.GetProperty("Payload");
- var eventId = body.GetProperty(kEventId).GetProperty("Value");
+ var eventId = body.GetProperty(EventId).GetProperty("Value");
Assert.Equal(15, eventId.GetProperty("Type").GetInt32());
Assert.Equal(JsonValueKind.String, eventId.GetProperty("Body").ValueKind);
- var message = body.GetProperty(kMessage).GetProperty("Value");
+ var message = body.GetProperty(Message).GetProperty("Value");
Assert.Equal(21, message.GetProperty("Type").GetInt32());
Assert.Equal(JsonValueKind.String, message.GetProperty("Body").GetProperty("Text").ValueKind);
Assert.Equal("en-US", message.GetProperty("Body").GetProperty("Locale").GetString());
- var cycleId = body.GetProperty(kCycleIdExpanded).GetProperty("Value");
+ var cycleId = body.GetProperty(CycleIdExpanded).GetProperty("Value");
Assert.Equal(12, cycleId.GetProperty("Type").GetInt32());
Assert.Equal(JsonValueKind.String, cycleId.GetProperty("Body").ValueKind);
- var currentStep = body.GetProperty(kCurrentStepExpanded).GetProperty("Value");
+ var currentStep = body.GetProperty(CurrentStepExpanded).GetProperty("Value");
body = currentStep.GetProperty("Body");
Assert.Equal(22, currentStep.GetProperty("Type").GetInt32());
Assert.Equal(183, body.GetProperty("TypeId").GetProperty("Id").GetInt32());
@@ -342,16 +339,16 @@ public async Task CanEncodeWithReversibleEncodingAndWithCompliantEncodingTestTes
}
[Fact]
- public async Task CanEncode2EventsWithCompliantEncodingTest()
+ public async Task CanEncode2EventsWithCompliantEncodingTestAsync()
{
var dataSetWriterNames = new HashSet();
// Arrange
// Act
var (metadata, result) = await ProcessMessagesAndMetadataAsync(
- nameof(CanEncode2EventsWithCompliantEncodingTest),
+ nameof(CanEncode2EventsWithCompliantEncodingTestAsync),
"./Resources/SimpleEvents2.json", GetBothEvents, messageType: "ua-data",
- arguments: new[] { "-c", "--mm=PubSub", "--me=Json" });
+ arguments: ["-c", "--mm=PubSub", "--me=Json"]);
Assert.Single(result);
@@ -369,10 +366,10 @@ public async Task CanEncode2EventsWithCompliantEncodingTest()
var value = m.GetProperty("Payload");
// Variant encoding is the default
- var eventId = value.GetProperty(kEventId).GetProperty("Value");
- var message = value.GetProperty(kMessage).GetProperty("Value");
- var cycleId = value.GetProperty(kCycleIdExpanded).GetProperty("Value");
- var currentStep = value.GetProperty(kCurrentStepExpanded).GetProperty("Value");
+ var eventId = value.GetProperty(EventId).GetProperty("Value");
+ var message = value.GetProperty(Message).GetProperty("Value");
+ var cycleId = value.GetProperty(CycleIdExpanded).GetProperty("Value");
+ var currentStep = value.GetProperty(CurrentStepExpanded).GetProperty("Value");
Assert.Equal(JsonValueKind.String, eventId.ValueKind);
Assert.Equal(JsonValueKind.String, message.ValueKind);
@@ -401,13 +398,13 @@ JsonElement GetBothEvents(JsonElement jsonElement)
}
[Fact]
- public async Task CanSendPendingConditionsToIoTHubTest()
+ public async Task CanSendPendingConditionsToIoTHubTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendPendingConditionsToIoTHubTest), "./Resources/PendingAlarms.json", GetAlarmCondition,
- messageType: "ua-data", arguments: new string[] { "--mm=PubSub", "--dm=False" });
+ nameof(CanSendPendingConditionsToIoTHubTestAsync), "./Resources/PendingAlarms.json", GetAlarmCondition,
+ messageType: "ua-data", arguments: ["--mm=PubSub", "--dm=False"]);
// Assert
Assert.NotEmpty(messages);
@@ -421,13 +418,13 @@ public async Task CanSendPendingConditionsToIoTHubTest()
}
[Fact]
- public async Task CanSendExtensionFieldsToIoTHubTest()
+ public async Task CanSendExtensionFieldsToIoTHubTestAsync()
{
// Arrange
// Act
var (metadata, result) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendExtensionFieldsToIoTHubTest), "./Resources/ExtensionFields.json",
- messageType: "ua-data", arguments: new string[] { "--mm=FullNetworkMessages", "--dm=false" });
+ nameof(CanSendExtensionFieldsToIoTHubTestAsync), "./Resources/ExtensionFields.json",
+ messageType: "ua-data", arguments: ["--mm=FullNetworkMessages", "--dm=false"]);
Assert.Single(result);
@@ -459,13 +456,13 @@ public async Task CanSendExtensionFieldsToIoTHubTest()
}
[Fact]
- public async Task CanSendKeyFramesWithExtensionFieldsToIoTHubTest()
+ public async Task CanSendKeyFramesWithExtensionFieldsToIoTHubTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemToIoTHubTest), "./Resources/KeyFrames.json",
- messageType: "ua-data", arguments: new string[] { "--mm=FullNetworkMessages", "--dm=false" });
+ nameof(CanSendDataItemToIoTHubTestAsync), "./Resources/KeyFrames.json",
+ messageType: "ua-data", arguments: ["--mm=FullNetworkMessages", "--dm=false"]);
// Assert
var message = Assert.Single(messages).Message;
@@ -493,13 +490,13 @@ public async Task CanSendKeyFramesWithExtensionFieldsToIoTHubTest()
}
[Fact]
- public async Task CanSendFullAndCompliantNetworkMessageWithEndpointUrlAndApplicationUriToIoTHubTest()
+ public async Task CanSendFullAndCompliantNetworkMessageWithEndpointUrlAndApplicationUriToIoTHubTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendDataItemToIoTHubTest), "./Resources/DataItems.json", messageType: "ua-data",
- arguments: new string[] { "--mm=PubSub", "--fm=true", "--strict" });
+ nameof(CanSendDataItemToIoTHubTestAsync), "./Resources/DataItems.json", messageType: "ua-data",
+ arguments: ["--mm=PubSub", "--fm=true", "--strict"]);
// Assert
var message = Assert.Single(messages).Message;
@@ -525,14 +522,14 @@ public async Task CanSendFullAndCompliantNetworkMessageWithEndpointUrlAndApplica
}
[Fact]
- public async Task CanSendKeyFramesWithExtensionFieldsToIoTHubTestJsonReversible()
+ public async Task CanSendKeyFramesWithExtensionFieldsToIoTHubTestJsonReversibleAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendKeyFramesWithExtensionFieldsToIoTHubTestJsonReversible), "./Resources/KeyFrames.json", messageType: "ua-data",
+ nameof(CanSendKeyFramesWithExtensionFieldsToIoTHubTestJsonReversibleAsync), "./Resources/KeyFrames.json", messageType: "ua-data",
// NOTE: while we --fm and fullnetworkmessage, the keyframes.json overrides this back to PubSub
- arguments: new string[] { "--mm=FullNetworkMessages", "--me=JsonReversible", "--fm=true", "--strict" });
+ arguments: ["--mm=FullNetworkMessages", "--me=JsonReversible", "--fm=true", "--strict"]);
// Assert
var message = Assert.Single(messages).Message;
@@ -572,7 +569,7 @@ public async Task CyclicReadWithAgeTestAsync()
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
nameof(CyclicReadWithAgeTestAsync), "./Resources/CyclicRead.json",
TimeSpan.FromMinutes(1), 10, messageType: "ua-data",
- arguments: new string[] { "--mm=PubSub", "--dm=false" });
+ arguments: ["--mm=PubSub", "--dm=false"]);
// Assert
Assert.Equal(10, messages.Count);
@@ -584,14 +581,14 @@ public async Task CyclicReadWithAgeTestAsync()
}
[Fact]
- public async Task PeriodicHeartbeatTest()
+ public async Task PeriodicHeartbeatTestAsync()
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(PeriodicHeartbeatTest), "./Resources/Heartbeat2.json",
+ nameof(PeriodicHeartbeatTestAsync), "./Resources/Heartbeat2.json",
TimeSpan.FromMinutes(1), 10, messageType: "ua-data",
- arguments: new string[] { "--mm=PubSub", "-c" });
+ arguments: ["--mm=PubSub", "-c"]);
// Assert
Assert.NotNull(metadata);
@@ -626,13 +623,13 @@ public async Task PeriodicHeartbeatTest()
[Theory]
[InlineData(100)]
[InlineData(1)]
- public async Task CanSendKeyFramesToIoTHubTest(int maxMonitoredItems)
+ public async Task CanSendKeyFramesToIoTHubTestAsync(int maxMonitoredItems)
{
// Arrange
// Act
var (metadata, messages) = await ProcessMessagesAndMetadataAsync(
- nameof(CanSendKeyFramesToIoTHubTest), "./Resources/KeyFrames.json", TimeSpan.FromMinutes(2), 11,
- messageType: "ua-data", arguments: new[] { "--dm=false", "--xmi=" + maxMonitoredItems });
+ nameof(CanSendKeyFramesToIoTHubTestAsync), "./Resources/KeyFrames.json", TimeSpan.FromMinutes(2), 11,
+ messageType: "ua-data", arguments: ["--dm=false", "--xmi=" + maxMonitoredItems]);
// Assert
var allDataSetMessages = messages.Select(m => m.Message.GetProperty("Messages")).SelectMany(m => m.EnumerateArray()).ToList();
@@ -678,12 +675,12 @@ internal static void AssertCompliantSimpleEventsMetadata(JsonMessage? metadata)
},
v =>
{
- Assert.Equal(kCycleIdExpanded, v.GetProperty("Name").GetString());
+ Assert.Equal(CycleIdExpanded, v.GetProperty("Name").GetString());
Assert.Equal(12, v.GetProperty("DataType").GetProperty("Id").GetInt32());
},
v =>
{
- Assert.Equal(kCurrentStepExpanded, v.GetProperty("Name").GetString());
+ Assert.Equal(CurrentStepExpanded, v.GetProperty("Name").GetString());
Assert.Equal(183, v.GetProperty("DataType").GetProperty("Id").GetInt32());
Assert.Equal("http://opcfoundation.org/SimpleEvents",
v.GetProperty("DataType").GetProperty("Namespace").GetString());
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/BasicSamplesIntegrationTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/BasicSamplesIntegrationTests.cs
index b01a949c90..35f3f23a28 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/BasicSamplesIntegrationTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/BasicSamplesIntegrationTests.cs
@@ -50,11 +50,11 @@ protected override void Dispose(bool disposing)
}
[Fact]
- public async Task CanSendDataItemToIoTHubTest()
+ public async Task CanSendDataItemToIoTHubTestAsync()
{
// Arrange
// Act
- var messages = await ProcessMessagesAsync(nameof(CanSendDataItemToIoTHubTest),
+ var messages = await ProcessMessagesAsync(nameof(CanSendDataItemToIoTHubTestAsync),
"./Resources/DataItems.json");
// Assert
@@ -69,12 +69,12 @@ public async Task CanSendDataItemToIoTHubTest()
[InlineData(MessageTimestamp.EncodingTimeUtc, HeartbeatBehavior.WatchdogLKG)]
[InlineData(MessageTimestamp.CurrentTimeUtc, HeartbeatBehavior.WatchdogLKVWithUpdatedTimestamps)]
[InlineData(MessageTimestamp.PublishTime, HeartbeatBehavior.PeriodicLKV)]
- public async Task CanSendHeartbeatToIoTHubTest(MessageTimestamp timestamp, HeartbeatBehavior behavior)
+ public async Task CanSendHeartbeatToIoTHubTestAsync(MessageTimestamp timestamp, HeartbeatBehavior behavior)
{
// Arrange
// Act
- var messages = await ProcessMessagesAsync(nameof(CanSendHeartbeatToIoTHubTest) + timestamp, "./Resources/Heartbeat.json",
- TimeSpan.FromMinutes(2), 5, arguments: new[] { "--fm=True", $"--mts={timestamp}", $"--hbb={behavior}" });
+ var messages = await ProcessMessagesAsync(nameof(CanSendHeartbeatToIoTHubTestAsync) + timestamp, "./Resources/Heartbeat.json",
+ TimeSpan.FromMinutes(2), 5, arguments: ["--fm=True", $"--mts={timestamp}", $"--hbb={behavior}"]);
// Assert
Assert.True(messages.Count > 1);
@@ -113,13 +113,13 @@ public async Task CanSendHeartbeatToIoTHubTest(MessageTimestamp timestamp, Heart
[InlineData(HeartbeatBehavior.WatchdogLKV)]
[InlineData(HeartbeatBehavior.WatchdogLKVWithUpdatedTimestamps)]
[InlineData(HeartbeatBehavior.PeriodicLKV)]
- public async Task CanSendHeartbeatWithMIErrorToIoTHubTest(HeartbeatBehavior behavior)
+ public async Task CanSendHeartbeatWithMIErrorToIoTHubTestAsync(HeartbeatBehavior behavior)
{
// Arrange
// Act
- var messages = await ProcessMessagesAsync(nameof(CanSendHeartbeatWithMIErrorToIoTHubTest),
+ var messages = await ProcessMessagesAsync(nameof(CanSendHeartbeatWithMIErrorToIoTHubTestAsync),
"./Resources/HeartbeatErrors.json",
- TimeSpan.FromMinutes(2), 5, arguments: new[] { "--fm=True", $"--hbb={behavior}" });
+ TimeSpan.FromMinutes(2), 5, arguments: ["--fm=True", $"--hbb={behavior}"]);
// Assert
Assert.True(messages.Count > 1);
@@ -134,13 +134,13 @@ public async Task CanSendHeartbeatWithMIErrorToIoTHubTest(HeartbeatBehavior beha
}
[Fact]
- public async Task CanSendDeadbandItemsToIoTHubTest()
+ public async Task CanSendDeadbandItemsToIoTHubTestAsync()
{
// Arrange
// Act
- var messages = await ProcessMessagesAsync(nameof(CanSendDeadbandItemsToIoTHubTest),
+ var messages = await ProcessMessagesAsync(nameof(CanSendDeadbandItemsToIoTHubTestAsync),
"./Resources/Deadband.json",
- TimeSpan.FromMinutes(2), 20, arguments: new[] { "--fm=True" });
+ TimeSpan.FromMinutes(2), 20, arguments: ["--fm=True"]);
// Assert
messages.ForEach(m => _output.WriteLine(m.Topic + m.Message.ToJsonString()));
@@ -180,11 +180,11 @@ public async Task CanSendDeadbandItemsToIoTHubTest()
}
[Fact]
- public async Task CanSendEventToIoTHubTest()
+ public async Task CanSendEventToIoTHubTestAsync()
{
// Arrange
// Act
- var messages = await ProcessMessagesAsync(nameof(CanSendEventToIoTHubTest),
+ var messages = await ProcessMessagesAsync(nameof(CanSendEventToIoTHubTestAsync),
"./Resources/SimpleEvents.json");
// Assert
@@ -199,13 +199,13 @@ public async Task CanSendEventToIoTHubTest()
[Theory]
[InlineData(true)]
[InlineData(false)]
- public async Task CanSendEventToIoTHubTestFullFeaturedMessage(bool useCurrentTime)
+ public async Task CanSendEventToIoTHubTestFullFeaturedMessageAsync(bool useCurrentTime)
{
// Arrange
// Act
var messages = await ProcessMessagesAsync(
- nameof(CanSendEventToIoTHubTestFullFeaturedMessage), "./Resources/SimpleEvents.json",
- arguments: new string[] { "--fm=true", useCurrentTime ? "--mts=CurrentTimeUtc" : "--mts=PublishTime" });
+ nameof(CanSendEventToIoTHubTestFullFeaturedMessageAsync), "./Resources/SimpleEvents.json",
+ arguments: ["--fm=true", useCurrentTime ? "--mts=CurrentTimeUtc" : "--mts=PublishTime"]);
// Assert
var message = Assert.Single(messages).Message;
@@ -217,13 +217,13 @@ public async Task CanSendEventToIoTHubTestFullFeaturedMessage(bool useCurrentTim
}
[Fact]
- public async Task CanEncodeWithReversibleEncodingSamplesTest()
+ public async Task CanEncodeWithReversibleEncodingSamplesTestAsync()
{
// Arrange
// Act
var result = await ProcessMessagesAsync(
- nameof(CanEncodeWithReversibleEncodingSamplesTest), "./Resources/SimpleEvents.json",
- arguments: new[] { "--mm=Samples", "--me=JsonReversible" }
+ nameof(CanEncodeWithReversibleEncodingSamplesTestAsync), "./Resources/SimpleEvents.json",
+ arguments: ["--mm=Samples", "--me=JsonReversible"]
);
var m = Assert.Single(result).Message;
@@ -259,35 +259,33 @@ public async Task CanEncodeWithReversibleEncodingSamplesTest()
Assert.Equal(JsonValueKind.Number, body.GetProperty("Body").GetProperty("Duration").ValueKind);
var json = value
- .GetProperty("Body")
- .GetProperty("Body")
- .GetRawText();
+ .GetProperty("Body")
+ .GetProperty("Body")
+ .GetRawText();
var buffer = Encoding.UTF8.GetBytes(json);
var serviceMessageContext = new ServiceMessageContext();
serviceMessageContext.Factory.AddEncodeableType(typeof(EncodeableDictionary));
- await using (var stream = new MemoryStream(buffer))
- {
- using var decoder = new JsonDecoderEx(stream, serviceMessageContext);
- var actual = new EncodeableDictionary();
- actual.Decode(decoder);
+ await using var stream = new MemoryStream(buffer);
+ using var decoder = new JsonDecoderEx(stream, serviceMessageContext);
+ var actual = new EncodeableDictionary();
+ actual.Decode(decoder);
- Assert.Equal(4, actual.Count);
- Assert.Equal(new[] { kEventId, kMessage, kCycleId, kCurrentStep }, actual.Select(x => x.Key));
- Assert.All(actual.Select(x => x.Value?.Value), Assert.NotNull);
+ Assert.Equal(4, actual.Count);
+ Assert.Equal(new[] { kEventId, kMessage, kCycleId, kCurrentStep }, actual.Select(x => x.Key));
+ Assert.All(actual.Select(x => x.Value?.Value), Assert.NotNull);
- var eof = decoder.ReadDataValue(null);
- Assert.Null(eof);
- }
+ var eof = decoder.ReadDataValue(null);
+ Assert.Null(eof);
}
[Fact]
- public async Task CanSendPendingConditionsToIoTHubTest()
+ public async Task CanSendPendingConditionsToIoTHubTestAsync()
{
// Arrange
// Act
- var messages = await ProcessMessagesAsync(nameof(CanSendPendingConditionsToIoTHubTest),
+ var messages = await ProcessMessagesAsync(nameof(CanSendPendingConditionsToIoTHubTestAsync),
"./Resources/PendingAlarms.json", GetAlarmCondition);
// Assert
@@ -305,11 +303,11 @@ public async Task CanSendPendingConditionsToIoTHubTest()
}
[Fact]
- public async Task CanSendDataItemToIoTHubTestWithDeviceMethod()
+ public async Task CanSendDataItemToIoTHubTestWithDeviceMethodAsync()
{
- const string name = nameof(CanSendDataItemToIoTHubTestWithDeviceMethod);
+ const string name = nameof(CanSendDataItemToIoTHubTestWithDeviceMethodAsync);
var testInput = GetEndpointsFromFile(name, "./Resources/DataItems.json");
- StartPublisher(name, arguments: new string[] { "--mm=FullSamples" }); // Alternative to --fm=True
+ StartPublisher(name, arguments: ["--mm=FullSamples"]); // Alternative to --fm=True
try
{
var endpoints = await PublisherApi.GetConfiguredEndpointsAsync();
@@ -344,9 +342,9 @@ public async Task CanSendDataItemToIoTHubTestWithDeviceMethod()
}
[Fact]
- public async Task CanSendEventToIoTHubTestWithDeviceMethod()
+ public async Task CanSendEventToIoTHubTestWithDeviceMethodAsync()
{
- const string name = nameof(CanSendEventToIoTHubTestWithDeviceMethod);
+ const string name = nameof(CanSendEventToIoTHubTestWithDeviceMethodAsync);
var testInput = GetEndpointsFromFile(name, "./Resources/SimpleEvents.json");
StartPublisher(name);
try
@@ -382,9 +380,9 @@ public async Task CanSendEventToIoTHubTestWithDeviceMethod()
}
[Fact]
- public async Task CanSendPendingConditionsToIoTHubTestWithDeviceMethod()
+ public async Task CanSendPendingConditionsToIoTHubTestWithDeviceMethodAsync()
{
- const string name = nameof(CanSendPendingConditionsToIoTHubTestWithDeviceMethod);
+ const string name = nameof(CanSendPendingConditionsToIoTHubTestWithDeviceMethodAsync);
var testInput = GetEndpointsFromFile(name, "./Resources/PendingAlarms.json");
StartPublisher(name);
try
@@ -430,13 +428,13 @@ public async Task CanSendPendingConditionsToIoTHubTestWithDeviceMethod()
[Theory]
[InlineData(100)]
[InlineData(1)]
- public async Task CanSendDataItemToIoTHubTestWithDeviceMethod2(int maxMonitoredItems)
+ public async Task CanSendDataItemToIoTHubTestWithDeviceMethod2Async(int maxMonitoredItems)
{
- const string name = nameof(CanSendDataItemToIoTHubTestWithDeviceMethod2);
+ const string name = nameof(CanSendDataItemToIoTHubTestWithDeviceMethod2Async);
var testInput1 = GetEndpointsFromFile(name, "./Resources/DataItems.json");
var testInput2 = GetEndpointsFromFile(name, "./Resources/SimpleEvents.json");
var testInput3 = GetEndpointsFromFile(name, "./Resources/PendingAlarms.json");
- StartPublisher(name, arguments: new[] { "--xmi=" + maxMonitoredItems });
+ StartPublisher(name, arguments: ["--xmi=" + maxMonitoredItems]);
try
{
var endpoints = await PublisherApi.GetConfiguredEndpointsAsync();
@@ -459,7 +457,7 @@ await PublisherApi.AddOrUpdateEndpointsAsync(new List
{
new ()
{
- OpcNodes = nodes.OpcNodes.ToList(),
+ OpcNodes = [.. nodes.OpcNodes],
EndpointUrl = e.EndpointUrl,
UseSecurity = e.UseSecurity,
DataSetWriterGroup = name
@@ -503,9 +501,9 @@ await PublisherApi.AddOrUpdateEndpointsAsync(new List
}
[Fact]
- public async Task CanSendPendingConditionsToIoTHubTestWithDeviceMethod2()
+ public async Task CanSendPendingConditionsToIoTHubTestWithDeviceMethod2Async()
{
- const string name = nameof(CanSendPendingConditionsToIoTHubTestWithDeviceMethod2);
+ const string name = nameof(CanSendPendingConditionsToIoTHubTestWithDeviceMethod2Async);
var testInput = GetEndpointsFromFile(name, "./Resources/PendingAlarms.json");
StartPublisher(name);
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/ReverseConnectIntegrationTests.cs b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/ReverseConnectIntegrationTests.cs
index eb5072a3dc..090309dacf 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/ReverseConnectIntegrationTests.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Module/tests/Sdk/ReferenceServer/ReverseConnectIntegrationTests.cs
@@ -35,7 +35,7 @@ public async Task RegisteredReadTestAsync(bool useReverseConnect)
EndpointUrl = server.EndpointUrl;
var name = nameof(RegisteredReadTestAsync) + (useReverseConnect ? "WithReverseConnect" : "NoReverseConnect");
- StartPublisher(name, "./Resources/RegisteredRead.json", arguments: new string[] { "--mm=PubSub", "--dm=false" },
+ StartPublisher(name, "./Resources/RegisteredRead.json", arguments: ["--mm=PubSub", "--dm=false"],
reverseConnectPort: useReverseConnect ? server.ReverseConnectPort : null);
try
{
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Sdk/src/Azure.IIoT.OpcUa.Publisher.Sdk.csproj b/src/Azure.IIoT.OpcUa.Publisher.Sdk/src/Azure.IIoT.OpcUa.Publisher.Sdk.csproj
index da53cbfe5c..c009d845ec 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Sdk/src/Azure.IIoT.OpcUa.Publisher.Sdk.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Sdk/src/Azure.IIoT.OpcUa.Publisher.Sdk.csproj
@@ -1,6 +1,6 @@
- net8.0
+ net9.0
true
true
true
@@ -8,13 +8,13 @@
enable
-
-
-
+
+
+
-
-
-
+
+
+
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Azure.IIoT.OpcUa.Publisher.Service.Cli.csproj b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Azure.IIoT.OpcUa.Publisher.Service.Cli.csproj
index 579493a655..c010f1a7f1 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Azure.IIoT.OpcUa.Publisher.Service.Cli.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Azure.IIoT.OpcUa.Publisher.Service.Cli.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
true
@@ -11,12 +11,12 @@
mcr.microsoft.com/dotnet/runtime:8.0-cbl-mariner2.0-distroless
-
-
-
+
+
+
-
-
+
+
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Program.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Program.cs
index 4326ac6a20..7c3ec9ff95 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Program.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Program.cs
@@ -39,10 +39,8 @@ public static void Main(string[] args)
.AddCommandLine(args)
.Build();
- using (var scope = new Program(config))
- {
- scope.RunAsync(args).Wait();
- }
+ using var scope = new Program(config);
+ scope.RunAsync(args).Wait();
}
///
@@ -1292,7 +1290,6 @@ private async Task MonitorSupervisorsAsync()
///
private async Task UpdateSupervisorAsync(CliOptions options)
{
- var config = BuildDiscoveryConfig(options);
await _client.Registry.UpdateSupervisorAsync(GetSupervisorId(options),
new SupervisorUpdateModel
{
@@ -1456,7 +1453,6 @@ private async Task MonitorDiscoverersAsync(CliOptions options)
///
private async Task UpdateDiscovererAsync(CliOptions options)
{
- var config = BuildDiscoveryConfig(options);
await _client.Registry.UpdateDiscovererAsync(GetDiscovererId(options),
new DiscovererUpdateModel
{
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Runtime/Configuration.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Runtime/Configuration.cs
index bf0a6c7337..e9e208d7a2 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Runtime/Configuration.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/cli/Runtime/Configuration.cs
@@ -73,7 +73,7 @@ private Func> BuildTokenProvider()
var scope = $"{serviceAppId}/.default";
var tokenProvider = new TokenProvider(clientId, instance, tenantId);
- return () => tokenProvider.GetTokenAsync(new[] { scope }, false);
+ return () => tokenProvider.GetTokenAsync([scope], false);
}
}
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk.csproj b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk.csproj
index a2fdf271eb..f69a0e4ef8 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk.csproj
@@ -1,6 +1,6 @@
- net8.0
+ net9.0
true
true
true
@@ -8,14 +8,14 @@
enable
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/Extensions/HistoryServiceApiEx.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/Extensions/HistoryServiceApiEx.cs
index 8318b9ddea..60c2c78194 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/Extensions/HistoryServiceApiEx.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/Extensions/HistoryServiceApiEx.cs
@@ -29,7 +29,7 @@ public static async Task> HistoryReadAllValuesAs
var result = await client.HistoryReadValuesAsync(endpointId, request).ConfigureAwait(false);
return await HistoryReadAllRemainingValuesAsync(client, endpointId, request.Header,
result.ContinuationToken, result.History?.AsEnumerable()
- ?? Enumerable.Empty()).ConfigureAwait(false);
+ ?? []).ConfigureAwait(false);
}
///
@@ -46,7 +46,7 @@ public static async Task> HistoryReadAllModified
var result = await client.HistoryReadModifiedValuesAsync(endpointId, request).ConfigureAwait(false);
return await HistoryReadAllRemainingValuesAsync(client, endpointId, request.Header,
result.ContinuationToken, result.History?.AsEnumerable()
- ?? Enumerable.Empty()).ConfigureAwait(false);
+ ?? []).ConfigureAwait(false);
}
///
@@ -63,7 +63,7 @@ public static async Task> HistoryReadAllValuesAt
var result = await client.HistoryReadValuesAtTimesAsync(endpointId, request).ConfigureAwait(false);
return await HistoryReadAllRemainingValuesAsync(client, endpointId, request.Header,
result.ContinuationToken, result.History?.AsEnumerable()
- ?? Enumerable.Empty()).ConfigureAwait(false);
+ ?? []).ConfigureAwait(false);
}
///
@@ -80,7 +80,7 @@ public static async Task> HistoryReadAllProcesse
var result = await client.HistoryReadProcessedValuesAsync(endpointId, request).ConfigureAwait(false);
return await HistoryReadAllRemainingValuesAsync(client, endpointId, request.Header,
result.ContinuationToken, result.History?.AsEnumerable()
- ?? Enumerable.Empty()).ConfigureAwait(false);
+ ?? []).ConfigureAwait(false);
}
///
@@ -97,7 +97,7 @@ public static async Task> HistoryReadAllEventsAs
var result = await client.HistoryReadEventsAsync(endpointId, request).ConfigureAwait(false);
return await HistoryReadAllRemainingEventsAsync(client, endpointId, request.Header,
result.ContinuationToken, result.History?.AsEnumerable()
- ?? Enumerable.Empty()).ConfigureAwait(false);
+ ?? []).ConfigureAwait(false);
}
///
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/SignalR/ICallbackRegistrar.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/SignalR/ICallbackRegistrar.cs
index d7092bd564..9791621d3a 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/SignalR/ICallbackRegistrar.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/SignalR/ICallbackRegistrar.cs
@@ -44,9 +44,9 @@ public IDisposable Register(
(T0?)args[0]
);
}, this, method,
- new Type[] {
+ [
typeof(T0)
- });
+ ]);
}
}
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/SignalR/SignalRHubClient.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/SignalR/SignalRHubClient.cs
index 6e7e1026e9..1fdbcd9a55 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/SignalR/SignalRHubClient.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.Sdk/src/SignalR/SignalRHubClient.cs
@@ -30,7 +30,7 @@ public SignalRHubClient(IOptions options,
_jsonSettings = jsonSettings;
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
- _clients = new Dictionary();
+ _clients = [];
_lock = new SemaphoreSlim(1, 1);
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi.csproj b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi.csproj
index 5364a1f2aa..bdf52df70d 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi.csproj
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi.csproj
@@ -1,7 +1,7 @@
Exe
- net8.0
+ net9.0
true
true
true
@@ -16,22 +16,22 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Filters/ExceptionsFilterAttribute.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Filters/ExceptionsFilterAttribute.cs
index ad9d28576f..4a0b78023b 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Filters/ExceptionsFilterAttribute.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Filters/ExceptionsFilterAttribute.cs
@@ -56,44 +56,44 @@ public override void OnException(ExceptionContext context)
.GetService();
switch (context.Exception)
{
- case ResourceNotFoundException re:
+ case ResourceNotFoundException:
context.Result = GetResponse(HttpStatusCode.NotFound,
context.Exception, summarizer);
break;
- case ResourceInvalidStateException ri:
+ case ResourceInvalidStateException:
context.Result = GetResponse(HttpStatusCode.Forbidden,
context.Exception, summarizer);
break;
- case ResourceConflictException ce:
+ case ResourceConflictException:
context.Result = GetResponse(HttpStatusCode.Conflict,
context.Exception, summarizer);
break;
- case UnauthorizedAccessException ue:
- case SecurityException se:
+ case UnauthorizedAccessException:
+ case SecurityException:
context.Result = GetResponse(HttpStatusCode.Unauthorized,
context.Exception, summarizer);
break;
case MethodCallStatusException mcs:
context.Result = new ObjectResult(mcs.Details.ToProblemDetails());
break;
- case SerializerException sre:
- case MethodCallException mce:
- case BadRequestException br:
- case ArgumentException are:
+ case SerializerException:
+ case MethodCallException:
+ case BadRequestException:
+ case ArgumentException:
context.Result = GetResponse(HttpStatusCode.BadRequest,
context.Exception, summarizer);
break;
- case NotImplementedException ne:
- case NotSupportedException ns:
+ case NotImplementedException:
+ case NotSupportedException:
context.Result = GetResponse(HttpStatusCode.NotImplemented,
context.Exception, summarizer);
break;
- case TimeoutException te:
+ case TimeoutException:
context.Result = GetResponse(HttpStatusCode.RequestTimeout,
context.Exception, summarizer);
break;
- case SocketException sex:
- case IOException ce:
+ case SocketException:
+ case IOException:
context.Result = GetResponse(HttpStatusCode.BadGateway,
context.Exception, summarizer);
break;
@@ -116,15 +116,15 @@ public override void OnException(ExceptionContext context)
// one of the above.
//
- case ServerBusyException se:
+ case ServerBusyException:
context.Result = GetResponse(HttpStatusCode.TooManyRequests,
context.Exception, summarizer);
break;
- case ResourceOutOfDateException re:
+ case ResourceOutOfDateException:
context.Result = GetResponse(HttpStatusCode.PreconditionFailed,
context.Exception, summarizer);
break;
- case ExternalDependencyException ex:
+ case ExternalDependencyException:
context.Result = GetResponse(HttpStatusCode.ServiceUnavailable,
context.Exception, summarizer);
break;
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/ApplicationsHub.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/ApplicationsHub.cs
index 65c4a97d4a..4aa614fca3 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/ApplicationsHub.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/ApplicationsHub.cs
@@ -14,7 +14,5 @@ namespace Azure.IIoT.OpcUa.Publisher.Service.WebApi
///
[MapTo("events/v2/applications/events")]
[Authorize(Policy = Policies.CanRead)]
- public class ApplicationsHub : Hub
- {
- }
+ public class ApplicationsHub : Hub;
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/DiscoverersHub.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/DiscoverersHub.cs
index 5239bf995a..74ad5d7466 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/DiscoverersHub.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/DiscoverersHub.cs
@@ -14,7 +14,5 @@ namespace Azure.IIoT.OpcUa.Publisher.Service.WebApi
///
[MapTo("events/v2/discovery/events")]
[Authorize(Policy = Policies.CanRead)]
- public class DiscoverersHub : Hub
- {
- }
+ public class DiscoverersHub : Hub;
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/EndpointsHub.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/EndpointsHub.cs
index 07067a8590..e007d4f03c 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/EndpointsHub.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/EndpointsHub.cs
@@ -14,7 +14,5 @@ namespace Azure.IIoT.OpcUa.Publisher.Service.WebApi
///
[MapTo("events/v2/endpoints/events")]
[Authorize(Policy = Policies.CanRead)]
- public class EndpointsHub : Hub
- {
- }
+ public class EndpointsHub : Hub;
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/GatewaysHub.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/GatewaysHub.cs
index a40931db32..e740fea82f 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/GatewaysHub.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/GatewaysHub.cs
@@ -14,7 +14,5 @@ namespace Azure.IIoT.OpcUa.Publisher.Service.WebApi
///
[MapTo("events/v2/gateways/events")]
[Authorize(Policy = Policies.CanRead)]
- public class GatewaysHub : Hub
- {
- }
+ public class GatewaysHub : Hub;
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/PublishersHub.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/PublishersHub.cs
index 20abae729c..3d6b44ea94 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/PublishersHub.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/PublishersHub.cs
@@ -14,7 +14,5 @@ namespace Azure.IIoT.OpcUa.Publisher.Service.WebApi
///
[MapTo("events/v2/publishers/events")]
[Authorize(Policy = Policies.CanRead)]
- public class PublishersHub : Hub
- {
- }
+ public class PublishersHub : Hub;
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/SupervisorsHub.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/SupervisorsHub.cs
index 1872c110fb..dd95760526 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/SupervisorsHub.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Hubs/SupervisorsHub.cs
@@ -14,7 +14,5 @@ namespace Azure.IIoT.OpcUa.Publisher.Service.WebApi
///
[MapTo("events/v2/supervisors/events")]
[Authorize(Policy = Policies.CanRead)]
- public class SupervisorsHub : Hub
- {
- }
+ public class SupervisorsHub : Hub;
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Runtime/Security.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Runtime/Security.cs
index cdac6b4b1b..b2c3e2feaf 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Runtime/Security.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/Runtime/Security.cs
@@ -62,7 +62,7 @@ public static IServiceCollection AddAuthentication(this IServiceCollection servi
var clientId = context.GetService>()?.Value.ClientId;
return new ConfigureNamedOptions(JwtBearerDefaults.AuthenticationScheme,
options => options.TokenValidationParameters.ValidAudiences =
- clientId == null ? Enumerable.Empty() : clientId.YieldReturn());
+ clientId == null ? [] : clientId.YieldReturn());
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(_ => { }, _ => { },
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/MapToAttribute.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/MapToAttribute.cs
index b70a091b8b..ae354ddf2d 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/MapToAttribute.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/MapToAttribute.cs
@@ -10,21 +10,16 @@ namespace Azure.IIoT.OpcUa.Publisher.Service.WebApi.SignalR
///
/// Metadata for hub
///
+ ///
+ /// Create attribute
+ ///
+ ///
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
- public sealed class MapToAttribute : Attribute
+ public sealed class MapToAttribute(string route) : Attribute
{
- ///
- /// Create attribute
- ///
- ///
- public MapToAttribute(string route)
- {
- Route = route;
- }
-
///
/// Mapping
///
- public string Route { get; }
+ public string Route { get; } = route;
}
}
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/SignalRBuilderEx.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/SignalRBuilderEx.cs
index 0f726eb9e6..53da32f32e 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/SignalRBuilderEx.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/SignalRBuilderEx.cs
@@ -54,7 +54,7 @@ public static T AddNewtonsoftJson(this T builder) where T : ISignalRBuilder
if (!set.IsProperSupersetOf(settings.Converters))
{
options.PayloadSerializerSettings.Converters =
- set.MergeWith(settings.Converters).ToList();
+ [.. set.MergeWith(settings.Converters)];
}
}));
return builder;
diff --git a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/SignalRHub.cs b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/SignalRHub.cs
index 497d02e40f..a6ffb6d9f3 100644
--- a/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/SignalRHub.cs
+++ b/src/Azure.IIoT.OpcUa.Publisher.Service.WebApi/src/SignalR/SignalRHub.cs
@@ -44,7 +44,7 @@ public async Task BroadcastAsync(string method, object[] arguments,
try
{
await _hub.Clients.All.SendCoreAsync(method,
- arguments ?? Array.Empty