Thursday, March 10, 2022

Custom EF Core Function to Use Transact-SQL AT TIME ZONE

In this post, let's see how we can write a Custom EF Core Function to Use Transact-SQL AT TIME ZONE.

Consider the below example. I have the following Order entity in my DbContext.

public class Order
{
    public int Id { get; set; }
 
    public DateTimeOffset OrderDate { get; set; }
}

Now I have the following Extension method to Convert a given DateTimeOffset to a given TimeZone.

public static class DateTimeExtensions
{
    public static DateTimeOffset ConvertToTimeZone(this DateTimeOffset dateTimeOffset, string timeZone)
    {
        TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
        DateTime datetime = TimeZoneInfo.ConvertTimeFromUtc(dateTimeOffset.UtcDateTime, timeZoneInfo);
 
        return new DateTimeOffset(datetime, timeZoneInfo.GetUtcOffset(datetime));
    }
}

Now consider the below query.

var timeZone = "Eastern Standard Time";
 
var orders = await context.Orders
    .Select(x => new
    {
        OrderDate = x.OrderDate,
        ConvertedOrderDate = x.OrderDate.ConvertToTimeZone(timeZone)
    })
    .ToListAsync();

Note for ConvertedOrderDate, I am using the above CLR extension method. 

And when I run this query, the generated SQL statement is going to look like below.

SELECT [o].[OrderDate]
FROM [Orders] AS [o]

And with the below result.

OrderDate                     | ConvertedOrderDate
------------------------------| ------------------------------
20/02/2022 12:00:00 am +00:00 | 19/02/2022 7:00:00 pm -05:00

In the SQL statements EF generated, you can see it doesn't contain anything on ConvertedOrderDate or TimeZone conversion. That's because EF can't translate my CLR extension method into SQL statements. And if we have used this extension method in a Where statement (instead of Select), EF is going to loudly throw an error saying "Translation of method 'DateTimeExtensions.ConvertToTimeZone' failed". So here basically the TimeZone conversion was done In Memory.

And for these kinds of scenarios, we can use this feature in EF, where we can say how a method should get translated into SQL.

First, I am creating a static class with the following method.

public static class EfFunctions
{
    public static DateTimeOffset ConvertToTimeZone(DateTimeOffset dateTimeOffset, [NotParameterized] string timeZone)
        => throw new NotImplementedException("This method should be implemented in EF.");
}

We don't provide any implementation here.

Now we need to instruct EF on how to translate this method.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    MethodInfo methodInfo = typeof(EfFunctions).GetMethod(nameof(EfFunctions.ConvertToTimeZone));
    modelBuilder
        .HasDbFunction(methodInfo)
        .HasTranslation(x =>
        {
            ColumnExpression columnExpression = x.First() as ColumnExpression;
 
            SqlConstantExpression timeZoneExpression = x.Skip(1).First() as SqlConstantExpression;
 
            string timeZoneLiteralValue = timeZoneExpression.TypeMapping.GenerateSqlLiteral(timeZoneExpression.Value);
 
            SqlFragmentExpression valueExpression =
                new($"{columnExpression.Table.Alias}.{columnExpression.Name} AT TIME ZONE {timeZoneLiteralValue} AS DATETIMEOFFSET");
 
            return new SqlFunctionExpression(
                "CAST",
                new List<SqlExpression>() { valueExpression },
                false,
                new List<bool>() { false, false, false },
                typeof(DateTimeOffset),
                null
            );
    });
}

Here I am using Transact-SQL CAST and AT TIME ZONE to generate the proper SQL statements for TimeZone conversion.

And now I am changing my query as follows.

var timeZone = "Eastern Standard Time";
 
var orders = await context.Orders
    .Select(x => new
    {
        OrderDate = x.OrderDate,
        ConvertedOrderDate = EfFunctions.ConvertToTimeZone(x.OrderDate, timeZone)
    })
    .ToListAsync();
This time, for ConvertedOrderDate, I am using the EF Function we just wrote. 

