Skip to content
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions dotnet/Azure.Iot.Operations.sln
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Iot.Operations.Connec
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PollingTelemetryConnectorTemplate", "templates\PollingTelemetryConnector\PollingTelemetryConnectorTemplate.csproj", "{698D0245-18C6-37E9-08F6-E8EADCBA0880}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleRpcClient", "samples\SampleRpcClient\SampleRpcClient\SampleRpcClient.csproj", "{8931AAF6-627F-4598-B059-D51102F28F88}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleRpcServer", "samples\SampleRpcServer\SampleRpcServer\SampleRpcServer.csproj", "{9DC14638-1801-40B9-9FFC-2F883B1C7CDB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -227,6 +231,14 @@ Global
{698D0245-18C6-37E9-08F6-E8EADCBA0880}.Debug|Any CPU.Build.0 = Debug|Any CPU
{698D0245-18C6-37E9-08F6-E8EADCBA0880}.Release|Any CPU.ActiveCfg = Release|Any CPU
{698D0245-18C6-37E9-08F6-E8EADCBA0880}.Release|Any CPU.Build.0 = Release|Any CPU
{8931AAF6-627F-4598-B059-D51102F28F88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8931AAF6-627F-4598-B059-D51102F28F88}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8931AAF6-627F-4598-B059-D51102F28F88}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8931AAF6-627F-4598-B059-D51102F28F88}.Release|Any CPU.Build.0 = Release|Any CPU
{9DC14638-1801-40B9-9FFC-2F883B1C7CDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9DC14638-1801-40B9-9FFC-2F883B1C7CDB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9DC14638-1801-40B9-9FFC-2F883B1C7CDB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9DC14638-1801-40B9-9FFC-2F883B1C7CDB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -270,6 +282,8 @@ Global
{4992415C-ABB2-2284-D6CD-8FE01910092F} = {4DDB0B28-1830-4B6F-8A10-FB37874D4D57}
{C527ECCE-FBE1-4FBC-9987-F94BACC904F2} = {CE9A7664-594B-43EB-AA48-606B88411FC9}
{698D0245-18C6-37E9-08F6-E8EADCBA0880} = {4636D1F8-ACA6-4138-8EC0-1FF71CAF3A3B}
{8931AAF6-627F-4598-B059-D51102F28F88} = {0F2D6563-6660-4FE7-A936-E15CBFBE3BC0}
{9DC14638-1801-40B9-9FFC-2F883B1C7CDB} = {0F2D6563-6660-4FE7-A936-E15CBFBE3BC0}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F2687BCD-45E3-4094-9656-BF183C816BA0}
Expand Down
21 changes: 21 additions & 0 deletions dotnet/samples/SampleRpcClient/SampleRpcClient/PayloadObject.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace SampleRpcClient
{
public class PayloadObject
{
[JsonPropertyName("SomeField")]
public string? SomeField { get; set; }

[JsonPropertyName("OtherField")]
public string? OtherField { get; set; }
}
}
35 changes: 35 additions & 0 deletions dotnet/samples/SampleRpcClient/SampleRpcClient/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Diagnostics;
using Azure.Iot.Operations.Mqtt.Session;
using Azure.Iot.Operations.Protocol;
using Azure.Iot.Operations.Protocol.Connection;
using Microsoft.Extensions.Configuration;
using SampleRpcClient;

string commandName = "someCommandName";

var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();

var mqttDiag = Convert.ToBoolean(configuration["mqttDiag"]);
if (mqttDiag) Trace.Listeners.Add(new ConsoleTraceListener());
await using MqttSessionClient mqttClient = new(new MqttSessionClientOptions { EnableMqttLogging = mqttDiag });
ApplicationContext applicationContext = new();

await using SampleCommandInvoker rpcInvoker = new(applicationContext, mqttClient, commandName, new Utf8JsonSerializer());

await mqttClient.ConnectAsync(MqttConnectionSettings.FromEnvVars());

var payload = new PayloadObject()
{
SomeField = "someValue",
OtherField = "someOtherValue"
};

PayloadObject response = (await rpcInvoker.InvokeCommandAsync(payload)).Response;
Console.WriteLine("Received RPC response");
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.Iot.Operations.Protocol;
using Azure.Iot.Operations.Protocol.RPC;