And now when we execute the query, EF is creating the following SQL statement.
SELECT [o].[OrderDate], CAST(o.OrderDate AT TIME ZONE N'Eastern Standard Time' AS DATETIMEOFFSET) AS [ConvertedOrderDate]
FROM [Orders] AS [o]
With the following result as above.
OrderDate                     | ConvertedOrderDate
------------------------------| ------------------------------
20/02/2022 12:00:00 am +00:00 | 19/02/2022 7:00:00 pm -05:00
Hope this helps.


Happy Coding.

Regards,
Jaliya

Tuesday, March 1, 2022

C# 11.0 Preview: Parameter Null Checking

You can now try out some C# 11.0 Preview features if you have the latest RTM version of Visual Studio and .NET SDK (Visual Studio 2022 17.1 and .NET SDK 6.0.200 respectively) installed in your machine. And by the way, Visual Studio 2022 17.2 Preview 1 and .NET 7 Preview 1 are also available if you are interested.

In this post let's have a look at a nice feature that's available with C# 11.0, which is improved Parameter Null Checking.

First, make sure you have set <LangVersion> to preview in your .csproj file.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <LangVersion>preview</LangVersion>
  </PropertyGroup>
</Project>

Consider the below code where you are doing a null check of parameters inside a method.

Prior to C# 10,

static void PrintFullName(Person person)
{
    if (person == null)
    {
        throw new ArgumentNullException(nameof(person));
    }
    
    // Or the following
    //person = person ?? throw new ArgumentNullException(nameof(person));
    
    Console.WriteLine($"FullName: {person.FirstName} {person.LastName}");
}

With C# 10,

static void PrintFullName(Person person)
{
    ArgumentNullException.ThrowIfNull(person);
 
    Console.WriteLine($"FullName: {person.FirstName} {person.LastName}");
}

You have to write some extra code (even though it's just a one-line) to achieve the goal. With C# 11.0, we can basically skip that line by doing something like below.

static void PrintFullName(Person person!!)
{
    Console.WriteLine($"FullName: {person.FirstName} {person.LastName}");
}

Note the bang-bang operator, !! positioned after the parameter name. This will cause the C# compiler to emit null checking code for that parameter behind the scene. When multiple parameters contain the bang-bang operator, !!, null checks will occur in the same order as the parameters are declared.

And if we pass null to this method, we will get the exception we used to throw explicitly before.

Unhandled exception.System.ArgumentNullException: Value cannot be null. (Parameter 'person')
at<PrivateImplementationDetails>.Throw(String paramName)
at<PrivateImplementationDetails>.ThrowIfNull(Object argument, String paramName)
More read: 

Do try out C# 11.0!

Happy Coding.

Regards,
Jaliya

Important Update: 2022-04-13

This feature has been removed from C# 11.0:

Tuesday, February 22, 2022

Azure API Management with Developer Pricing Tier: 504 Gateway Timeout

If you are using Azure API Management with Developer Pricing Tier and it's getting deployed/managed using Azure Resource Manager (ARM) APIs (https://management.azure.com) and your APIs has large schema, you are very likely to get 504 Gateway Timeout errors upon resource management/deployments. 

This is because ARM APIs impose a 2-minute timeout on all operations, and if the API is large, the operation can take more than 2 minutes. Most of the time that's because of SQL bottleneck, as the APIM Developer Pricing Tier uses the Basic SQL Tier which has very limited processing and storage capacity.

Solutions/workarounds,
  • Use your APIM instances' Management API (https://apimname.management.azure-api.net) instead of ARM APIs (https://management.azure.com) to manage your APIM. Direct Management API calls run for as long as needed and are not subject to timeouts.
  • Upgrade APIM instances to larger SKUs. With larger SKU’s we would not have the same issue as those have larger processing and storage capacity.
  • Watch out for what you are returning in your APIs. You might be returning more properties than you really need to. Removing them will reduce the schema size.
As far as I know, Microsoft has plans to make all these ARM operations asynchronous in the near future (no ETA currently), so we are not limited by ARM timeouts.

Hope this will save someone some research time.

Happy Coding.

Regards,
Jaliya

Thursday, February 10, 2022

System.Text.Json.JsonSerializer: Serialize Properties of Derived Classes

Did you know by default JsonSerializer doesn't serialize Properties of Derived Classes?

Say we have the following classes.

public class Person
{
    public string Name { get; set; }
}
 
public class Student : Person
{
    public int StudentId { get; set; }
}

I am creating a Student, but I am assigning it to a Person.

Person person = new Student
{
    Name = "John Doe",
    StudentId = 1
};

Now if I serialize this using Json.NET,

var options = new Newtonsoft.Json.JsonSerializerSettings
{
    Formatting = Newtonsoft.Json.Formatting.Indented,
};
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(person, options));