namespace SampleRpcClient
{
[CommandTopic("rpc/command-samples/{commandName}")]
public class SampleCommandInvoker : CommandInvoker<PayloadObject, PayloadObject>
{
public SampleCommandInvoker(ApplicationContext applicationContext, IMqttPubSubClient mqttClient, string commandName, IPayloadSerializer serializer) : base(applicationContext, mqttClient, commandName, serializer)
{
TopicTokenMap["commandName"] = commandName;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\Azure.Iot.Operations.Mqtt\Azure.Iot.Operations.Mqtt.csproj" />
<ProjectReference Include="..\..\..\src\Azure.Iot.Operations.Protocol\Azure.Iot.Operations.Protocol.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Buffers;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Iot.Operations.Protocol;
using Azure.Iot.Operations.Protocol.Models;

namespace SampleRpcClient;

public class EmptyJson
{
}

public class Utf8JsonSerializer : IPayloadSerializer
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please just add the Utf8JsonSerializer into the SDK?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather not. This library's core is not about serialization. If we pin ourselves to any particular serialization package (even System.Text.Json) we open ourselves up to inevitable security issues from that library.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've already gone through security reviews for this library where we were explicitly told that this is the correct way to handle serialization libraries. Changing course now may require another round of security reviews.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As the code generation, would create this class I don't see the point, in the end tooling from us would cause this dependency in the application of the customer. Also, System.Text.Json is part of dotnet framework and no separate nuget anymore and used in other places also.

{
protected static readonly JsonSerializerOptions _jsonSerializerOptions = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

public const string ContentType = "application/json";

public const MqttPayloadFormatIndicator PayloadFormatIndicator = MqttPayloadFormatIndicator.CharacterData;

public T FromBytes<T>(ReadOnlySequence<byte> payload, string? contentType, MqttPayloadFormatIndicator payloadFormatIndicator)
where T : class
{
if (contentType != null && contentType != ContentType)
{
throw new AkriMqttException($"Content type {contentType} is not supported by this implementation; only {ContentType} is accepted.")
{
Kind = AkriMqttErrorKind.HeaderInvalid,
HeaderName = "Content Type",
HeaderValue = contentType,
IsShallow = false,
IsRemote = false,
};
}

try
{
if (payload.IsEmpty)
{
if (typeof(T) != typeof(EmptyJson))
{
throw AkriMqttException.GetPayloadInvalidException();
}

return (new EmptyJson() as T)!;
}

Utf8JsonReader reader = new(payload);
return JsonSerializer.Deserialize<T>(ref reader, _jsonSerializerOptions)!;
}
catch (Exception)
{
throw AkriMqttException.GetPayloadInvalidException();
}
}

public SerializedPayloadContext ToBytes<T>(T? payload)
where T : class
{
try
{
if (typeof(T) == typeof(EmptyJson))
{
return new(ReadOnlySequence<byte>.Empty, ContentType, PayloadFormatIndicator);
}

return new(new(JsonSerializer.SerializeToUtf8Bytes(payload, _jsonSerializerOptions)), ContentType, PayloadFormatIndicator);
}
catch (Exception)
{
throw AkriMqttException.GetPayloadInvalidException();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"mqttDiag": true
}
21 changes: 21 additions & 0 deletions dotnet/samples/SampleRpcServer/SampleRpcServer/PayloadObject.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace SampleRpcServer
{
public class PayloadObject
{
[JsonPropertyName("SomeField")]
public string? SomeField { get; set; }

[JsonPropertyName("OtherField")]
public string? OtherField { get; set; }
}
}
49 changes: 49 additions & 0 deletions dotnet/samples/SampleRpcServer/SampleRpcServer/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.Diagnostics;
using Azure.Iot.Operations.Mqtt.Session;
using Azure.Iot.Operations.Protocol;
using Azure.Iot.Operations.Protocol.Connection;
using Microsoft.Extensions.Configuration;
using SampleRpcServer;

string commandName = "someCommandName";

var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();

var mqttDiag = Convert.ToBoolean(configuration["mqttDiag"]);
if (mqttDiag) Trace.Listeners.Add(new ConsoleTraceListener());
await using MqttSessionClient mqttClient = new(new MqttSessionClientOptions { EnableMqttLogging = mqttDiag });
ApplicationContext applicationContext = new();

await mqttClient.ConnectAsync(MqttConnectionSettings.FromEnvVars());

await using SampleCommandExecutor rpcExecutor = new(applicationContext, mqttClient, commandName, new Utf8JsonSerializer())
{
OnCommandReceived = (request, cancellationToken) =>
{
Console.WriteLine("Received RPC request");

var responsePayload = new PayloadObject()
{
SomeField = request.Request.SomeField,
OtherField = request.Request.OtherField,
};

// Echo the payload back to the sender
return Task.FromResult(new Azure.Iot.Operations.Protocol.RPC.ExtendedResponse<PayloadObject>()
{
Response = responsePayload
});
}
};

await rpcExecutor.StartAsync();

await Task.Delay(TimeSpan.FromMinutes(1));




Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.Iot.Operations.Protocol;
using Azure.Iot.Operations.Protocol.RPC;

namespace SampleRpcServer
{
[CommandTopic("rpc/command-samples/{commandName}")]
public class SampleCommandExecutor : CommandExecutor<PayloadObject, PayloadObject>
{
public SampleCommandExecutor(ApplicationContext applicationContext, IMqttPubSubClient mqttClient, string commandName, IPayloadSerializer serializer) : base(applicationContext, mqttClient, commandName, serializer)
{
TopicTokenMap["commandName"] = commandName;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Azure.Iot.Operations.Mqtt\Azure.Iot.Operations.Mqtt.csproj" />
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use this as real customer example and use the nugets instead of the project reference

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure that matters for this exercise, but sure, I can do that.

<ProjectReference Include="..\..\..\src\Azure.Iot.Operations.Protocol\Azure.Iot.Operations.Protocol.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Loading
Loading