I am getting the following output. The correct underline type is serialized.

{
  "StudentId": 1,
  "Name": "John Doe"
}

Now if I serialize the same using JsonSerializer,

var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(person, options));

I am getting the following output. You can see it has only serialized the properties that are in the Parent class.

{
  "Name": "John Doe"
}

Now we can change this behavior using one of two ways.

  1. Call an overload of Serialize and ask to use type at run time
  2. Declare the object to be serialized as an object

var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true };

// Call an overload of Serialize that lets you specify the type at run time:
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(person, person.GetType(), options));

// Declare the object to be serialized as object
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize<object>(person, options));

And now we can see the correct underline type is getting serialized.

{
  "StudentId": 1,
  "Name": "John Doe"
}

Hope this helps.

Happy Coding.

Regards,
Jaliya

Friday, February 4, 2022

Visual Studio 17.1 Preview 5: Streamlined File Scoped Namespacing

This is a quick post on a very nice feature that got introduced with Visual Studio Version 17.1.0 Preview 5.0 (released on February 1, 2022).

I am using .NET 6/C# 10.0 in most of my projects and I have been updating the source files to use File Scoped Namespaces. I have been adding a semicolon at the end of the namespace name and then I had to manually delete unnecessary curly braces. And that was tiring. 

Converting to File Scoped Namespaces

But I no longer have to do that, Hooray! With the Visual Studio Version 17.1.0 Preview 5.0, I can just add the semicolon at the end of the namespace name, and Visual Studio takes care of the rest automatically. I just love this!

If you are planning on migrating your code to use File Scoped Namespaces, I would highly recommend doing so with the latest Visual Studio 2022 Preview, it's going to save you a lot of time.

Happy Coding.

Regards,
Jaliya

Wednesday, February 2, 2022

Azure Automation Runbook: Execute SQL Scripts and Capture Print Statements

In my last post, I wrote about how we can execute SQL Scripts on an Azure SQL Database with Managed Identities using an Azure Automation Runbook. In this post, let's see how we can Capture the Print Statements in the SQL script, so we can output those.

Consider the following Stored Procedure.

CREATE OR ALTER PROC dbo.TestSelectStoredProcedure 
(
    @Param1 INT,
    @Param2 VARCHAR(100) 
)
AS
BEGIN
PRINT CONCAT('Param1: ', @Param1)
PRINT CONCAT('Param2: ', @Param2)
END

I need to execute this script and capture the Print messages, so I can output those. In this post, I am not going to explain how we can execute a SQL script from an Azure Automation Runbook, (for that you can read this post: Azure Automation Runbook: Execute SQL Scripts with Managed Identities).

My Runbook is PowerShell 7.1 (preview). This approach would still work if you are using PowerShell 5.1 Runtime.

Now to capture the messages the SP is printing, we need to register SqlInfoMessageEventHandler to the SqlConnection as follows.

# Reading from variables
$AzureSqlServer = Get-AutomationVariable -Name "AzureSqlServer"
$ApplicationDatabase = Get-AutomationVariable -Name "ApplicationDatabase"
$ClientId = Get-AutomationVariable -Name "AzureSqlManagedIdentityId"
 
# Getting AccessToken for User assigned Managed Identity
# Note: Query Parameter now includes the client_Id
$Resource = "https://database.windows.net/"
$QueryParameter = "?resource=$Resource&client_Id=$ClientId"
$Url = $env:IDENTITY_ENDPOINT + $QueryParameter
$Url = $env:IDENTITY_ENDPOINT + $QueryParameter
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" 
$Headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER) 
$Headers.Add("Metadata", "True") 
$Content =[System.Text.Encoding]::Default.GetString((Invoke-WebRequest `
	-UseBasicParsing `
	-Uri $Url `
	-Method 'GET' `
	-Headers $Headers).RawContentStream.ToArray()) | ConvertFrom-Json 
$AccessToken = $Content.access_token 
 
# PowerShell/ADO.NET
$SqlConnection = New-Object System.Data.SqlClient.SQLConnection  
$SqlConnection.ConnectionString = "Server=$AzureSqlServer;Initial Catalog=$ApplicationDatabase;Connect Timeout=30" 
$SqlConnection.AccessToken = $AccessToken 
$Events = new-object System.Collections.Generic.List[Object]
$Handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] { param($sender, $event) $Events.Add($event) }
$SqlConnection.add_InfoMessage($Handler); 
$SqlConnection.FireInfoMessageEventOnUserErrors = $true;
$SqlConnection.Open();
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = "exec dbo.TestStoredProcedure @Param1=100, @Param2='Hello World'"
$SqlCommand.ExecuteNonQuery() | Out-Null
ForEach($event in $Events)
{
    Write-Output $event.Message
}
$SqlConnection.Close();
And now when I test this Runbook, I am seeing the following output as expected.
SQL Script Print Messages Being Outputted
Hope this helps.

Happy Coding.

Regards,
Jaliya

Tuesday, January 25, 2022

Azure Automation Runbook: Execute SQL Scripts with Managed Identities

In this post, let's see how we can execute SQL Scripts on an Azure SQL Database with Managed Identities using an Azure Automation Runbook.

I am using PowerShell with ADO.NET instead of Invoke-Sqlcmd, because Invoke-Sqlcmd doesn't support Azure AD Authentication (via an AccessToken).

For the purpose of the demo, I have created the following SP on the target database, which we are going to be executing.

CREATE OR ALTER PROC dbo.TestStoredProcedure 
(
    @Param1 INT,
    @Param2 VARCHAR(100) 
)
AS
BEGIN
SELECT @Param1 As Data1, @Param2 as Data2
END

The first step is to create an Automation Account. In Azure, search for Automation Accounts and click on Create.

Create an Automation Account
I have selected a Subscription, Resource Group, Region and given it a name.

Create an Automation Account: Managed Identities
This is an important step. This is where we are selecting Managed Identities for this Automation Account. For now, I am going to uncheck both the options (System assigned and User assigned) and clicking on Review + Create (or you can proceed through the Wizard, you should be fine with the defaults for the purpose of this post).

Once the Automation Account is created, we are all set to go.

System assigned Managed Identity

First, let's have a look at how to execute a SQL Script System assigned Managed Identity. First step is enabling System assigned Managed Identity in the Automation Account as below.

Automation Account: System assigned Managed Identity
Once that's saved, we need to grant this System assigned Managed Identity the access to our database. The name of the System assigned Managed Identity is the name of the Automation Account. 
CREATE USER [aa-demo] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [aa-demo];
ALTER ROLE db_datawriter ADD MEMBER [aa-demo];
ALTER ROLE db_ddladmin ADD MEMBER [aa-demo];
GO
 
EXEC sp_addrolemember 'db_datareader', 'aa-demo'
EXEC sp_addrolemember 'db_datawriter', 'aa-demo'
EXEC sp_addrolemember 'db_ddladmin', 'aa-demo'
GRANT EXECUTE ON SCHEMA::dbo TO [aa-demo]
We can run the above query to create and grant access to our System assigned Managed Identity. Note: The query needs to be executed after connecting to the database using an Azure AD login.

Now I am adding some variables to my Automation Account as follows. One for the Azure SQL Server and the other for the name of the Database.
Automation Account: Variables
Next, I am creating a Runbook in Automation Account. 
Create a Runbook
I have selected PowerShell 7.1 (preview). And I am adding the following script.
# Reading from variables
$AzureSqlServer = Get-AutomationVariable -Name "AzureSqlServer"
$ApplicationDatabase = Get-AutomationVariable -Name "ApplicationDatabase"
    
# Getting AccessToken for System assigned Managed Identity
$Resource = "https://database.windows.net/"
$QueryParameter = "?resource=$Resource"
$Url = $env:IDENTITY_ENDPOINT + $QueryParameter
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" 
$Headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER) 
$Headers.Add("Metadata", "True") 
$Content =[System.Text.Encoding]::Default.GetString((Invoke-WebRequest `
    -UseBasicParsing `
    -Uri $Url `
    -Method 'GET' `
    -Headers $Headers).RawContentStream.ToArray()) | ConvertFrom-Json 
$AccessToken = $Content.access_token 
    
# PowerShell/ADO.NET Connected Architecture
$SqlConnection = New-Object System.Data.SqlClient.SQLConnection  
$SqlConnection.ConnectionString = "Server=$AzureSqlServer;Initial Catalog=$ApplicationDatabase;Connect Timeout=30" 
$SqlConnection.AccessToken = $AccessToken 
$SqlCommand = new-object System.Data.SqlClient.SqlCommand("exec dbo.TestStoredProcedure @Param1=100, @Param2='Hello World'", $SqlConnection);
$SqlConnection.Open();
$SqlDataReader = $SqlCommand.ExecuteReader()
$Results = @()
while ($SqlDataReader.Read())
{
    $Row = @{}
    for ($i = 0; $i -lt $SqlDataReader.FieldCount; $i++)
    {
        $Row[$SqlDataReader.GetName($i)] = $SqlDataReader.GetValue($i)
    }
    $Results += new-object psobject -property $Row
}
$SqlConnection.Close()
Write-Output $Results
And that's it. Now when I test this, I am seeing the following output:
Using System assigned Managed Identity: Output
That's working. 

User assigned Managed Identity

Now let's have a look at how to get things done using User Assigned Managed Identity. I am going back to our Automation Account and assigning a User assigned Managed Identity. I have already created a User assigned Managed Identity and I am just going to add it in.

Automation Account: User assigned Managed Identity

Sametime I have added another variable to the Automation Account to hold the ClientId/ObjectId the User assigned Managed Identity we just assigned.

Now we need to grant this User assigned Managed Identity the access to our SQL Database. We could follow the same steps as we did above for System assigned Managed Identity. But this time, I am going to go for a different approach, just to show our options.

I am navigating to the SQL Server where our database is in, and setting our User assigned Managed Identity as the Azure AD admin under SQL Server settings.

AAD Admin
Once that's saved, let's modify our Runbook as follows.
# Reading from variables
$AzureSqlServer = Get-AutomationVariable -Name "AzureSqlServer"
$ApplicationDatabase = Get-AutomationVariable -Name "ApplicationDatabase"
$ClientId = Get-AutomationVariable -Name "AzureSqlManagedIdentityId"
 
# Getting AccessToken for User assigned Managed Identity
# Note: Query Parameter now includes the client_Id
$Resource = "https://database.windows.net/"
$QueryParameter = "?resource=$Resource&client_Id=$ClientId"
$Url = $env:IDENTITY_ENDPOINT + $QueryParameter
$Url = $env:IDENTITY_ENDPOINT + $QueryParameter
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" 
$Headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER) 
$Headers.Add("Metadata", "True") 
$Content =[System.Text.Encoding]::Default.GetString((Invoke-WebRequest `
	-UseBasicParsing `
	-Uri $Url `
	-Method 'GET' `
	-Headers $Headers).RawContentStream.ToArray()) | ConvertFrom-Json 
$AccessToken = $Content.access_token 
 
# PowerShell/ADO.NET Dicconnected Architecture
$SqlConnection = New-Object System.Data.SqlClient.SQLConnection  
$SqlConnection.ConnectionString = "Server=$AzureSqlServer;Initial Catalog=$ApplicationDatabase;Connect Timeout=30" 
$SqlConnection.AccessToken = $AccessToken 
$SqlCommand = New-Object System.Data.SqlClient.SqlCommand("dbo.TestStoredProcedure", $SqlConnection)
$SqlCommand.CommandType = [System.Data.CommandType]::StoredProcedure
$SqlCommand.Parameters.AddWithValue("@Param1", 100) | Out-Null
$SqlCommand.Parameters.AddWithValue("@Param2", "Hello World") | Out-Null
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCommand
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet) | Out-Null
$SqlConnection.Close()
Write-Output $DataSet.Tables[0]
Note: When using User assigned Managed Identity we need to pass in the client_id to AccessToken request (this is not required when using System assigned Managed Identity as it will automatically get resolved). And I have changed PowerShell/ADO.NET to use the Disconnected Architecture to show how to use that approach as well.

And now let's test this. I am seeing the following output:

Using User assigned Managed Identity: Output
And that's also working nicely.

Now you can publish the Runbook and schedule it the way you want.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, January 20, 2022

Azure Service Bus Simple Request-Reply Pattern

In this post let's have a look at how to implement Simple Request-Reply Pattern with Azure Service Bus.

So first have a look at what this Simple Request-Reply Pattern is. While the Service Buses are used mainly for asynchronous processing, there can be scenarios where the message Publisher/Sender needs to wait for a reply from Consumer/Receiver to the message they sent before proceeding. And that's where the Simple Request-Reply Pattern comes into the picture.

Let's go by an example.

Say a Sender sends the following message into a particular queue and a Receiver is consuming it. The sender populates the Input and expects the Consumer to populate the Output for it to proceed further.

public record ApplicationMessage(string Input)
{
    public string? Output { get; set; }
}

So how do we achieve this?

ServiceBusMessage has this ReplyTo Property where the Sender can use to set the address of an entity to send its replies to, something like below.

Sender

ServiceBusAdministrationClient serviceBusAdministrationClient = new(Configuration.CONNECTION_STRING);

// Temporary Queue for Receiver to send their replies into
string replyQueueName = Guid.NewGuid().ToString();
await serviceBusAdministrationClient.CreateQueueAsync(new CreateQueueOptions(replyQueueName)
{
    AutoDeleteOnIdle = TimeSpan.FromSeconds(300)
});
    
// Sending the message
await using ServiceBusClient serviceBusClient = new(Configuration.CONNECTION_STRING);
ServiceBusSender serviceBusSender = serviceBusClient.CreateSender(Configuration.QUEUE_NAME);
    
ApplicationMessage applicationMessage = new("John");
ServiceBusMessage serviceBusMessage = new(JsonSerializer.SerializeToUtf8Bytes(applicationMessage))
{
    ContentType = "application/json",
    ReplyTo = replyQueueName,
};
await serviceBusSender.SendMessageAsync(serviceBusMessage);

Then after sending the message, Sender needs to look for replies in Queue: replyQueueName.

// Creating a receiver and waiting for the Receiver to reply
ServiceBusReceiver serviceBusReceiver = serviceBusClient.CreateReceiver(replyQueueName);
ServiceBusReceivedMessage serviceBusReceivedMessage = await serviceBusReceiver.ReceiveMessageAsync(TimeSpan.FromSeconds(60));
    
if (serviceBusReceivedMessage == null)
{
    WriteLine("Error: Didn't receive a response.");
    return;
}
    
applicationMessage = JsonSerializer.Deserialize<ApplicationMessage>(serviceBusReceivedMessage.Body.ToString());

Consumer

From the Consumer, it's easy. It just needs to send the reply to the entity specified in the incoming ServiceBusMessage.ReplyTo.

await using ServiceBusClient serviceBusClient = new(Configuration.CONNECTION_STRING);
ServiceBusProcessor serviceBusProcessor = serviceBusClient.CreateProcessor(Configuration.QUEUE_NAME);
    
serviceBusProcessor.ProcessMessageAsync += async args =>
{
    // Message received
    ApplicationMessage applicationMessage = JsonSerializer.Deserialize<ApplicationMessage>(args.Message.Body.ToString());
    
    WriteLine($"Message Received: {applicationMessage}.\n");
    
    // Process the message/Update the Output
    applicationMessage.Output = $"Hello {applicationMessage.Input}!.";
    
    // Sending the reply
    ServiceBusSender serviceBusSender = serviceBusClient.CreateSender(args.Message.ReplyTo);
    ServiceBusMessage serviceBusMessage = new(JsonSerializer.Serialize(applicationMessage));
    await serviceBusSender.SendMessageAsync(serviceBusMessage);
};
And when we run this, the output would be something like below.
Simple Request-Reply Pattern Output
You can find the sample code through the below link.

More Read,
   Message Routing and Correlation

Hope this helps.

Happy Coding.

Regards,
Jaliya

Friday, January 14, 2022

Running .NET 6 Isolated Azure Functions in Azure

In this post, let's see how we can run .NET 6 Isolated (Out-of-process) Azure Functions in Azure. 

If you are new to .NET 6 Isolated (Out-of-process) Azure Functions, you can read this post: .NET 6 and Azure Functions.

Let's start off by Creating a Function App. Here you need to select these options.

  • Runtime Stack: .NET
  • Version: 6
Create .NET 6 Function App
Now you can follow the Wizard and create the Function App. Once the Function App is created, we need to deploy a .NET 6 Isolated (Out-of-process) Azure Function App. I am not going to show that step, let's assume we just deployed a sample .NET 6 Isolated (Out-of-process) Azure Function App.

And now, when we navigate into the Function App from Azure, we should be seeing an error, something like this: Microsoft.Azure.WebJobs.Script: Did not find functions with language [dotnet].
Microsoft.Azure.WebJobs.Script: Did not find functions with language [dotnet].
And the reason for this is, by default when Azure creates .NET 6 Function App, it sets FUNCTIONS_WORKER_RUNTIME as dotnet.
FUNCTIONS_WORKER_RUNTIME
In order to run Azure Functions in Isolated (Out-of-process) mode, we need to set FUNCTIONS_WORKER_RUNTIME to dotnet-isolated.

And that should be it. Now the Azure Function is all set up to run in Isolated (Out-of-process) mode.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, January 6, 2022

Great Start to the Year: Visual Studio 17.1 Preview 2 is Now Available

It's another year and a newer preview version of Visual Studio 2022 is already out, Visual Studio 2022 version 17.1 Preview 2.  This Preview version got shipped with some very nice features related to,
  • .NET Productivity
  • Git Tooling
  • Code Editor
  • IDE
  • Test tools
  • And more
These include some features that I have been waiting for so long.

.NET Productivity: Go to Definition, Navigate to the Original Source File


This is my favorite of them all and it's a fantastic feature. Now when we do Go to Definition, we are being navigated to the original source file. This is tremendously helpful in situations like we are exploring .NET APIs.

For example, say I need to go to the definition of AddDbContext<TContext>(...)
Go to Definition in Visual Studio 17.1 Preview 2
I can see the full implementation, whereas in prior versions, I am not seeing the method body.
Go to Definition in Earlier Version of Visual Studio

Git Tooling: Enable line-staging support


This one is another favorite. All this time, after doing a change in a file, we could only stage the whole file, not hunks. This feature has been there in most of the other Git tools out there for so many years, but was lacking in Visual Studio Git experience. Now finally, it's arrived.

This feature is not enabled by default, you need to explicitly turn this on. You can do it by navigating into Tools -> Options -> Environment -> Preview Features.
Enable line-staging support
And then we can stage hunks individually if we want to.
Stage Changes/Hunks

Editor: Code Cleanup on Save


Another nice One. With this feature we don't have to do  Ctrl+K, Ctrl+E (code cleanup) explicitly. Visual Studio will do the Code Cleanup on File upon Save automatically. And we can even choose which Profile to be used for the Code Cleanup. This feature again is not enabled by default, you need to explicitely enable it. You can do it by navigating into Tools -> Options -> Text Editor -> Code Cleanup.
Code Cleanup on Save
Aren't these nice?

Read more about all the new features in Visual Studio 17.1 Preview 2,

Happy Coding and Happy New year everyone!

Regards,
Jaliya