<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Memory dumps of a developer</title><link>https://www.techrepository.in:443/</link><description>Articles and tutorials on .NET Core,  ASP.NET MVC, Kendo UI, Windows 10, Windows Mobile, Orchard</description><item><title>Connecting Azure Blob Storage account using Managed Identity</title><link>https://www.techrepository.in:443/blog/posts/connecting-storage-account-using-mi</link><description>&lt;p&gt;In the previous post, we saw that we can connect to Azure KeyVault from ASP.NET Core application using the default credentials. If you haven't read that, please find it here&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/blog/posts/manage-application-settings-with-azure-keyvault" target="_blank" rel="noopener" title="Manage application settings with Azure KeyVault"&gt;Manage application settings with Azure KeyVault&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;But this is not a secure way of doing things obviously due to security concerns. In order to overcome this, the recommended approach is used to Managed Identity in Azure. This will work only if your application is hosted in Azure. It is similar to a service principal which connects on your app's behalf to communicate with other resources&lt;/p&gt;
&lt;h3&gt;Create Managed Identity&lt;/h3&gt;
&lt;p&gt;The first step is to create a Managed Identity resource in Azure and then give read permission for this identity in the Keyvault which you need to communicate&lt;/p&gt;
&lt;p&gt;You can refer to the official documentation given below to perform this step&lt;/p&gt;
&lt;p&gt;&lt;a href="https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview" target="_blank" rel="noopener" title="Managed identities for Azure resources"&gt;Managed identities for Azure resources&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Connecting to KeyVault from ASP.NET Core Web App&lt;/h3&gt;
&lt;p&gt;In my sample code, I want to connect to a storage account using MI, I have added the necessary configuration entries is my appsettings.json. This can change depending our your requirement&lt;/p&gt;
&lt;p&gt;
&lt;!--more--&gt;
&lt;pre&gt;&lt;code class="language-json"&gt;"AzureStorage": {&lt;br&gt;    "AccountName": "gab22demostorage",&lt;br&gt;    "ContainerName": "file-container"&lt;br&gt;    &lt;br&gt;  },&lt;br&gt;"AzureKeyVault": {&lt;br&gt;    "keyvault-url": "https://gab22demo-rg.vault.azure.net/",&lt;br&gt;    "mi-client-id": "your mi id here"&lt;br&gt;  }, &amp;nbsp;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, in my method where I want to connect to the storage account, add the below code&lt;/p&gt;
&lt;pre&gt;&lt;code class="language-csharp"&gt;
var accountName = _configuration["AzureStorage:AccountName"];&lt;br&gt;var containerName = _configuration["AzureStorage:ContainerName"];&lt;br&gt;var miClientId = _configuration["AzureKeyVault:mi-client-id"];&lt;br&gt;&lt;br&gt;// Construct the blob container endpoint from the arguments.&lt;br&gt;string containerEndpoint = $"https://{accountName}.blob.core.windows.net/{containerName}";&lt;br&gt;&lt;br&gt;// Get a credential and create a client object for the blob container.&lt;br&gt;BlobContainerClient blobContainer = new BlobContainerClient(new Uri(containerEndpoint),&lt;br&gt;	new ManagedIdentityCredential(miClientId));&lt;br&gt;&lt;br&gt;foreach (var itm in products)&lt;br&gt;{&lt;br&gt;	BlobClient blobClient = blobContainer.GetBlobClient($"uploads/{itm.ImageFileName}");&lt;br&gt;        using (var memoryStream = new MemoryStream())&lt;br&gt;        {&lt;br&gt;        	await blobClient.DownloadToAsync(memoryStream);&lt;br&gt;                var bytes = memoryStream.ToArray();&lt;br&gt;                var b64String = Convert.ToBase64String(bytes);&lt;br&gt;                itm.ImageUri = "data:image/png;base64," + b64String;&lt;br&gt;	}&lt;br&gt;}&lt;br&gt;&lt;br&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What we are doing basically here is&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;reading the configuration from appsettings.json file&lt;/li&gt;
&lt;li&gt;connecting to the storage account using MI&lt;/li&gt;
&lt;li&gt;iterates through the blob container to download the image file&lt;code class="language-csharp"&gt;
&lt;span style="font-family: Verdana, Arial, Helvetica, sans-serif;"&gt;&lt;span style="white-space: normal;"&gt;

&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;</description><pubDate>Fri, 09 Dec 2022 07:57:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/connecting-storage-account-using-mi</guid></item><item><title>Securing Azure KeyVault connections using Managed Identity</title><link>https://www.techrepository.in:443/blog/posts/securing-azure-keyvault-using-mi</link><description>&lt;p&gt;In the previous post we saw that we can connect to Azure KeyVault from ASP.NET Core application using the default credentials. If you haven't read that, please find it here&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/blog/posts/manage-application-settings-with-azure-keyvault" target="_blank" rel="noopener" title="Manage application settings with Azure KeyVault"&gt;Manage application settings with Azure KeyVault&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;But this is not a secure way of doing things obviously due to security concerns. In order to overcome this, the recommended approach is used to Managed Identity in Azure. This will work only if your application is hosted in Azure. It is similar to a service principal which connects on your app's behalf to communicate with other resources&lt;/p&gt;
&lt;h3&gt;Create Managed Identity&lt;/h3&gt;
&lt;p&gt;The first step is to create a Managed Identity resource in Azure and then give read permission for this identity in the Keyvault which you need to communicate&lt;/p&gt;
&lt;p&gt;You can refer to the official documentation given below to perform this step&lt;/p&gt;
&lt;p&gt;&lt;a href="https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview" target="_blank" rel="noopener" title="Managed identities for Azure resources"&gt;Managed identities for Azure resources&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Connecting to KeyVault from ASP.NET Core Web App&lt;/h3&gt;
&lt;p&gt;Add a Nuget package called Azure.Identity&lt;/p&gt;
&lt;pre&gt;&amp;lt;PackageReference Include="Azure.Identity" Version="1.6.0" /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Modify the entries in your appsettings.json to add entries for the key vault URL and managed identity id&lt;/p&gt;
&lt;!--more--&gt;
&lt;pre&gt;&lt;code class="language-json"&gt; "AzureKeyVault": {&lt;br&gt;    "keyvault-url": "https://gab22demo-rg.vault.azure.net/",&lt;br&gt;    "mi-client-id": "72b0cc31-b3f9-4230-9e12-bd3f5c793e55"&lt;br&gt;  },
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, in the startup code, add the following snippet&lt;/p&gt;
&lt;pre&gt;&lt;code class="language-csharp"&gt;var keyVaultURL = hostingContext.Configuration.GetSection("AzureKeyVault:keyvault-url").Value;&lt;br&gt;var miClientId = hostingContext.Configuration.GetSection("AzureKeyVault:mi-client-id").Value;&lt;br&gt;
var client = new SecretClient(new Uri(keyVaultURL), new ManagedIdentityCredential(miClientId)); &lt;br&gt;config.AddAzureKeyVault(client: client, new KeyVaultSecretManager());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What we are doing basically here is&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;adds the KeyVault as a configuration provider&lt;/li&gt;
&lt;li&gt;sets up the connection to key vault using &lt;code&gt;AddAzureKeyVault&lt;/code&gt; method&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Once you complete this step, you will be able to access the key vault references in the same way you access values from other configuration providers such as &lt;code&gt;appsetting.json&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;A sample snippet is given below. Here we are using the &lt;code&gt;IConfiguration&lt;/code&gt; instance to read the value&amp;nbsp;&amp;nbsp;&lt;code&gt;DBConnection&lt;/code&gt; which is being fetched from the vault during the startup phase.&lt;/p&gt;
&lt;pre&gt;&lt;code class="language-csharp"&gt;private readonly ILogger&amp;lt;HomeController&amp;gt; _logger;
private readonly IConfiguration _configuration; 

public HomeController(ILogger&amp;lt;HomeController&amp;gt; logger, IConfiguration configuration)
{
    _logger = logger;
    _configuration = configuration;
}

public IActionResult Index()
{
    List&amp;lt;Product&amp;gt; products = new();
    using (var db = new GABDemoDbContext(_configuration["DBConnection"]))
    {
        products = db.Product.OrderBy(x =&amp;gt; x.Name).ToList();
    }
    return View(products);
}


&lt;/code&gt;&lt;/pre&gt;</description><pubDate>Sat, 26 Nov 2022 11:54:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/securing-azure-keyvault-using-mi</guid></item><item><title>Manage application settings with Azure KeyVault</title><link>https://www.techrepository.in:443/blog/posts/manage-application-settings-with-azure-keyvault</link><description>&lt;h1 id="manage-application-settings-with-azure-keyvault"&gt;&lt;/h1&gt;
&lt;p&gt;Securing your data and application configuration should be of prime importance for an application developer/architect and needs to be taken care of during the design phase itself. It is always better to take preventive steps rather than do firefighting after an incident. There are a lot of best practices out there to safeguard the data, but from time to time we ignore/forget to securely store app configuration settings.&lt;/p&gt;
&lt;p&gt;Very often developers tend to store hard-coded passwords, tokens, authorization keys, etc in the code or in the application configuration files and then commit the code into the version control. If your repo is publically available or some bad actors got access to it, then you may end up in a lot of trouble. There are automated bots that look for this kind of information by scanning the repos publically available in GitHub or BitBucket and then target your infrastructure with these credentials&lt;/p&gt;
&lt;h2 id="securing-the-configuration-settings"&gt;Securing the configuration settings&lt;/h2&gt;
&lt;p&gt;There are a lot of ways you can make that secure, for example by encrypting the entries in the configuration files or by keeping that sensitive information in some other medium such as a database. Another option is to rely on resources provided by cloud vendors such as Microsoft or Amazon.&lt;/p&gt;
&lt;p&gt;Azure KeyVault is one such cloud service provided by Microsoft for securely storing and accessing not only secrets but also certificates, keys, passwords, etc. Please refer to this &lt;a href="https://docs.microsoft.com/en-us/azure/key-vault/general/basic-concepts"&gt;official document&lt;/a&gt; for more details about Azure KeyVault. Apart from storing it securely, KeyVault provides additional features such as access control, audit logging, versioning, validity, and much more. With the help of these features, we can make sure that only authorized personnel/app has access to the data with proper auditing and expiration controls.&lt;/p&gt;
&lt;!--more--&gt;
&lt;h2 id="creating-a-keyvault-in-azure"&gt;Creating a KeyVault in Azure&lt;/h2&gt;
&lt;p&gt;We can create a resource in Azure in a number of ways, here I am going to show you how to create a vault from the portal as well as with commands using &lt;code&gt;Azure CLI&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Portal&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Just type&amp;nbsp;&amp;nbsp;&lt;code&gt;Key Vault&lt;/code&gt; in the search bar at the top and select &lt;code&gt;Key Vaults&lt;/code&gt; from the results. From the next page, select the &lt;code&gt;Create&lt;/code&gt; option and you will get a window like the one below. There, just select the Resource Group, specify a name for the key vault, region, and pricing tier, and leave the rest with the default values&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/docs/images/create-keyvault-1.png"&gt;&lt;img alt="Creating keyvault from portal" src="https://www.techrepository.in/docs/images/create-keyvault-1.png" height="50%" width="50%"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/docs/images/create-keyvault-2.png"&gt;&lt;img alt="Creating keyvault from portal" src="https://www.techrepository.in/docs/images/create-keyvault-2.png" height="50%" width="50%"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/docs/images/create-keyvault-3.png"&gt;&lt;img alt="Creating keyvault from portal" src="https://www.techrepository.in/docs/images/create-keyvault-3.png" height="50%" width="50%"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Azure CLI&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class="language-bash"&gt;az keyvault create --name "gab22demo-rg" --resource-group "GAB22RG" --location "SouthIndia"
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="creating-a-secret"&gt;Creating a secret&lt;/h2&gt;
&lt;p&gt;Before you can add a secret in the key vault, you will need to give yourself access to either add or manage it. In order to do that, you can go to &lt;code&gt;Access Policies&lt;/code&gt; from the left menu under your key vault and then select &lt;code&gt;Add Access Policy&lt;/code&gt;. Since we are dealing only with secrets, we will only select the necessary permissions needed for the same and then the identity to give access to&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/docs/images/add-kv-secret-1.png"&gt;&lt;img alt="Adding secret in key vault" src="https://www.techrepository.in/docs/images/add-kv-secret-1.png" height="50%" width="50%"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/docs/images/add-access-policy-1.png"&gt;&lt;img alt="Adding secret in key vault" src="https://www.techrepository.in/docs/images/add-access-policy-1.png" height="50%" width="50%"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CLI Command&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class="language-bash"&gt;az keyvault secret set --vault-name "gab22demo-rg" --name "DBConnection" --value "&amp;lt;your connection string&amp;gt;"
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id="reading-secrets-in-your-code"&gt;Reading secrets in your code&lt;/h2&gt;
&lt;p&gt;So we have created the key vault and added a secret in the vault to store the database connection string. Now, let's read this connection string from the vault and establish a connection to the database from the code base. For this post, I am going to use a .NET6 Web application for the demo purpose.&lt;/p&gt;
&lt;p&gt;In Azure, while creating the key vault it exposes API endpoint which can be used in our code to establish a connection to the vault for performing various operations. To get started, we will need to install a nuget package named &lt;code&gt;Microsoft.Extensions.Configuration.AzureKeyVault&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;We are going to store the key vault endpoint in the config file and will load it into the configuration collection during the bootstrapping phase&lt;/p&gt;
&lt;p&gt;So, let's add an entry in the &lt;code&gt;appsettings.json&lt;/code&gt; file as shown below&lt;/p&gt;
&lt;pre&gt;&lt;code class="language-json"&gt;  "AzureKeyVault": {
    "keyvault-url": "https://gab22demo-rg.vault.azure.net/"
  },
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, in the startup code, add the following snippet&lt;/p&gt;
&lt;pre&gt;&lt;code class="language-csharp"&gt;
builder.Host
    .ConfigureAppConfiguration((hostingContext, config) =&amp;gt;
    {
        AzureServiceTokenProvider azureServiceTokenProvider = new();
        KeyVaultClient keyVaultClient = new(
            new KeyVaultClient.AuthenticationCallback(
                azureServiceTokenProvider.KeyVaultTokenCallback
                ));
        config.AddAzureKeyVault(hostingContext.Configuration.GetSection("AzureKeyVault:keyvault-url").Value,
            keyVaultClient,
            new DefaultKeyVaultSecretManager());

    });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What we are doing basically here is&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;adds the KeyVault as a configuration provider&lt;/li&gt;
&lt;li&gt;sets up the connection to the key vault using &lt;code&gt;AddAzureKeyVault&lt;/code&gt; method&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Once you complete this step, you will be able to access the key vault references in the same way you access values from other configuration providers such as &lt;code&gt;appsetting.json&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;A sample snippet is given below. Here we are using the &lt;code&gt;IConfiguration&lt;/code&gt; instance to read the value&amp;nbsp;&amp;nbsp;&lt;code&gt;DBConnection&lt;/code&gt; which is being fetched from the vault during the startup phase.&lt;/p&gt;
&lt;pre&gt;&lt;code class="language-csharp"&gt;private readonly ILogger&amp;lt;HomeController&amp;gt; _logger;
private readonly IConfiguration _configuration; 

public HomeController(ILogger&amp;lt;HomeController&amp;gt; logger, IConfiguration configuration)
{
    _logger = logger;
    _configuration = configuration;
}

public IActionResult Index()
{
    List&amp;lt;Product&amp;gt; products = new();
    using (var db = new GABDemoDbContext(_configuration["DBConnection"]))
    {
        products = db.Product.OrderBy(x =&amp;gt; x.Name).ToList();
    }
    return View(products);
}


&lt;/code&gt;&lt;/pre&gt;</description><pubDate>Wed, 09 Nov 2022 11:54:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/manage-application-settings-with-azure-keyvault</guid></item><item><title>Adding Serilog to Azure Functions created using .NET 5</title><link>https://www.techrepository.in:443/blog/posts/adding-serilog-to-azure-functions-created-using-net-5</link><description>&lt;div class="alert alert-warning"&gt;The post is based on .NET 5.0&lt;/div&gt;
&lt;p&gt;Before the release of .NET 5, all functions developed using .NET ran as a class library in Azure and it was running inside the same process as the host. But with .NET 5, a function app built with .NET 5 runs in an isolated worker process which lets you decouple your function code from the runtime. A .NET isolated function is basically a console application targeting .NET 5 and requires the following files&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;host.json file&lt;/li&gt;
&lt;li&gt;local.settings.json file&lt;/li&gt;
&lt;li&gt;C# project file which defines the project and dependencies&lt;/li&gt;
&lt;li&gt;Program.cs file(entry point of the app)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this post, I will go through the steps that are needed for creating a .NET 5 Azure function, integrating Serilog for file logging, debugging, and running it locally, and then move on to publishing the function to Azure. You may already know that Azure functions already support some form of logging out of the box, but you may need to implement custom logging mechanisms depending on your need or for satisfying organizational requirements. I am going to use Serilog, which is a third-party logging provider which supports .NET and is also one of the most widely used in the ecosystem&lt;/p&gt;
&lt;h2&gt;Pre-requisites&lt;/h2&gt;
&lt;p&gt;There are some things you need before you start implementing this one. Azure Subscription is needed for hosting the functions in Azure, .NET 5 SDK, and Azure Functions Core Tools. Azure CLI is needed for developing, debugging, and publishing the app to Azure and VS Code for writing code.&amp;nbsp;&lt;/p&gt;
&lt;div&gt;
&lt;p style="padding-left: 30px;"&gt;Azure Subscription&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;.NET 5 SDK&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;Azure Function Core Tools version&amp;nbsp;&lt;span&gt;3.0.3381 or greater&lt;/span&gt;&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span&gt;Visual Studio Code&lt;/span&gt;&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span&gt;Azure CLI&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;h2&gt;Step 1&amp;nbsp;&lt;/h2&gt;
&lt;p&gt;The first step is to create a new Functions project, we will be using the func command to create a new one from the command line.&amp;nbsp;Even though you can edit and debug the project in Visual Studio, full support is not yet available as the project templates for creating the project and all. The following command will create a new Azure Function project and specifying the runtime as dotnetisolated enables you to run the app on .NET 5&lt;/p&gt;
&lt;pre&gt;func init FunctionLogger --worker-runtime dotnetisolated&lt;/pre&gt;
&lt;p&gt;When this command is executed, it will create all the necessary files including the host.json and local.settings.json files. The host.json file contains the configuration options affecting all the functions in your app whereas the other file can be used for storing options such as connection strings, secrets, and other settings used by your app. Since this file can have sensitive data, it is excluded when you check in the code to source control&lt;/p&gt;
&lt;h2&gt;Step 2&amp;nbsp;&lt;/h2&gt;
&lt;p&gt;Next, we will move on to create a new function in the project which is triggered by an HTTP request. The below statement creates a function named HttpExample using the HttpTrigger template and enables anonymous authentication&lt;/p&gt;
&lt;pre&gt;func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;pre&gt;public  class HttpExample
    {
        [Function("HttpExample")]
        public  HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("HttpExample");
            logger.LogInformation("C# HTTP trigger function processed a request.");

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString("Welcome to Azure Functions!");

            return response;
        }
    }
&lt;/pre&gt;
&lt;p&gt;We are not going to modifying the contents of the function created by default, because these statements are sufficient for demonstrating the logging mechanism&lt;/p&gt;
&lt;h2&gt;Step 3&amp;nbsp;&lt;/h2&gt;
&lt;p&gt;To use Serilog, you will need to add some packages in order to use it in your application. The package named Serilog is having the core functionality and Serilog.File and Serilog.Console is having the logic for writing it to the console and file respectively. In Serilog, these are called Sinks and there are a lot of them available for writing logs to Database, Seq, App Insights etc&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;dotnet add package Microsoft.Azure.Functions.Extensions
dotnet add package Serilog
dotnet add package Serilog.Extensions.Logging
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File&lt;/pre&gt;
&lt;h2&gt;Step 4&lt;/h2&gt;
&lt;p&gt;In a .NET 5 isolated function, you can configure the startup option by modify the main method in the Program.cs file. The entry point of your function is this method and here you will be able to configure the host options. To integrate Serilog,&amp;nbsp;you will need to import them into your project first and then configure the pipeline as shown below. Here I'm enabling both the file and console sinks, and the file sink is configured as a rolling file which creates a new file for each day.&lt;/p&gt;
&lt;pre&gt;    public class Program
    {
        public static void Main()
        {
            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults()
                // .ConfigureAppConfiguration((hostingcontext,config)=&amp;gt;{

                // })
                .ConfigureServices(s=&amp;gt;
                {
                     var logger = new LoggerConfiguration()
                    .WriteTo.Console()
                    .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
                    .CreateLogger();
                    s.AddLogging(lb =&amp;gt; lb.AddSerilog(logger));
                })
                .Build();

            host.Run();
        }
    }
&lt;/pre&gt;
&lt;h2&gt;&lt;span&gt;Step 5&lt;/span&gt;&lt;/h2&gt;
&lt;div&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;&lt;span&gt;Let's compile the project and run the app by going to the terminal and executing the below command. It will run the function locally using Azure Function core tools&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;&lt;span&gt;&lt;span&gt;&lt;!--StartFragment --&gt;&lt;/span&gt;&lt;/span&gt;
&lt;pre&gt;&lt;span&gt;func &lt;/span&gt;&lt;span&gt;start &lt;/span&gt;&lt;span&gt;--dotnet-isolated&lt;/span&gt;&lt;/pre&gt;
&lt;span&gt;&lt;!--EndFragment --&gt;&lt;/span&gt;&lt;/div&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog-az-fun/console-output.png" width="772" height="314"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog-az-fun/log-file.png" width="970" height="461"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;When the HTTP trigger function is executed by invoking the request from the browser, you can see that information is now being written to the console as well as the log file. The file will be created by the Serilog provider if it is not there and will be rolled over at the end of each day&lt;/p&gt;
&lt;h2&gt;Step 6&lt;/h2&gt;
&lt;p&gt;Now, let's publish the function app to Azure. As of now, functions developed using .NET 5 can be published only using the Azure CLI and are not supported in Portal as well as Visual Studio.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;First, I am going to create a resource group and a storage account in Azure which are the pre-requisites for creating a function app in Azure&lt;/p&gt;
&lt;p&gt;You can either use the portal or Azure CLI for the same&lt;/p&gt;
&lt;p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog-az-fun/create-rg.png" width="621" height="385"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog-az-fun/create-storage-account.png" width="607" height="636"&gt;&lt;/p&gt;
&lt;p&gt;Now, we will proceed to create the function app from the CLI using the below command. It will create the function in the resource group created previously and will use a consumption plan. It will use the storage account which we created earlier for the function management and uses .NET 5 and function V3 runtime for executing the function&lt;/p&gt;
&lt;pre&gt;az functionapp create --resource-group function-demo-rg --consumption-plan-location eastus --runtime dotnet-isolated --runtime-version 5.0 --functions-version 3 --name FunctionLoggerApp --storage-account functiondemostorage&lt;/pre&gt;
&lt;blockquote class="blockquote"&gt;Note: Make sure that you have the latest version of the Azure CLI, otherwise you get errors saying &lt;em&gt;"dotnet-isolated is not a valid value for --runtime"&lt;/em&gt;&lt;/blockquote&gt;
&lt;p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog-az-fun/az-function-app-creation.png"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;We will need to make a slight adjustment in our code to specify the location of the log file path. When I tried to put the log file in the folder from where our application was running, the logs were not getting written into it. By default, Azure creates a log folder outside the root folder of your app to write all the telemetry generated by the runtime. So when I used that path, it started writing information into it. Now my &lt;em&gt;Program.cs&lt;/em&gt; code looks like the one below&lt;/p&gt;
&lt;p&gt;
&lt;pre&gt;     var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults()
                // .ConfigureAppConfiguration((hostingcontext,config)=&amp;gt;{

                // })
                .ConfigureServices(s=&amp;gt;
                {&lt;br&gt;                    //If the app is hosted in Azure, then the env variable WEBSITE_SITE_NAME will have a value
                    var filepath = !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME"))?@"D:\home\LogFiles\Application\log.txt":"log.txt";
    
                     var logger = new LoggerConfiguration()
                    .WriteTo.Console()
                    .WriteTo.File(filepath, rollingInterval: RollingInterval.Day)
                    .CreateLogger();
                    s.AddLogging(lb =&amp;gt; lb.AddSerilog(logger));
                })
                .Build();

            host.Run();

&lt;/pre&gt;
&lt;p&gt;To publish the app to Azure&lt;/p&gt;
&lt;pre&gt;func azure functionapp publish FunctionLoggerApp&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog-az-fun/function-app-publish.png" width="624" height="394"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;If you browse to the endpoint of your function app using a browser, you will see the same message we got while testing in local, and our log file in the cloud will now have info written into it&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog-az-fun/log-file-console.png" width="838" height="496"&gt;&lt;/p&gt;
&lt;p&gt;</description><pubDate>Sat, 03 Apr 2021 16:26:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/adding-serilog-to-azure-functions-created-using-net-5</guid></item><item><title>Learn how to split log data into different tables using Serilog in ASP.NET Core</title><link>https://www.techrepository.in:443/blog/posts/split-log-data-different-tables-serilog-aspnet-core</link><description>&lt;p&gt;For most of the application developers, file systems are the primary choice for storing the information generated by the logging providers. One of the main drawbacks of using the files is that it's very difficult for the search for information or to do an analysis of the information written to it over time. Third-party logging providers such as &lt;a rel="nofollow" href="https://serilog.net/"&gt;Serilog&lt;/a&gt; have facilities to persist the data in database tables instead of the file system. Even then, if you use a single table to write all you errors and other debug information, the size of the table will grow considerably over time which can affect the performance of the whole operation itself.&lt;/p&gt;
&lt;p&gt;So, in this post, I will explore the possibility of using multiple tables for storing the logging information using Serilog. If you are new to Serilog, please refer to my previous articles on the same here using the links given below.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.techrepository.in/blog/posts/implementing-logging-in-a-net-core-web-application-using-serilog"&gt;Implementing Logging in a .NET Core Web Application using Serilog&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.techrepository.in/blog/posts/rollover-log-files-automatically-in-an-asp-net-core-web-application-using-serilog"&gt;Rollover log files automatically in an ASP.NET Core Web Application using Serilog&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.techrepository.in/blog/posts/write-your-logs-into-database-in-an-asp-net-core-application-using-serilog"&gt;Write your logs into database in an ASP.NET Core application using Serilog&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="alert alert-warning" style="text-align: justify;"&gt;
&lt;p&gt;Code snippets in this post are based on .NET Core 5.0 Preview 5&lt;/p&gt;
&lt;/div&gt;
&lt;h3&gt;Step 1: Create a Web Application in .NET Core&lt;/h3&gt;
&lt;p&gt;To get started we will create a new empty web application using the default template available in Visual Studio. Goto File -&amp;gt; New Project -&amp;gt; ASP.NET Core Web Application&lt;/p&gt;
&lt;p&gt;Give a name for the application, leave the rest of the fields with default values and click Create&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog/multiple-tables-new-proj.png" width="581" height="402"&gt;&lt;/p&gt;
&lt;p&gt;In the next window, select Web Application as a project template. Before you click on the Create button, make sure that you have selected the desired version of .NET Core in the dropdown shown at the top. Here, for this one, I selected .NET 5.0&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog/multiple-tables-proj-template.png" width="576" height="405"&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;You can also do this from .NET CLI using the following command&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet new web  --name SerilogMultipleTables
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When the command is executed it will scaffold a new application using the MVC structure and then restores the necessary packages needed for the default template.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p style="text-align: justify;"&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p&gt;By default, it will create two &lt;code&gt;json&lt;/code&gt; files named, &lt;code&gt;appsettings.json&lt;/code&gt; and &lt;code&gt;appsettings.development.json&lt;/code&gt;. These are the configuration files for the application and is chosen based on the environment where your application is running. These files will have a default configuration as shown below basically sets the default level for logging.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By default, it is set as &lt;code&gt;Information&lt;/code&gt;, which writes a lot of data to the logs. This setting is very useful while we are developing the application, but we should set it higher severity levels when the application is deployed to higher environments. Since Serilog is not going to reference this section, we can safely remove this from the configuration files&lt;/p&gt;
&lt;h2&gt;Step 2: Adding Serilog&lt;/h2&gt;
&lt;p&gt;To integrate Serilog with our application, we will need to add the following packages&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/serilog/serilog-aspnetcore" rel="nofollow"&gt;Serilog.AspNetCore&lt;/a&gt; - Base package dedicated for ASP .NET Core integration&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/serilog/serilog-settings-configuration" rel="nofollow"&gt;Serilog.Settings.Configuration&lt;/a&gt; - Provider that reads from the Configuration object&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/serilog/serilog-filters-expressions" rel="nofollow"&gt;Serilog.Filters.Expressions&lt;/a&gt; - Used for expression-based event filtering&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/serilog/serilog-sinks-mssqlserver" rel="nofollow"&gt;Serilog.Sinks.MSSqlServer&lt;/a&gt; - Used for writing logs in to one or more files&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the solution explorer window, right-click on the solution and choose Manage NuGet Packages from the context menu. Search for the packages given above and click on install to add it&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;To add the packages into your projects using .NET CLI, execute the commands given below from the command prompt&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Filters.Expressions
dotnet add package Serilog.Filters.MSSqlServer
&lt;/code&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Step 3: Added Serilog settings in the configuration file&lt;/h3&gt;
&lt;p&gt;Now we will modify our &lt;code&gt;appsettings.json&lt;/code&gt; file to add the settings for Serilog. In one of the earlier step, we removed the default entries for logging and will add the following instead of that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;"Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "MSSqlServer",
                "Args": {
                  "connectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Employee;Trusted_Connection=True;MultipleActiveResultSets=true",
                  "tableName": "ErrorLogs",
                  "autoCreateSqlTable": true
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Information' or @Level = 'Debug')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "MSSqlServer",
                "Args": {
                  "connectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Employee;Trusted_Connection=True;MultipleActiveResultSets=true",
                  "tableName": "InformationLogs",
                  "autoCreateSqlTable": true
                }
              }
            ]
          }
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "Application": "MultipleLogFilesSample"
    }
  }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here we have configured entries for writing logs into two tables depending upon the severity. For the first one, we set up the filter like this&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;"configureLogger": {
    "Filter": [
        {
        "Name": "ByIncludingOnly",
        "Args": {
            "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
        }
        }
    ],
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Under the &lt;code&gt;WriteTo&lt;/code&gt; section, we will need to configure the database connection string, name of the table that will be created for writing the logging information. I have specified different names for the table in the two-section so that it will split the writing operation between the tables depending upon the levels. Also, I have enabled the option to automatically create the tables, so when you run the application for the first time it will create the tables with the following schema.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CREATE TABLE [dbo].[ErrorLogs] (
    [Id]              INT            IDENTITY (1, 1) NOT NULL,
    [Message]         NVARCHAR (MAX) NULL,
    [MessageTemplate] NVARCHAR (MAX) NULL,
    [Level]           NVARCHAR (MAX) NULL,
    [TimeStamp]       DATETIME       NULL,
    [Exception]       NVARCHAR (MAX) NULL,
    [Properties]      NVARCHAR (MAX) NULL
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Because of the conditions, we specified in the configuration file, only &lt;code&gt;Error&lt;/code&gt;, &lt;code&gt;Fatal&lt;/code&gt; and &lt;code&gt;Warning&lt;/code&gt; types of logs will be written into a table named &lt;code&gt;ErrorLogs&lt;/code&gt;. Similarly, for the second one, it will write into the file named &lt;code&gt;InformationLogs&lt;/code&gt; if and only if the level is &lt;code&gt;Debug&lt;/code&gt; or &lt;code&gt;Information&lt;/code&gt;'&lt;/p&gt;
&lt;h2&gt;Step 4: Integrate Serilog in the application&lt;/h2&gt;
&lt;p&gt;To configure Serilog in our application, we will modify our &lt;code&gt;Program.cs&lt;/code&gt; file to call the Serilog middleware as shown below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static IHostBuilder CreateHostBuilder(string[] args) =&amp;gt;
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;p style="text-align: justify;"&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;h2&gt;Step 5: Writing logs from the application&lt;/h2&gt;
&lt;p&gt;Let's modify the &lt;code&gt;IndexModel&lt;/code&gt; method in the &lt;code&gt;Index.cshtml.cs&lt;/code&gt; file to simulate the call to logger methods which in turns writes information to the files&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public IndexModel(ILogger&amp;lt;IndexModel&amp;gt; logger)
{
    _logger = logger;
    _logger.LogInformation("Writing to log file with INFORMATION severity level.");
    _logger.LogDebug("Writing to log file with DEBUG severity level."); 
    _logger.LogWarning("Writing to log file with WARNING severity level.");
    _logger.LogError("Writing to log file with ERROR severity level.");
    _logger.LogCritical("Writing to log file with CRITICAL severity level.");

}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you run the application now, you will see the information in written into different files based on the log levels&lt;/p&gt;
&lt;p&gt;&lt;code&gt;ErrorLogs&lt;/code&gt; Table&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog/ErrorLogs-Table.png" width="844" height="148"&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;InformationLogs&lt;/code&gt; Table&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog/InformationLogs-Table.png" width="842" height="188"&gt;&lt;/p&gt;</description><pubDate>Thu, 23 Apr 2020 08:31:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/split-log-data-different-tables-serilog-aspnet-core</guid></item><item><title>Writing logs to different files using Serilog in ASP.NET Core Web Application</title><link>https://www.techrepository.in:443/blog/posts/writing-logs-to-different-files-serilog-asp-net-core</link><description>&lt;p style="text-align: justify;"&gt;Application log files play an important role in analyzing the bugs and for troubleshooting issues in an application. It&amp;rsquo;s worth noting that the log files are also used for writing information about events and other information that occurs when the application is running or serving requests in the case of a web application. Most application developers use a single file to log everything from errors, warnings, debug information, etc. There is no harm in following this approach, but the downside is that it will be harder for you to segregate information from the file easily. We can easily overcome this by maintaining multiple log files depending on the need. In this post, I am going to show how we can achieve this with Serilog&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;a href="https://serilog.net/"&gt;Serilog&lt;/a&gt; is a popular third party diagnostic logging library for .NET applications, I have already written some post about it and it&amp;rsquo;s usage already. If you are new to Serilog, please refer to those posts using the links given below.&lt;/p&gt;
&lt;ul style="text-align: justify;"&gt;
&lt;li&gt;&lt;a href="https://www.techrepository.in/blog/posts/implementing-logging-in-a-net-core-web-application-using-serilog"&gt;Implementing Logging in a .NET Core Web Application using Serilog&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.techrepository.in/blog/posts/rollover-log-files-automatically-in-an-asp-net-core-web-application-using-serilog"&gt;Rollover log files automatically in an ASP.NET Core Web Application using Serilog&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.techrepository.in/blog/posts/write-your-logs-into-database-in-an-asp-net-core-application-using-serilog"&gt;Write your logs into database in an ASP.NET Core application using Serilog&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="alert alert-warning" style="text-align: justify;"&gt;
&lt;p&gt;Code snippets in this post are based on .NET Core 5.0 Preview 5&lt;/p&gt;
&lt;/div&gt;
&lt;h3 style="text-align: justify;"&gt;&lt;a id="Step_1__Create_a_Web_Application_in_NET_Core_11"&gt;&lt;/a&gt;Step 1 : Create a Web Application in .NET Core&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;Create a new &lt;a href="http://ASP.NET"&gt;ASP.NET&lt;/a&gt; Core MVC application using the below command&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet new mvc  --name MultiLogFileSample
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;You can also do this from Visual Studio by going into File -&amp;gt; New Project -&amp;gt; ASP .NET Core Web Application&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p style="text-align: justify;"&gt;When the command is executed it will scaffold a new application using the MVC structure and then restores the necessary packages needed for the default template.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;By default, it will create two &lt;code&gt;json&lt;/code&gt; files named, &lt;code&gt;appsettings.json&lt;/code&gt; and &lt;code&gt;appsettings.development.json&lt;/code&gt;. These are the configuration files for the application and are chosen based on the environment where your application is running. These files will have a default configuration as shown below basically sets the default level for logging.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  "Logging":{
    "LogLevel":{
      "Default":Information",
      "Microsoft":Warning",
      "Microsoft.Hosting.Lifetime":Information"
    }
  }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;By default, it is set as &lt;code&gt;Information&lt;/code&gt;, which writes a lot of data to the logs. This setting is very useful while we are developing the application, but we should set it higher severity levels when the application is deployed to higher environments. Since Serilog is not going to reference this section, we can safely remove this from the configuration files&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;h3 style="text-align: justify;"&gt;&lt;a id="Step_2_Adding_Serilog_38"&gt;&lt;/a&gt;Step 2: Adding Serilog&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;To integrate Serilog with our application, we will need to add the following packages&lt;/p&gt;
&lt;ul style="text-align: justify;"&gt;
&lt;li&gt;&lt;a href="https://github.com/serilog/serilog-aspnetcore"&gt;Serilog.AspNetCore&lt;/a&gt; - Base package dedicated for ASP .NET Core integration&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/serilog/serilog-settings-configuration"&gt;Serilog.Settings.Configuration&lt;/a&gt; - Provider that reads from the Configuration object&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/serilog/serilog-filters-expressions"&gt;Serilog.Filters.Expressions&lt;/a&gt; - Used for expression-based event filtering&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/serilog/serilog-sinks-file"&gt;Serilog.Sinks.File&lt;/a&gt; - Used for writing logs in to one or more files&lt;/li&gt;
&lt;/ul&gt;
&lt;p style="text-align: justify;"&gt;To add the packages into your projects, execute the commands given below from the command prompt&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet add package Serilog.AspNetCore&lt;br&gt;dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Filters.Expressions
dotnet add package Serilog.Filters.File
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;To do this from Visual Studio, go to Manage NuGet Packages and then add the packages from there&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3 style="text-align: justify;"&gt;&lt;a id="Step_3_Added_Serilog_settings_in_the_configuration_file_57"&gt;&lt;/a&gt;Step 3: Added Serilog settings in the configuration file&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;Now we will modify our &lt;code&gt;appsettings.json&lt;/code&gt; file to add the settings for Serilog. In one of the earlier step, we removed the default entries for logging and will add the following instead of that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;"Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/ex_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Information' or @Level = 'Debug')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/cp_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "Application": "MultipleLogFilesSample"
    }
  }

&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;Here we have configured entries for writing logs into two files depending upon the severity. For the first one, we set up the filter like this&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;"configureLogger": {
    "Filter": [
        {
        "Name": "ByIncludingOnly",
        "Args": {
            "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
        }
        }
    ],
&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;Because of this condition, only &lt;code&gt;Error&lt;/code&gt;, &lt;code&gt;Fatal&lt;/code&gt; and &lt;code&gt;Warning&lt;/code&gt; types of logs will be written into a file named &lt;code&gt;ex-*.log&lt;/code&gt;. Since we have configured it as a rolling file, the date will also get appended to the file name. Similarly, for the second one, it will write into the file named &lt;code&gt;cp-*.log&lt;/code&gt; if and only if the level is &lt;code&gt;Debug&lt;/code&gt; or &lt;code&gt;Information&lt;/code&gt;&amp;rsquo;&lt;/p&gt;
&lt;h3 style="text-align: justify;"&gt;&lt;a id="Step_4_Integrate_Serilog_in_the_application_152"&gt;&lt;/a&gt;Step 4: Integrate Serilog in the application&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;To configure Serilog in our application, we will modify our &lt;code&gt;Program.cs&lt;/code&gt; file to call the Serilog middleware as shown below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static IHostBuilder CreateHostBuilder(string[] args)=&amp;gt;
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =&amp;gt;
        {
            webBuilder.UseStartup&amp;lt;Startup&amp;gt;();
        })
        .UseSerilog((hostingContext, loggerConfig) =&amp;gt;
            loggerConfig.ReadFrom.Configuration(hostingContext.Configuration)
        );
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 style="text-align: justify;"&gt;&lt;a id="Step_5_Writing_logs_from_the_application_168"&gt;&lt;/a&gt;Step 5: Writing logs from the application&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;Let&amp;rsquo;s modify the &lt;code&gt;Index&lt;/code&gt; method in the &lt;code&gt;HomeController.cs&lt;/code&gt; file to simulate the call to logger methods which in turns writes information to the files&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public HomeController(ILogger&amp;lt;HomeController&amp;gt; logger)
{
    _logger = logger;
    _logger.LogInformation(Writing to log file with INFORMATION severity level.");
    _logger.LogDebug(Writing to log file with DEBUG severity level."); 
    _logger.LogWarning(Writing to log file with WARNING severity level.");
    _logger.LogError(Writing to log file with ERROR severity level.");
    _logger.LogCritical(Writing to log file with CRITICAL severity level.");

}
&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;If you run the application now, you will see the information in written into different files based on the log levels&lt;br&gt; &lt;code&gt;cp-*.log&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;2020-06-20T23:11:42.0922074+05:30 [INF] (MultipleLogFilesSample.Controllers.HomeController) This is a log with INFORMATION severity level.
2020-06-20T23:11:42.0934669+05:30 [DBG] (MultipleLogFilesSample.Controllers.HomeController) This is a log with DEBUG severity level.

&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;code&gt;ex-*.log&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;2020-06-20T23:11:42.0934979+05:30 [WRN] (MultipleLogFilesSample.Controllers.HomeController) This is a log with WARNING severity level.
2020-06-20T23:11:42.0950269+05:30 [ERR] (MultipleLogFilesSample.Controllers.HomeController) This is a log with ERROR severity level.
2020-06-20T23:11:42.0958420+05:30 [FTL] (MultipleLogFilesSample.Controllers.HomeController) This is a log with CRITICAL severity level.
&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;img alt="Multiple Log Files in Serilog" src="https://www.techrepository.in/Media/Default/images/core/serilog/01-mulitple-log-files.png"&gt;&lt;/p&gt;</description><pubDate>Wed, 15 Apr 2020 18:16:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/writing-logs-to-different-files-serilog-asp-net-core</guid></item><item><title>Write your logs into database in an ASP.NET Core application using Serilog</title><link>https://www.techrepository.in:443/blog/posts/write-your-logs-into-database-in-an-asp-net-core-application-using-serilog</link><description>&lt;p style="text-align: justify;"&gt;In most scenarios, we normally use a flat-files for writing your logs or exception messages. But what if you write that information into the table in a database instead of a file.&amp;nbsp;To implement this functionality, we can make use of third-party providers such as&amp;nbsp;&lt;a href="https://serilog.net/" target="_blank" rel="nofollow"&gt;Serilog&lt;/a&gt; to log information in a SQL server database. Even though it's not a recommended approach, one can easily search the logs by executing SQL queries against the table.&lt;/p&gt;
&lt;h3 style="text-align: justify;"&gt;Installing Packages&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;Serilog provides the functionality to write logs to different sources such as files, trace logs, database and&amp;nbsp;the providers for these are called Serilog Sinks. To write logs to a table in a SQL Server database, you will need to add the following NuGet packages&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;Install-Package Serilog
Install-Package &lt;span&gt;Serilog.Settings.Configuration&lt;/span&gt;
Install-Package &lt;span&gt;Serilog.Sinks.MSSqlServer&lt;/span&gt;
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;The first package contains the core runtime, the second package can read the key under the "Serilog" section from a valid IConfiguration&amp;nbsp;source and the last one is responsible for making the connection to the database and writing information into the log table.&lt;/span&gt;&lt;/p&gt;
&lt;h3 style="text-align: justify;"&gt;&lt;span&gt;Configuring Serilog&amp;nbsp;&lt;/span&gt;&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;Modify the&amp;nbsp;&lt;/span&gt;&lt;code&gt;appsettings.json&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;file to&amp;nbsp;add a new section called "Serilog". We will set up the connection string to the database, provide the name of the table and instruct Serilog to create the table if not found in the DB&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;"Serilog": {
    "MinimumLevel": "Error",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Employee;Trusted_Connection=True;MultipleActiveResultSets=true",
          "tableName": "Logs",
          "autoCreateSqlTable": true
        }
      }
    ]
  },
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;Then modify the&amp;nbsp;&lt;/span&gt;&lt;code&gt;Program.cs&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;file to read these values from the JSON file&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;var configSettings = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

.ConfigureAppConfiguration(config =&amp;gt;
{
    config.AddConfiguration(configSettings);
})
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;Now, to hook up Serilog provider, import the namespace first&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;using Serilog
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;An add the following in the&amp;nbsp;&lt;/span&gt;&lt;code&gt;CreateHostBuilder&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;method&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configSettings)
    .CreateLogger();

.ConfigureLogging(logging =&amp;gt;
{
    logging.AddSerilog();
})
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;Here's the full code&lt;/p&gt;
&lt;pre&gt;public static IHostBuilder CreateHostBuilder(string[] args)
{
    var configSettings = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configSettings)
        .CreateLogger();

    return Host.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration(config =&amp;gt;
    {
        config.AddConfiguration(configSettings);
    })
    .ConfigureLogging(logging =&amp;gt;
    {
        logging.AddSerilog();
    })
    .ConfigureWebHostDefaults(webBuilder =&amp;gt;
    {
        webBuilder.UseStartup&lt;startup&gt;();
    });

}
&lt;/startup&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;
&lt;h3 style="text-align: justify;"&gt;&lt;span&gt;&lt;/span&gt;Testing it out&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;Create a new MVC application from Visual Studio By default, Logging is enabled in the application via the ILogger interface. In the case of a web app, you will get an&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;code&gt;ILogger&lt;/code&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;from DI container and use that object for writing into the configured log providers Let's see how we can do that in&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;code&gt;HomeController&lt;/code&gt;&lt;/p&gt;
&lt;p data-line="26" class="code-line code-line     " style="text-align: justify;"&gt;First, create a private variable&lt;/p&gt;
&lt;pre data-line="26" class="code-line code-line     "&gt;&lt;span class="hljs-keyword"&gt;private&lt;/span&gt;&lt;span&gt; &lt;/span&gt;&lt;span class="hljs-keyword"&gt;readonly&lt;/span&gt;&lt;span&gt; ILogger&amp;lt;HomeController&amp;gt; _logger;&lt;/span&gt;&lt;/pre&gt;
&lt;p data-line="26" class="code-line code-line     " style="text-align: justify;"&gt;&lt;span&gt;Then modify the constructor as shown below&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;public HomeController(ILogger&lt;homecontroller&gt; logger)
{
    _logger = logger;
}&lt;br&gt;&lt;/homecontroller&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p data-line="26" class="code-line code-line     " style="text-align: justify;"&gt;&lt;span&gt;Now, use the&amp;nbsp;&lt;/span&gt;&lt;code&gt;LogError&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;method to write a message into the log&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;public IActionResult Index()
{
    _logger.LogError("Writing to log");
    return View();
}
&lt;/pre&gt;
&lt;p data-line="51" class="code-line code-line" style="text-align: justify;"&gt;If you run the application and goto the home page, you will see this message written to the table.&lt;/p&gt;
&lt;p data-line="51" class="code-line code-line" style="text-align: justify;"&gt;&lt;img src="https://www.techrepository.in/Media/Default/images/core/serilog/03-01-log-table.PNG" width="931" height="162"&gt;&lt;/p&gt;
&lt;p data-line="51" class="code-line code-line" style="text-align: justify;"&gt;</description><pubDate>Sun, 02 Feb 2020 08:00:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/write-your-logs-into-database-in-an-asp-net-core-application-using-serilog</guid></item><item><title>Rollover log files automatically in an ASP.NET Core Web Application using Serilog</title><link>https://www.techrepository.in:443/blog/posts/rollover-log-files-automatically-in-an-asp-net-core-web-application-using-serilog</link><description>&lt;p style="text-align: justify;"&gt;We all implement logging in whatever applications we develop and over time it will grow bigger by each passing day. If we don't control that over time we will run into problems, especially with the size. Most of the logging providers help to overcome this by using rolling log providers which automatically archives the current log file when it reaches specific criteria or a threshold and creates the new file to resume the logging. In this article we will how we can make of the rolling file provider supported by Serilog to implement this functionality.&lt;/p&gt;
&lt;h3 data-line="7" class="code-line code-line    " style="text-align: justify;"&gt;Step 1: Install Packages&lt;/h3&gt;
&lt;p data-line="7" class="code-line code-line    " style="text-align: justify;"&gt;&lt;br&gt;First, install the following packages&lt;/p&gt;
&lt;pre data-line="7" class="code-line code-line    "&gt;Install-Package Serilog&lt;br&gt;Install-Package Serilog.Extensions.Logging&lt;br&gt;Install-Package Serilog.Sinks.File&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;The first package has all the core functionalities of Serilog whereas the second one is a provider for the logging subsystem used by&amp;nbsp;&lt;/span&gt;&lt;a href="http://asp.net/" data-href="http://ASP.NET" title="http://ASP.NET"&gt;ASP.NET&lt;/a&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Core(Microsoft.Extensions.Logging). The third package is responsible for writing the log information to the file, manages the rollover and all the related functionalities&lt;/span&gt;&lt;/p&gt;
&lt;h3 style="text-align: justify;"&gt;Step 2: Configure Serilog&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;&lt;br&gt;&lt;span&gt;Modify the&amp;nbsp;&lt;/span&gt;&lt;code&gt;appsettings.json&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;file to include the path for the log file&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt; "Logging": {
    "LogPath": "logs//ex.log",
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;Then, configure the sink to read this path from the config file and set it up to write to the file by modifying the&amp;nbsp;&lt;/span&gt;&lt;code&gt;CreateHostBuilder&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;method in&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;code&gt;Program.cs&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;file&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt; 
var configSettings = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

Log.Logger = new LoggerConfiguration()

    .WriteTo.File(configSettings["Logging:LogPath"], rollOnFileSizeLimit:true,fileSizeLimitBytes:10)
    .CreateLogger()

&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;Here, I configured the policy to roll over the file when the size of the current log file reaches 100 Kb. And finally, add the provider while bootstrapping the host as shown below&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;public static IHostBuilder CreateHostBuilder(string[] args)
{
    var configSettings = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    Log.Logger = new LoggerConfiguration()

        .WriteTo.File(configSettings["Logging:LogPath"], rollOnFileSizeLimit:true,fileSizeLimitBytes:100000)
        .CreateLogger();

    return Host.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration(config =&amp;gt;
    {
        config.AddConfiguration(configSettings);
    })
    .ConfigureLogging(logging =&amp;gt;
    {
        logging.AddSerilog();
    })
    .ConfigureWebHostDefaults(webBuilder =&amp;gt;
    {
        webBuilder.UseStartup&lt;startup&gt;();
    });

}
&lt;/startup&gt;&lt;/pre&gt;
&lt;h3 id="step-3-writing-the-log-to-the-file" data-line="75" class="code-line" style="text-align: justify;"&gt;Step 3: Writing the log to the file&lt;/h3&gt;
&lt;p data-line="77" class="code-line" style="text-align: justify;"&gt;For a web application, use an object of&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;code&gt;ILogger&lt;/code&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;which can be retrieved from the DI container as shown below&lt;/p&gt;
&lt;pre&gt;//declare a private variable
private readonly ILogger&lt;homecontroller&gt; _logger;

//assign the object got from the DI container in the constructor
public HomeController(ILogger&lt;homecontroller&gt; logger)
{
    _logger = logger;
}
&lt;/homecontroller&gt;&lt;/homecontroller&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;span&gt;If you run the application now and access the home page you will see the information is writing into the log file and rollover is happening automatically. The provider will automatically archive the file by appending a running sequence number to the file name.&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;&lt;homecontroller&gt;&lt;homecontroller&gt;&lt;span&gt;ex.log &lt;br&gt;ex_001.log &lt;br&gt;ex_002.log &lt;br&gt;ex_003.log&lt;/span&gt;

&lt;/homecontroller&gt;&lt;/homecontroller&gt;&lt;/pre&gt;
&lt;h3 id="rolling-policies" data-line="99" class="code-line" style="text-align: justify;"&gt;Rolling Policies&lt;/h3&gt;
&lt;h4 id="log-file-per-day" data-line="101" class="code-line" style="text-align: justify;"&gt;Log file per day&lt;/h4&gt;
&lt;p data-line="103" class="code-line" style="text-align: justify;"&gt;If you want to configure rollover for a period, say for a day or month, you will need to set up the interval as shown below&lt;/p&gt;
&lt;pre&gt;Log.Logger = new LoggerConfiguration()
    .WriteTo.File(configSettings["Logging:LogPath"], rollingInterval: RollingInterval.Day)
    .CreateLogger();

&lt;/pre&gt;
&lt;p data-line="111" class="code-line" style="text-align: justify;"&gt;This setting will create a log file per day&lt;/p&gt;
&lt;h4 id="limits" data-line="113" class="code-line" style="text-align: justify;"&gt;Limits&lt;/h4&gt;
&lt;p data-line="115" class="code-line" style="text-align: justify;"&gt;When you set up rolling interval periods, be it for size or period, there are some default values&lt;/p&gt;
&lt;ul style="text-align: justify;"&gt;
&lt;li data-line="117" class="code-line"&gt;By default, the size of the file is capped at 1 GB, so if are not limiting the file size it will grow up to 1 GB
&lt;pre&gt;.WriteTo.File(configSettings["Logging:LogPath"], rollingInterval: RollingInterval.Day, fileSizeLimitBytes:100000)
&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;ul style="text-align: justify;"&gt;
&lt;li&gt;&lt;span&gt;Only the most recent 31 files are retained by default, you can override it by using&amp;nbsp;&lt;/span&gt;&lt;code&gt;retainedFileCountLimit&lt;/code&gt;
&lt;pre&gt;.WriteTo.File(configSettings["Logging:LogPath"], rollingInterval: RollingInterval.Day, retainedFileCountLimit: 100)
&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-line="7" class="code-line code-line    " style="text-align: justify;"&gt;
&lt;p data-line="7" class="code-line code-line    " style="text-align: justify;"&gt;</description><pubDate>Sun, 19 Jan 2020 13:15:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/rollover-log-files-automatically-in-an-asp-net-core-web-application-using-serilog</guid></item><item><title>Implementing Logging in a .NET Core Web Application using Serilog</title><link>https://www.techrepository.in:443/blog/posts/implementing-logging-in-a-net-core-web-application-using-serilog</link><description>&lt;h2&gt;&lt;span&gt;Setting&amp;nbsp;up&amp;nbsp;default&amp;nbsp;logging&lt;/span&gt;&lt;/h2&gt;
&lt;p class="code-line code-line     " data-line="4"&gt;Create a new MVC application from Visual Studio. By default, Logging is enabled in the application via the ILogger interface. It has got some built-in providers for writing the log information to the console, event log as well as for third-party providers such as NLog, Serilog, etc.&lt;/p&gt;
&lt;p class="code-line code-line    " data-line="7"&gt;For example, if you want to write&amp;nbsp;logging information to the console window or event log, you will need to configure it in the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;code&gt;CreateDefaultHostBuilder&lt;/code&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;method in the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;code&gt;Program.cs&lt;/code&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;file as shown below.&lt;/p&gt;
&lt;p class="code-line code-line    " data-line="7"&gt;
&lt;pre&gt; public static IHostBuilder CreateHostBuilder(string[] args) =&amp;gt;
    Host.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =&amp;gt;
    {
        logging.AddConsole();
        logging.AddEventLog();
    })
    .ConfigureWebHostDefaults(webBuilder =&amp;gt;
    {
        webBuilder.UseStartup&lt;startup&gt;();
    });
&lt;/startup&gt;&lt;/pre&gt;
&lt;p class="code-line code-line           " data-line="23"&gt;In the case of a web app, you will get an&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;code&gt;ILogger&lt;/code&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;from the DI container and use that object for writing into the configured log providers. Let's see how we can do that in the&lt;span&gt; &lt;/span&gt;&lt;code&gt;HomeController&lt;/code&gt;&lt;/p&gt;
&lt;p class="code-line code-line     " data-line="26"&gt;First, create a private variable for the logger interface.&lt;/p&gt;
&lt;pre class="code-line code-line     " data-line="26"&gt;&lt;span class="hljs-keyword"&gt;private&lt;/span&gt;&lt;span&gt; &lt;/span&gt;&lt;span class="hljs-keyword"&gt;readonly&lt;/span&gt;&lt;span&gt; ILogger&amp;lt;HomeController&amp;gt; _logger;&lt;/span&gt;&lt;/pre&gt;
&lt;p class="code-line code-line     " data-line="26"&gt;&lt;span&gt;Then modify the constructor as shown below&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;public HomeController(ILogger&lt;homecontroller&gt; logger)
{
    _logger = logger;
}
&lt;/homecontroller&gt;&lt;/pre&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p class="code-line code-line     " data-line="26"&gt;&lt;span&gt;Now, use the&amp;nbsp;&lt;/span&gt;&lt;code&gt;LogInformation&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;method available in the logger interface to write a message into the log&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;public IActionResult Index()
{
    _logger.LogInformation("Writing to log");
    return View();
}
&lt;/pre&gt;
&lt;p class="code-line code-line" data-line="51"&gt;If we run the application and goto the home page now, you will see this message written to the console.&lt;/p&gt;
&lt;p class="code-line code-line" data-line="53"&gt;To write an error, we normally use&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;code&gt;LogError&lt;/code&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;method as shown below&lt;/p&gt;
&lt;p class="code-line code-line" data-line="53"&gt;
&lt;pre&gt;public IActionResult Index()
{
    _logger.LogInformation("Writing to log");
    _logger.LogError("Error from Serlog sample");
    return View();
}
&lt;/pre&gt;
&lt;p class="code-line code-line" data-line="53"&gt;&lt;span&gt;And the output will be&lt;/span&gt;&lt;/p&gt;
&lt;p class="code-line code-line" data-line="53"&gt;&lt;span&gt;&lt;img alt="" src="https://www.techrepository.in/Media/Default/images/core/serilog/01-01-console-output.PNG"&gt;&lt;/span&gt;&lt;/p&gt;
&lt;h2 class="code-line code-line" id="step-2-implementing-serilog-to-log-in-a-file" data-line="66"&gt;Implementing Serilog to log in a flat-file&lt;/h2&gt;
&lt;p&gt;&lt;span&gt;First, you will need to install the necessary packages given below.&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;Install-Package Serilog
Install-Package Serilog.Extensions.Logging
Install-Package Serilog.Sinks.File
&lt;/pre&gt;
&lt;p&gt;&lt;span&gt;Modify the&amp;nbsp;&lt;/span&gt;&lt;code&gt;appsettings.json&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;file to include the path for the log file&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;"Logging": {
    "LogPath": "logs//ex.log",
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
&lt;/pre&gt;
&lt;p&gt;&lt;span&gt;Then modify the&amp;nbsp;&lt;/span&gt;&lt;code&gt;Program.cs&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;file to read these values from the JSON file&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;var configSettings = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

.ConfigureAppConfiguration(config =&amp;gt;
{
    config.AddConfiguration(configSettings);
})
&lt;/pre&gt;
&lt;p&gt;&lt;span&gt;Now, to hook up Serilog provider, import the namespace first and then modify&amp;nbsp;&lt;code&gt;CreateHostBuilder&lt;/code&gt;&lt;span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;method&lt;/span&gt; to set up the logger&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;using Serilog
&lt;/pre&gt;
&lt;p&gt;
&lt;pre&gt;Log.Logger = new LoggerConfiguration()

    .WriteTo.File(configSettings["Logging:LogPath"])
    .CreateLogger();

.ConfigureLogging(logging =&amp;gt;
{
    logging.AddSerilog();
})
&lt;/pre&gt;
&lt;p&gt;Here's the method is full&lt;/p&gt;
&lt;pre&gt;public static IHostBuilder CreateHostBuilder(string[] args)
{
    var configSettings = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    Log.Logger = new LoggerConfiguration()

        .WriteTo.File(configSettings["Logging:LogPath"])
        .CreateLogger();

    return Host.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration(config =&amp;gt;
    {
        config.AddConfiguration(configSettings);
    })
    .ConfigureLogging(logging =&amp;gt;
    {
        logging.AddSerilog();
    })
    .ConfigureWebHostDefaults(webBuilder =&amp;gt;
    {
        webBuilder.UseStartup&lt;startup&gt;();
    });

}
&lt;/startup&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;&lt;span&gt;Now if we run the application, you will see the information being written to the file mentioned in the path.&lt;/span&gt;&lt;/p&gt;</description><pubDate>Wed, 08 Jan 2020 16:51:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/implementing-logging-in-a-net-core-web-application-using-serilog</guid></item><item><title>Generate Help Pages for your ASP.NET Core Web Api using Swagger</title><link>https://www.techrepository.in:443/blog/posts/generate-help-pages-for-your-asp-net-core-web-api-using-swagger</link><description>&lt;p&gt;For any Web API developers, documenting your API and its methods is of paramount importance. Because these are intended to be consumed third parties, they will find it hard to incorporate it without any proper documentation. Creating a document is a very tedious and time-consuming job and most of the developers are least worried about it. This is where tools like Swagger which can automatically generate the documentation for you by examining your API code.&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Adding Swagger&lt;/h3&gt;
&lt;p&gt;To set it up, you will need to add the below package to your project. This is can be done using the NuGet Package Manager in Visual Studio or by executing the following command in the Package Manager Console window&lt;/p&gt;
&lt;pre&gt;Install-Package Swashbuckle.AspNetCore&lt;/pre&gt;
&lt;p&gt;This package will add the following components&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Swashbuckle.AspNetCore.Swagger : Middleware used to expose Swagger Document as a JSON endpoint&lt;/li&gt;
&lt;li&gt;Swashbuckle.AspNetCore.SwaggerGen : a generator that builds the Swagger Document by looking into your controllers and action methods&lt;/li&gt;
&lt;li&gt;Swashbuckle.AspNetCore.SwaggerUI : interprets the JSON outputted by the endpoint and builds an interactive UI&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Configuring Swagger in your API Project&lt;/h3&gt;
&lt;p&gt;Adding and configuring Swagger is done in the Program class, first, you will need to import the following namespace&lt;/p&gt;
&lt;pre&gt;using Microsoft.OpenApi.Models;
&lt;/pre&gt;
&lt;p&gt;Then in the ConfigureServices method, register the Swagger generator and define a document&lt;/p&gt;
&lt;pre&gt;services.AddSwaggerGen(c =&amp;gt;
 {
     c.SwaggerDoc("v1", new OpenApiInfo { Title = "Swagger Sample API V1", Version = "v1" });
 });
&lt;/pre&gt;
&lt;p&gt;In the Configure method, add the two statements given below. The first one will enable the middleware to serve the generated document and the second one this document to show the interactive UI&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;pre&gt;//enables middleware
app.UseSwagger();

//enables SwaggerUI middleware to serve the UI for documentation
//and also specified the Swagger JSON endpoint
app.UseSwaggerUI(c =&amp;gt;
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger Sample API V1");
});
&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;Here's the Configure method in full&lt;/p&gt;
&lt;pre&gt;public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSwagger();

    app.UseSwaggerUI(c =&amp;gt;
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger Sample API V1");
    });


    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =&amp;gt;
    {
        endpoints.MapControllers();
    });
}&lt;/pre&gt;
&lt;h3&gt;Accessing Swagger UI&lt;/h3&gt;
&lt;p&gt;You can access the UI by appending "swagger" to the root URL. For example, if you run the project&amp;nbsp;just created, the interactive documentation will look like the one given below&lt;/p&gt;
&lt;p&gt;&lt;img width="650" height="240" src="https://www.techrepository.in/Media/Default/images/core/swagger/01-default-view-docs.PNG"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;&lt;img width="404" height="207" src="https://www.techrepository.in/Media/Default/images/core/swagger/02-schema-expanded.png"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;&lt;img width="742" height="363" src="https://www.techrepository.in/Media/Default/images/core/swagger/03-api-method-details.png"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;&lt;img width="753" height="396" src="https://www.techrepository.in/Media/Default/images/core/swagger/04-api-method-execution.PNG"&gt;&lt;/p&gt;
&lt;p&gt;</description><pubDate>Sat, 14 Sep 2019 07:00:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/generate-help-pages-for-your-asp-net-core-web-api-using-swagger</guid></item><item><title>Serializing enums as strings using System.Text.Json library in .NET Core 3.0</title><link>https://www.techrepository.in:443/blog/posts/serializing-enums-as-strings-using-system-text-json-library-in-net-core-3-0</link><description>&lt;p style="text-align: justify;"&gt;.NET Core 3.0 uses the System.Text.Json API by default for JSON serialization operations. Prior versions of .NET Core relied on JSON.NET, a third party library developed by Newtonsoft and the framework team decided to create a brand new library that can make use of the latest features in the language and the framework.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;The new library has got support for all the new features that got introduced in the latest version of C#. And this was one of the main reasons behind the development of the new library because implementing these changes in JSON.NET meant a significant rewrite.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;While serializing an object into JSON using the new library we can control various options such as casing, indentation, etc, but one notable omission is the support for enums by default. If you try to serialize an enum in .NET Core 3.0 with the default library, it will convert it into an integer value instead of the name of the enum. &lt;br&gt;For example, let consider the following model and see if what happens when we serialize it using the System.Text.Json library&lt;/p&gt;
&lt;pre&gt;public enum AddressType
{        
    HomeAddress,
    OfficeAddress,
    CommunicationAddress
    }

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public AddressType CommunicationPreference { get; set; }
}
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;and when you serialize it using the serialize method&lt;/p&gt;
&lt;pre&gt;List&lt;employee&gt; employees = new List&lt;employee&gt;{
    new Employee{
        FirstName = "Amal",
        LastName ="Dev",
        CommunicationPreference = AddressType.HomeAddress
    },
    new Employee{
        FirstName = "Dev",
        LastName ="D",
        CommunicationPreference = AddressType.CommunicationAddress
    },
    new Employee{
        FirstName = "Tris",
        LastName ="Tru",
        CommunicationPreference = AddressType.OfficeAddress
    }
}

JsonSerializer.Serialize(employees);
&lt;/employee&gt;&lt;/employee&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;it will produce an output like the one given below&lt;/p&gt;
&lt;pre&gt;[ 
   { 
      "FirstName":"Amal",
      "LastName":"Dev",
      "CommunicationPreference":0
   },
   { 
      "FirstName":"Dev",
      "LastName":"D",
      "CommunicationPreference":2
   },
   { 
      "FirstName":"Tris",
      "LastName":"Tru",
      "CommunicationPreference":1
   }
]
&lt;/pre&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-slot="4913572023" data-ad-client="ca-pub-9668277581503568" data-ad-format="fluid" data-ad-layout="in-article"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;If you look closely at the output string, the CommunicationPreference property has integer values instead of the names. In some scenarios, say if you are trying to give it as an output of an API method call it is not desirable to give back these integer values which can be meaningless. To overcome this, you can make use of a converter available in the library to do the conversion for you. To use this, instantiate an object of the JsonSerializerOptions and specify the converter there. And when you call the serialize method, pass this object also into that method as shown below&lt;/p&gt;
&lt;pre&gt;JsonSerializerOptions options = new JsonSerializerOptions{
    Converters ={
        new JsonStringEnumConverter()
    }
};

JsonSerializer.Serialize(employees, options);
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;Now the generated output will be&lt;/p&gt;
&lt;pre&gt;[
   {
      "FirstName":"Amal",
      "LastName":"Dev",
      "CommunicationPreference":"HomeAddress"
   },
   {
      "FirstName":"Dev",
      "LastName":"D",
      "CommunicationPreference":"CommunicationAddress"
   },
   {
      "FirstName":"Tris",
      "LastName":"Tru",
      "CommunicationPreference":"OfficeAddress"
   }
]
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;You will see now that our property is correctly displaying the names of the enums which is done automatically by the converter we added. By default, the library converts the strings to Pascal Case instead of the camelCase which is the most widely used format in JSON. You can control this behavior by specifying the format while hooking up the converter to the serializer&lt;/p&gt;
&lt;pre&gt;JsonSerializerOptions options = new JsonSerializerOptions{
    Converters ={
        new JsonStringEnumConverter( JsonNamingPolicy.CamelCase)
    },
    
};
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;And now, the output will be&lt;/p&gt;
&lt;pre&gt;[
   {
      "FirstName":"Amal",
      "LastName":"Dev",
      "CommunicationPreference":"homeAddress"
   },
   {
      "FirstName":"Dev",
      "LastName":"D",
      "CommunicationPreference":"communicationAddress"
   },
   {
      "FirstName":"Tris",
      "LastName":"Tru",
      "CommunicationPreference":"officeAddress"
   }
]
&lt;/pre&gt;
&lt;h3 style="text-align: justify;"&gt;Deserializing Enums as Strings&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;We can use the same converter for doing deserialization also. If we try to deserialize &lt;g class="gr_ gr_38 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="38" data-gr-id="38"&gt;a incoming&lt;/g&gt; payload that contains a string value instead of &lt;g class="gr_ gr_40 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="40" data-gr-id="40"&gt;integer&lt;/g&gt; value for an enum the compiler value will throw JSON exception&lt;/p&gt;
&lt;pre&gt;string emp="[{\"FirstName\":\"Amal\",\"LastName\":\"Dev\",\"CommunicationPreference\":\"HomeAddress\"},{\"FirstName\":\"Dev\",\"LastName\":\"D\",\"CommunicationPreference\":\"CommunicationAddress\"},{\"FirstName\":\"Tris\",\"LastName\":\"Tru\",\"CommunicationPreference\":\"OfficeAddress\"}]";
&lt;/pre&gt;
&lt;pre&gt;Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to JsonTextApi.AddressType. Path: $[0].CommunicationPreference
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;But, if &lt;g class="gr_ gr_39 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="39" data-gr-id="39"&gt;provide&lt;/g&gt; an integer value instead of string for the enum, the serializer will deserialize it as expected If you want to use the string value, then add the converter while calling the Deserialize method as we did for the serialization operation.&lt;/p&gt;
&lt;pre&gt;JsonSerializerOptions options = new JsonSerializerOptions{
    Converters ={
        new JsonStringEnumConverter( JsonNamingPolicy.CamelCase)
    },

};

JsonSerializer.Deserialize&amp;lt;List&lt;employee&gt;&amp;gt;(emp,options).ForEach(x=&amp;gt; Console.WriteLine($"{x.FirstName} {x.LastName}, {x.CommunicationPreference}"));
&lt;/employee&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;Output&lt;/p&gt;
&lt;pre&gt;Amal Dev, HomeAddress
Dev D, CommunicationAddress
Tris Tru, OfficeAddress
&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;&lt;a title="Serializing &amp;amp; Deserializing JSON in .NET Core 3.0" href="https://www.techrepository.in/blog/posts/the-all-new-system-text-json-api-in-net-core" rel="dofollow"&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;Part 1 : Serializing and Deserializing&lt;span&gt;&amp;nbsp;&lt;/span&gt;Json&lt;span&gt;&amp;nbsp;&lt;/span&gt;in .NET Core 3.0 using System.Text.Json API&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;&lt;a title="Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json" href="https://www.techrepository.in/blog/posts/step-by-step-guide-to-serialize-and-deserialize-json-using-system-text-json" rel="dofollow"&gt;Part 2: Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/blog/posts/avoid-conversion-errors-by-using-custom-converters-in-system-text-json-api-net-core-3-0" target="_blank"&gt;Part 3: &lt;span style="text-decoration: underline;"&gt;&lt;span style="color: #000120;" color="#000120"&gt;Avoid conversion errors by using Custom Converters in System.Text.Json API&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;</description><pubDate>Fri, 30 Aug 2019 09:07:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/serializing-enums-as-strings-using-system-text-json-library-in-net-core-3-0</guid></item><item><title>Avoid conversion errors by using Custom Converters in System.Text.Json API(.NET Core 3.0)</title><link>https://www.techrepository.in:443/blog/posts/avoid-conversion-errors-by-using-custom-converters-in-system-text-json-api-net-core-3-0</link><description>&lt;div class="alert alert-warning"&gt;The post is based on .NET Core 3.0&lt;br&gt;SDK used : 3.0.100&lt;/div&gt;
&lt;p style="text-align: justify;"&gt;&lt;span class="veryhardreadability"&gt;&lt;span data-offset-key="6r4os-0-0"&gt;&lt;span data-text="true"&gt;One of the most common error encountered while doing JSON serialization and deserialization is the data type conversion errors&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;. Till now, we were using the&amp;nbsp;&lt;a href="https://www.newtonsoft.com/json" title="Json.NET library from Newtonsoft" rel="nofollow"&gt;Json.NET library from Newtonsoft&lt;/a&gt; for performing the serialization and deserialization in .NET/ASP.NET/.NET Core, but in the latest iteration of&lt;a href="https://dotnet.microsoft.com/download/dotnet-core/3.0" title=".NET Core which is currently under preview" rel="nofollow"&gt; .NET Core which is currently under preview&lt;/a&gt;, they have removed the dependency on Json.NET and introduced a new built-in library for doing the same. Along with that, the all new library that is going to be introduced with .NET Core 3.0 provides you to define custom converters that can be implemented to get rid of this kind of errors. If you are not aware of it,&amp;nbsp;I have already written a couple of posts about it which you can&amp;nbsp;refer to using the following links.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;a href="https://www.techrepository.in/blog/posts/the-all-new-system-text-json-api-in-net-core" rel="dofollow" title="Serializing &amp;amp; Deserializing JSON in .NET Core 3.0"&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;Serializing and Deserializing Json in .NET Core 3.0 using System.Text.Json API&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;&lt;a href="https://www.techrepository.in/blog/posts/step-by-step-guide-to-serialize-and-deserialize-json-using-system-text-json" rel="dofollow" title="Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json"&gt;Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;The&amp;nbsp;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.json?view=netcore-3.0" title="new API" rel="nofollow"&gt;new API&lt;/a&gt; is included with the System namespace and you don't need to add any NuGet package to get started with it. Along with the normally used methods for serializing/deserializing JSON, it also includes methods for supporting asynchronous programming. One of the known limitation in the&amp;nbsp;v1 of the API is the limited support for the data types, given below is the list of currently supported types. For more detail, please refer this link&amp;nbsp;&lt;a href="https://github.com/dotnet/corefx/blob/master/src/System.Text.Json/docs/SerializerProgrammingModel.md" rel="nofollow"&gt;Serializer API Document&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;ul style="list-style-type: disc;"&gt;
&lt;li&gt;Array&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Boolean&lt;/li&gt;
&lt;li&gt;Byte&lt;/li&gt;
&lt;li&gt;Char (as a JSON string of length 1)&lt;/li&gt;
&lt;li&gt;DateTime&amp;nbsp;&lt;/li&gt;
&lt;li&gt;DateTimeOffset&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Dictionary&amp;lt;string, TValue&amp;gt; (currently just primitives in Preview 5)&lt;/li&gt;
&lt;li&gt;Double&lt;/li&gt;
&lt;li&gt;Enum (as integer for now)&lt;/li&gt;
&lt;li&gt;Int16&lt;/li&gt;
&lt;li&gt;Int32&lt;/li&gt;
&lt;li&gt;Int64&lt;/li&gt;
&lt;li&gt;IEnumerable&amp;nbsp;&lt;/li&gt;
&lt;li&gt;IList&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Object (polymorhic mode for serialization only)&lt;/li&gt;
&lt;li&gt;Nullable &amp;lt; T &amp;gt;&lt;/li&gt;
&lt;li&gt;SByte&lt;/li&gt;
&lt;li&gt;Single&lt;/li&gt;
&lt;li&gt;String&lt;/li&gt;
&lt;li&gt;UInt16&lt;/li&gt;
&lt;li&gt;UInt32&lt;/li&gt;
&lt;li&gt;UInt64&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-9668277581503568" data-ad-slot="4913572023"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;Also, by design, any support for type coercion/inference is not included by default. For example, if we are trying to convert a boolean value stored as a string in the JSON to a boolean type, the serializer will throw an error during the deserializing operation. To illustrate this, let's consider the below JSON&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[
    {
        "Id": 1026,
        "Name": "Echo Dot",
        "Description": "Smart speakers from Amazon",
        "IsInStock": "false"
    },
    {
        "Id": 8084,
        "Name": "Chromecast",
        "Description": "Stream content to TV",
        "IsInStock": "true"
    },
    {
        "Id": 9096,
        "Name": "iPhone",
        "Description": "Latest one from Apple",
        "IsInStock": "false"
    }
]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And I have defined a class like the one below&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime LastUpdatedOn { get; set; }
        public bool IsInStock { get; set; }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we try to deserialize using the following statement, the API will throw an error as shown below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;JsonSerializer.Deserialize&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt;(productList, options);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;samp&gt;Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to System.Boolean. Path: $[0].IsInStock | LineNumber: 5 | BytePositionInLine: 25.
 ---&amp;gt; System.InvalidOperationException: Cannot get the value of a token type 'String' as a boolean.
&lt;/samp&gt;&lt;/pre&gt;
&lt;p&gt;In the JSON, for the &lt;strong&gt;"&lt;code&gt;IsInStock&lt;/code&gt;" &lt;/strong&gt;attribute the value is stored as a string and we are trying to map that attribute to a boolean property in the &lt;strong&gt;&lt;code&gt;Product&lt;/code&gt; &lt;/strong&gt;class using the &lt;strong&gt;&lt;code&gt;Deserialize&lt;/code&gt; &lt;/strong&gt;method in the API.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Complete code&amp;nbsp;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;ConverterSample.cs&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Collections.Generic;

namespace JsonTextApi
{

    class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime LastUpdatedOn { get; set; }
        public bool IsInStock { get; set; }
    }
    class ConverterSample
    {
        public List&amp;lt;Product&amp;gt; DeserializeData(string productList)
        {
           
            return JsonSerializer.Deserialize&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt;(productList);
        }
        

    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Program.cs&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;
using System.Collections.Generic;

namespace JsonTextApi
{
    class Program
    {
        static void Main(string[] args)
        {
            
            ConverterSample obj = new ConverterSample();
            var objProduct = new Product();

            var productJson = File.ReadAllText("input.json");
            Console.WriteLine(productJson);
            Console.ReadLine();
            var items = obj.DeserializeData(productJson);
            
            
            foreach(var item in items)
            {
                Console.WriteLine($"{item.Id}, {item.Name}, {item.IsInStock}");
            }
            Console.ReadLine();            
        }

    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;This is&amp;nbsp;happening because, as I already mentioned the API doesn't do these sort of conversions by default. But in most of the circumstances, the consuming applications don't have control over the type or format of the data. So to handle this kind of situations, one may need to implement custom converters to handle the job for you. It's very to easy to create and hookup converters using the System.Text.Json API.&amp;nbsp;&lt;/p&gt;
&lt;h2 style="text-align: justify;"&gt;Using Custom Converters&lt;/h2&gt;
&lt;p&gt;Let's&amp;nbsp;create a custom converter to convert the value stored as string in the JSON to a boolean type.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;strong&gt;Step 1&lt;/strong&gt;: Create a class by inheriting&amp;nbsp;from &lt;code&gt;&lt;strong&gt;JsonConverter&amp;lt;T&amp;gt;&amp;nbsp;&lt;/strong&gt;&lt;/code&gt;class&amp;nbsp;available in the &lt;code&gt;&lt;strong&gt;System.Text.Json.Serialization&lt;/strong&gt;&lt;/code&gt;&amp;nbsp;namespace where T is the type you want to convert to.&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class BooleanConverter : JsonConverter&amp;lt;bool&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Override the &lt;code&gt;&lt;strong&gt;Read&lt;/strong&gt; &lt;/code&gt;method to handle the deserialization of the incoming JSON string. Here, the conversion will happen if the value in the string is either "True", "true", "1", "False", "false", "0", the first three will resolve to boolean true and rest to boolean false&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;        public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            string value = reader.GetString();
            string chkValue = value.ToLower();
            if (chkValue.Equals("true") ||chkValue.Equals("yes") || chkValue.Equals("1") )
            {
                return true;
            }
            if (value.ToLower().Equals("false") ||chkValue.Equals("no") || chkValue.Equals("0"))
            {
                return false;
            }
            throw new JsonException();

        }

&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Similarly, Override the &lt;code&gt;&lt;strong&gt;Write&lt;/strong&gt;&lt;/code&gt; method if you want to convert the boolean value to a string while doing serialization&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; public override void Write( Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
        {
            switch (value)
            {
                case true:
                    writer.WriteStringValue("true");
                    break;
                case false:
                    writer.WriteStringValue("false");
                    break;
              
            }

        }&lt;br&gt;&lt;br&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Wire our converter method to the API. We can do that in multiple ways, either we can register the converter through &lt;strong&gt;&lt;code&gt;JsonSerializerOptions&lt;/code&gt;&lt;/strong&gt;or by placing the &lt;strong&gt;&lt;code&gt;[JsonConverter] &lt;/code&gt;&lt;/strong&gt;on the&amp;nbsp;property as shown below.&lt;/p&gt;
&lt;p&gt;
&lt;pre&gt;&lt;code&gt;var options  = new JsonSerializerOptions();
options.Converters.Add(new BooleanConverter());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[JsonConverter(typeof(BooleanConverter))]
public bool IsInStock { get; set; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let's go for the first approach and see how it solves the problem. Let's modify the DeserializeData method shown in&amp;nbsp;the first part as below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;        public List&amp;lt;Product&amp;gt; DeserializeData(string productList)
        {
             var options  = new JsonSerializerOptions();
             options.Converters.Add(new BooleanConverter());

            return JsonSerializer.Deserialize&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt;(productList,options);
        }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here's the code in full&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;ConverterSample.cs&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Collections.Generic;

namespace JsonTextApi
{

    class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime LastUpdatedOn { get; set; }
        public bool IsInStock { get; set; }
    }
    class ConverterSample
    {
        public List&amp;lt;Product&amp;gt; DeserializeData(string productList)
        {
             var options  = new JsonSerializerOptions();
             options.Converters.Add(new BooleanConverter());

            return JsonSerializer.Deserialize&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt;(productList,options);
        }
        public string SerializeData(List&amp;lt;Product&amp;gt;  productList)
        {
            var options  = new JsonSerializerOptions() {WriteIndented = true };
            options.Converters.Add(new BooleanConverter());

            return JsonSerializer.Serialize&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt;(productList, options);
        }

    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Program.cs&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;
using System.Collections.Generic;

namespace JsonTextApi
{
    class Program
    {
        static void Main(string[] args)
        {
            ConverterSample obj = new ConverterSample();
            var objProduct = new Product();
            //input json is read from the file
            var productJson = File.ReadAllText("input.json");
            Console.WriteLine(productJson);
            Console.ReadLine();
            var items = obj.DeserializeData(productJson);
            
            foreach(var item in items)
            {
                Console.WriteLine($"{item.Id}, {item.Name}, {item.IsInStock}");
            }

        }

    }
}

&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;INPUT STRING
=====================
[
    {
        "Id": 1026,
        "Name": "Echo Dot",
        "Description": "Smart speakers from Amazon",
        "IsInStock": "no"
    },
    {
        "Id": 8084,
        "Name": "Chromecast",
        "Description": "Stream content to TV",
        "IsInStock": "yes"
    },
    {
        "Id": 9096,
        "Name": "iPhone",
        "Description": "Latest one from Apple",
        "IsInStock": "no"
    }
]

DESERIALIZED DATA
=====================
1026, Echo Dot, False
8084, Chromecast, True
9096, iPhone, False
&lt;/samp&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;Similarly, for serializing the data, you can hook up the convertor to &lt;strong&gt;&lt;code&gt;JsonSerializerOptions&lt;/code&gt;&lt;/strong&gt; object and pass it on to the&amp;nbsp;&lt;strong&gt;&lt;code&gt;Serialize&lt;/code&gt;&lt;/strong&gt; method. Please refer to the SerializeData method in the ConverterSample.cs give above for the implementation.&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/blog/posts/the-all-new-system-text-json-api-in-net-core" rel="dofollow" title="Serializing &amp;amp; Deserializing JSON in .NET Core 3.0"&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;Part 1 : Serializing and Deserializing&lt;span&gt;&amp;nbsp;&lt;/span&gt;Json&lt;span&gt;&amp;nbsp;&lt;/span&gt;in .NET Core 3.0 using System.Text.Json API&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span data-offset-key="6r4os-1-0"&gt;&lt;span data-text="true"&gt;&lt;a href="https://www.techrepository.in/blog/posts/step-by-step-guide-to-serialize-and-deserialize-json-using-system-text-json" rel="dofollow" title="Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json"&gt;Part 2: Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;</description><pubDate>Wed, 14 Aug 2019 06:07:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/avoid-conversion-errors-by-using-custom-converters-in-system-text-json-api-net-core-3-0</guid></item><item><title>Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json</title><link>https://www.techrepository.in:443/blog/posts/step-by-step-guide-to-serialize-and-deserialize-json-using-system-text-json</link><description>&lt;div class="alert alert-warning"&gt;The post is based on .NET Core 3.0 version.&lt;/div&gt;
&lt;blockquote class="blockquote"&gt;
&lt;p class="mb-0"&gt;Update : In preview 7 few changes were made to the API. For serialization use Serialize method instead of ToString and Deserialize method instead of Parse. Post updated to reflect these changes. SDK version : 3.0.100-preview7-012821&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In the &lt;a href="https://www.techrepository.in/blog/posts/the-all-new-system-text-json-api-in-net-core" rel="dofollow" target="_blank" title="Serializing and Deserializing JSON in .NET Core 3.0"&gt;last post&lt;/a&gt;, I have already given an overview of the&amp;nbsp;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.json?view=netcore-3.0" rel="nofollow" target="_blank" title="System.Text.Json API Documentation"&gt;System.Text.Json&lt;/a&gt; API that is going to be&amp;nbsp;introduced with the release with &lt;a href="https://dotnet.microsoft.com/download/dotnet-core/3.0y9Eem90XqI376y" rel="nofollow" target="_blank" title="Download .NET Core 3.0"&gt;.NET Core 3.0&lt;/a&gt;. This API will replace the Json.NET library by&amp;nbsp;&lt;a href="https://www.newtonsoft.com" rel="nofollow" target="_blank" title="About Newtonsoft"&gt;Newtonsoft&lt;/a&gt; which is baked into the framework for doing serialization and deserialization of JSON. You can read more about it &lt;a href="https://www.techrepository.in/blog/posts/the-all-new-system-text-json-api-in-net-core" rel="dofollow" target="_blank" title="Serializing and Deserializing JSON in .NET Core"&gt;using this link.&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Step 1: Refer the namespaces&lt;/h2&gt;
&lt;p&gt;Add the following lines in your code. If you are working .NET Core 3 project, then there is no need to add any NuGet packages to your project. For .NET Standard and .NET Framework project, install the &lt;a href="https://nuget.org/packages/System.Text.Json" target="_blank" rel="nofollow" title="System.Text.Json NuGet package"&gt;System.Text.Json NuGet package&lt;/a&gt;. Make sure that Preview is enabled and select install version 4.6.0-preview6.19303.8 or higher&lt;/p&gt;
&lt;pre&gt;using System.Text.Json;&lt;br&gt;using System.Text.Json.Serialization;&lt;/pre&gt;
&lt;h2&gt;Step 2: Serializing an object into &lt;g class="gr_ gr_37 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="37" data-gr-id="37"&gt;JSON&lt;/g&gt; string&lt;/h2&gt;
&lt;p&gt;Serialization is the process of converting an object into a format that can be saved. JSON is one of the most preferred format for encoding object into strings. You will be able to do this conversion by calling the &lt;strong&gt;&lt;em&gt;ToString&lt;/em&gt;&lt;/strong&gt; method in the &lt;strong&gt;&lt;em&gt;JsonSerializer&lt;/em&gt; &lt;/strong&gt;class available in the &lt;strong&gt;&lt;em&gt;System.Text.Json API&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;For example, to convert a Dictionary object to a JSON string we can use the following statement&lt;/p&gt;
&lt;pre&gt;JsonSerializer.ToString&amp;lt;Dictionary&amp;lt;string,object&amp;gt;&amp;gt;(dictObj)&lt;/pre&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-9668277581503568" data-ad-slot="4913572023"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;script src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"&gt;&lt;/script&gt;
&lt;p&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Code Snippet&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;using System;
using System.Text.Json;
using System.Text.Json.Serialization;

using System.Collections.Generic;

namespace JsonTextApi
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary&amp;lt;string,object&amp;gt; dictObj = new Dictionary&amp;lt;string,object&amp;gt;();

            dictObj.Add("name","Amal");
            dictObj.Add("age",20);
            dictObj.Add("country","India");
            
            Console.WriteLine("\nJSON Object");
            Console.WriteLine("=========================\n");
            foreach(var item in dictObj )
            {
                    Console.WriteLine($"{item.Key} -&amp;gt; {item.Value}");
            }
            Console.WriteLine("\nConverting back to text");
            Console.WriteLine("=========================\n");
            Console.WriteLine(JsonSerializer.ToString&amp;lt;Dictionary&amp;lt;string,object&amp;gt;&amp;gt;(dictObj));
            Console.ReadLine();
        }
    }
}

&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp; &lt;img alt="Serializing dictionary object to json using .NET Core 3.0 JSON API" src="https://www.techrepository.in/Media/Default/images/dotnet-core/all-new-json-api/convert-to-string-output.PNG" width="506" height="274"&gt;&lt;/p&gt;
&lt;h2&gt;&lt;br&gt;Step 3: Deserializing JSON&lt;/h2&gt;
&lt;p&gt;Deserialization is the process of converting a string in JSON format to a&amp;nbsp;custom data type. Consider the following JSON string which has got three properties namely name, age, and country that needs to be converted to a &lt;strong&gt;&lt;em&gt;Dictionary&lt;/em&gt;&lt;/strong&gt; object&lt;/p&gt;
&lt;pre&gt;{ "name":"Amal", "age":20 , "country": "India" }&lt;/pre&gt;
&lt;p&gt;For that, we can make use of the &lt;em&gt;&lt;strong&gt;Parse&lt;/strong&gt;&lt;/em&gt; method available in the &lt;strong&gt;&lt;em&gt;JsonSerializer&lt;/em&gt; &lt;/strong&gt;class as shown below&lt;/p&gt;
&lt;pre&gt;var items = JsonSerializer.Parse&amp;lt;Dictionary&amp;lt;string,object&amp;gt;&amp;gt;(jsonString);&lt;/pre&gt;
&lt;p&gt;The above statement will convert the string into a Dictionary object and we will be able to refer these using the Key and Value properties. Full code is given below along with the output.&lt;/p&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block;" data-ad-format="fluid" data-ad-layout-key="-59+aj-fq-ry+133" data-ad-client="ca-pub-9668277581503568" data-ad-slot="6218914831"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;script&gt;// &lt;![CDATA[
(adsbygoogle = window.adsbygoogle || []).push({});
// ]]&gt;&lt;/script&gt;
&lt;p&gt;&lt;strong&gt;Code Snippet&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;using System;
using System.Text.Json;
using System.Text.Json.Serialization;

using System.Collections.Generic;

namespace JsonTextApi
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonString = "{ \"name\":\"Amal\", \"age\":20 , \"country\": \"India\" }";
            Console.WriteLine("\nInput String");
            Console.WriteLine("=========================\n");
            Console.WriteLine(jsonString);
            Console.WriteLine("\nConverting text");
            Console.WriteLine("========================\n");&lt;br&gt;            var items =JsonSerializer.Parse&amp;lt;Dictionary&amp;lt;string,object&amp;gt;&amp;gt;(jsonString);
            foreach(var item in items)
            {
                    Console.WriteLine($"{item.Key} -&amp;gt; {item.Value}");
            }
            Console.ReadLine();

        }
    }
}
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img alt="Deserializing json string to dictionary object using .NET Core 3.0 JSON API" src="https://www.techrepository.in/Media/Default/images/dotnet-core/all-new-json-api/parse-output.PNG" width="543" height="254"&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/blog/posts/the-all-new-system-text-json-api-in-net-core" target="_blank"&gt;Part &lt;g class="gr_ gr_32 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="32" data-gr-id="32"&gt;1 :&lt;/g&gt; Serializing and Deserializing &lt;g class="gr_ gr_31 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="31" data-gr-id="31"&gt;Json&lt;/g&gt; in .NET Core 3.0 using System.Text.Json API&lt;/a&gt;&lt;/p&gt;</description><pubDate>Wed, 10 Jul 2019 15:43:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/step-by-step-guide-to-serialize-and-deserialize-json-using-system-text-json</guid></item><item><title>Serializing and Deserializing Json in .NET Core 3.0 using System.Text.Json API</title><link>https://www.techrepository.in:443/blog/posts/the-all-new-system-text-json-api-in-net-core</link><description>&lt;div class="alert alert-warning"&gt;The post is based on .NET Core 3.0 version&lt;/div&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;Last October, the .NET Core team at Microsoft has announced that they are stripping out &lt;a href="https://www.newtonsoft.com/json" title="Json.Net"&gt;Json.Net&lt;/a&gt;, a popular library used by developers for serializing and deserializing the JSON from the upcoming version of the framework. Along with that, they also announced that they are working on a new namespace&amp;nbsp;&lt;a href="https://nuget.org/packages/System.Text.Json" target="_blank" title="System.Text.Json"&gt;System.Text.Json&lt;/a&gt; in the framework for doing the same. With the release of the latest preview version of .NET Core 3.0, developers will now be able to make use of this namespace for performing JSON operations.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;The new namespace comes as part of the framework and there is no need to install any NuGet packages for using it. It has got the support for a reader, writer, document object model &lt;g class="gr_ gr_39 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="39" data-gr-id="39"&gt;and&lt;/g&gt; a serializer.&lt;/p&gt;
&lt;h2 style="text-align: justify;"&gt;Why a new library now?&lt;/h2&gt;
&lt;p style="text-align: justify;"&gt;JSON is one of the most widely used formats for data transfer especially from the client-side, be it web, mobile or IoT to the server backends. Most of the developers using the .NET Framework were relying on popular libraries like Json.NET because of the lack of the out of the box support provided by Microsoft.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;One of the major reasons to develop a new library was to increase the performance of the APIs. To integrate the support for &lt;em&gt;&lt;strong&gt;Span&amp;lt;T&amp;gt;&lt;/strong&gt;&lt;/em&gt; and &lt;em&gt;&lt;strong&gt;UTF-8&lt;/strong&gt;&lt;/em&gt; processing into the Json.NET library was nearly impossible because it would either break the existing functionality or the performance would have taken a hit&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;Even though Json.NET is getting updated very frequently for patches and new features, the tight integration with the ASP.NET Core framework meant these features got into the framework only when an update to the framework is released. So the .NET team has decided to strip the library from the framework and the developers will now be able to add it as a dependency in .NET core 3.0 meaning they will be free to choose whichever version of the Json.NET library they want&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;Now the developers &lt;g class="gr_ gr_45 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="45" data-gr-id="45"&gt;has&lt;/g&gt; got two options for performing the Json operations, either use System.Text.Json namespace or use Json.NET library which can be added as a NuGet package and using&amp;nbsp;&lt;span class="pl-mi1"&gt;AddNewtonsoftJson&lt;/span&gt; extension method.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-9668277581503568" data-ad-slot="4913572023"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;script src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"&gt;&lt;/script&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block;" data-ad-format="fluid" data-ad-layout-key="-59+aj-fq-ry+133" data-ad-client="ca-pub-9668277581503568" data-ad-slot="6218914831"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;script&gt;// &lt;![CDATA[
(adsbygoogle = window.adsbygoogle || []).push({});
// ]]&gt;&lt;/script&gt;
&lt;h2 style="text-align: justify;"&gt;Referring the library in your projects&lt;/h2&gt;
&lt;p style="text-align: justify;"&gt;&lt;strong&gt;.NET Core&lt;/strong&gt;&lt;br&gt;To use it in a .NET Core project, you will need to install the latest preview version of &lt;a href="https://dotnet.microsoft.com/download/dotnet-core/3.0" target="_blank" title=".NET Core"&gt;.NET Core&lt;/a&gt;.&lt;br&gt;&lt;br&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;strong&gt;.NET Standard, .NET Framework&lt;/strong&gt;&lt;br&gt;Install the&amp;nbsp;&lt;a href="https://www.nuget.org/packages/System.Text.Json/4.6.0-preview6.19303.8" target="_blank" title="System.Text.Json"&gt;System.Text.Json&lt;/a&gt; package from NuGet, make sure that you select Includes Preview and install version 4.6.0-preview6.19303.8 or higher&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;As of now, the support for OpenAPI / Swagger is still under development and most probably won't make be available in time for .NET Core 3.0 release.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;&lt;g class="gr_ gr_33 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="33" data-gr-id="33"&gt;Reference :&lt;/g&gt; &lt;a href="https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/" target="_blank" title="Try the new System.Text.Json APIs"&gt;Try the new System.Text.Json APIs&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://www.techrepository.in/blog/posts/step-by-step-guide-to-serialize-and-deserialize-json-using-system-text-json" target="_blank" title="Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json"&gt;Part &lt;/a&gt;&lt;g class="gr_ gr_60 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="60" data-gr-id="60"&gt;2 :&lt;/g&gt;&lt;a href="https://www.techrepository.in/blog/posts/step-by-step-guide-to-serialize-and-deserialize-json-using-system-text-json" target="_blank" title="Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json"&gt; Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json&lt;/a&gt;&lt;/p&gt;</description><pubDate>Wed, 03 Jul 2019 07:20:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/blog/posts/the-all-new-system-text-json-api-in-net-core</guid></item><item><title>Breaking Changes coming your way for ASP.NET Core  3.0</title><link>https://www.techrepository.in:443/breaking-changes-in-coming-your-way-for-asp-net-core-3-0</link><description>&lt;p&gt;Microsoft is in the process of releasing a new version for their .NET Core framework and there are some significant changes coming your way in that release. The most important ones are&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Removal of some sub-components&lt;/li&gt;
&lt;li&gt;Removal of the &lt;g class="gr_ gr_56 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="56" data-gr-id="56"&gt;PackageReference&lt;/g&gt; to Microsoft.AspNetCore.App&lt;/li&gt;
&lt;li&gt;Reducing duplication between NuGet packages and shared frameworks&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In v3.0, the ASP.NET Core framework will contain only those assemblies which are fully developed, supported and serviceable by Microsoft. They are doing this to reap all the benefits provided by the .NET Core shared frameworks like smaller deployment size, faster bootup time, centralized patching etc&lt;/p&gt;
&lt;h3&gt;Removal of some sub-components&lt;/h3&gt;
&lt;p&gt;In this version, they are removing some sub-components from the ASP.NET Core shared framework and most notable among them are the following&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Json.NET&amp;nbsp;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;JSON format has become so popular these days and has become the primary method for transferring data in all modern applications. But .NET doesn't have a built-in library to deal with JSON and relied on third-party libraries like JSON.NET for some time now. In ASP.NET Core, it has a tight integration with Json.NET which restricted the users to chose another library or a different version of Json.NET itself.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;So with version 3.0 they have decoupled Json.NET from the ASP.NET Core shared framework and is planning to replace it with high-performance JSON APIs. That means you will now need to add Json.NET as a separate package in you ASP.NET Core 3.0 project&lt;/p&gt;
&lt;p&gt;and then update your &lt;strong&gt;&lt;em&gt;ConfigureServices&amp;nbsp;&lt;/em&gt;&lt;/strong&gt;&lt;em&gt;&lt;/em&gt;method to include a call to &lt;strong&gt;&lt;em&gt;AddNewtonsoftJson() &lt;/em&gt;&lt;/strong&gt;as shown below&lt;/p&gt;
&lt;p&gt;
&lt;pre&gt;public void ConfigureServices(IServiceCollection services)
{
           services.AddMvc()
               .AddNewtonsoftJson();
}
&lt;/pre&gt;
&lt;p&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Entity Framework Core&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Entity Framework will ship purely as a NuGet package in ASP.NET Core 3.0 in line with the shipping model of all other data access libraries on .NET which helps to bring out new features as and when is done instead of waiting for the release of the next version of the shared framework. Also, even though it has moved out of the shared framework, it will retain the status as a library which is fully developed and supported by Microsoft.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Roslyn&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Most of us will make updates to views or pages and preview the changes in the browser without restarting the server. With this cleaning up of the shared framework also meant to drop the usage of Rosyln which supported the runtime compilation of the pages and views. Now the compilation will happen at the build time and if you want to preview changes you may need to rebuild it and run the application again. They are planning to bring in NuGet packages for optionally enabling runtime compilation in the future preview updates.&lt;/p&gt;
&lt;h3&gt;Removal of PackageReference to Microsoft.AspNetCore.App&lt;/h3&gt;
&lt;p&gt;In the versions prior to 3.0, references to &lt;strong&gt;&lt;em&gt;Microsoft.AspNetCore.&lt;g class="gr_ gr_62 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="62" data-gr-id="62"&gt;App&lt;/g&gt;&amp;nbsp;&lt;/em&gt;&lt;/strong&gt;was added as a PackageReference in your &lt;g class="gr_ gr_55 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="55" data-gr-id="55"&gt;csproj&lt;/g&gt; file&lt;/p&gt;
&lt;pre&gt;&amp;lt;ItemGroup&amp;gt;&lt;br&gt;      &amp;lt;PackageReference Include="Microsoft.AspNetCore.App" /&amp;gt;&lt;br&gt;&amp;lt;/ItemGroup&amp;gt;&lt;/pre&gt;
&lt;p&gt;In 3.0, the SDK will introduce a new item called &lt;strong&gt;&lt;em&gt;&amp;lt;FrameworkReference&amp;gt;&amp;nbsp;&lt;/em&gt;&lt;/strong&gt;which is going to replace the&amp;nbsp;&lt;strong&gt;&lt;em&gt;&amp;lt;PackageReference&amp;gt; &lt;/em&gt;&lt;/strong&gt;tag&lt;/p&gt;
&lt;pre&gt;&amp;lt;ItemGroup&amp;gt; 
     &amp;lt;FrameworkReference Include="Microsoft.AspNetCore.App" /&amp;gt; 
&amp;lt;/ItemGroup&amp;gt;
&lt;/pre&gt;
&lt;script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"&gt;&lt;/script&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-9668277581503568" data-ad-slot="4913572023"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;script&gt;// &lt;![CDATA[
(&lt;g class="gr_ gr_54 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="54" data-gr-id="54"&gt;adsbygoogle&lt;/g&gt; = window.&lt;g class="gr_ gr_53 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="53" data-gr-id="53"&gt;adsbygoogle&lt;/g&gt; || []).push({});
// ]]&gt;&lt;/script&gt;
&lt;h3&gt;Reducing duplication between NuGet packages and shared frameworks&lt;/h3&gt;
&lt;p&gt;With these incoming changes to the shared frameworks, now there is no need to add the assemblies in the &lt;strong&gt;&lt;em&gt;Microsoft.AspNetCore.&lt;g class="gr_ gr_65 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="65" data-gr-id="65"&gt;App&lt;/g&gt;&lt;/em&gt;&lt;/strong&gt;&amp;nbsp;as NuGet packages when you consume it in your packages. That meant&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://github.com/aspnet/Announcements/issues/325"&gt;https://github.com/aspnet/Announcements/issues/325&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://github.com/aspnet/AspNetCore/issues/3612" target="_blank"&gt;https://github.com/aspnet/AspNetCore/issues/3612&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://github.com/dotnet/announcements/issues/90" target="_blank"&gt;https://github.com/dotnet/announcements/issues/90&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://blogs.msdn.microsoft.com/webdev/2018/10/29/a-first-look-at-changes-coming-in-asp-net-core-3-0/" target="_blank"&gt;https://blogs.msdn.microsoft.com/webdev/2018/10/29/a-first-look-at-changes-coming-in-asp-net-core-3-0/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://github.com/aspnet/announcements/issues?q=is%3Aopen+is%3Aissue+milestone%3A3.0.0" target="_blank"&gt;https://github.com/aspnet/announcements/issues?q=is%3Aopen+is%3Aissue+milestone%3A3.0.0&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;
&lt;p&gt;</description><pubDate>Thu, 31 Jan 2019 19:42:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/breaking-changes-in-coming-your-way-for-asp-net-core-3-0</guid></item><item><title>Resilient Connections in Entity Framework Core</title><link>https://www.techrepository.in:443/resilient-connections-in-entity-framework-core</link><description>&lt;p style="text-align: justify;"&gt;When you work with databases in your application, you may face connection issues from time to time which is beyond our control. When this happens normally the application will raise a connection timeout or server not available exception. In Entity Framework core you can overcome this kind of scenario by setting up resilient connections with exponential retries.&amp;nbsp;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;The code snippet given below will retry to connect up to&amp;nbsp;10 times in case of a failure with a delay of 30 seconds in-between each try.&lt;/p&gt;
&lt;pre&gt;services.AddDbContext&lt;repositorycontext&gt;(o =&amp;gt;
{
    o.UseSqlServer(connectionString,
        sqlServerOptionsAction: options =&amp;gt;
        {
            options.EnableRetryOnFailure(maxRetryCount: 10,
                maxRetryDelay: TimeSpan.FromSeconds(30),
                errorNumbersToAdd: null);
        });
});	
&lt;/repositorycontext&gt;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p&gt;
&lt;script src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"&gt;&lt;/script&gt;
&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-9668277581503568" data-ad-slot="4913572023"&gt;&lt;/ins&gt;
&lt;script&gt;// &lt;![CDATA[
     (adsbygoogle = window.adsbygoogle || []).push({});
// ]]&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;Also, when&amp;nbsp;you enable retries in EF Core connections, each operation you perform will become its own retriable operation. So that means whenever we&amp;nbsp;perform a query or a call to the SaveChanges method, it will be retried as a unit during a transient failure&amp;nbsp;scenario. But when you initiate a transaction block in your code using BeginTransaction, then you are defining your own group that needs to treated as a single unit.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;So, in this case, you will need to manually invoke an execution strategy with a delegate method that contains all that &lt;g class="gr_ gr_18 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="18" data-gr-id="18"&gt;need&lt;/g&gt; to be executed as a block. So, when a transient failure occurs, the execution strategy will invoke the delegate again as part of the retry operation.&lt;/p&gt;
&lt;pre&gt;var strategy = blogContext.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =&amp;gt;
{

    using (var transaction = blogContext.Database.BeginTransaction())
    {
        blogContext.PostItems.Update(postItem);
        await blogContext.SaveChangesAsync();


        if (raisePostChangedEvent)
        await eventLogService.SaveEventAsync(postChangedEvent);
        transaction.Commit();
    }
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;Reference : &lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/modern-web-apps-azure-architecture/work-with-data-in-asp-net-core-apps"&gt;https://docs.microsoft.com/en-us/dotnet/standard/modern-web-apps-azure-architecture/work-with-data-in-asp-net-core-apps&lt;/a&gt;&lt;/p&gt;</description><pubDate>Fri, 05 Oct 2018 05:18:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/resilient-connections-in-entity-framework-core</guid></item><item><title>Deploying Resources to Azure using Azure Resource Manager Templates - Part #3</title><link>https://www.techrepository.in:443/deploying-resources-to-azure-using-azure-resource-manager-templates-part-3</link><description>&lt;p style="text-align: justify;"&gt;&lt;a href="https://www.techrepository.in/deploy-to-azure-using-an-empty-azure-resource-manager-templates-part-2" target="_blank"&gt;In the previous post&lt;/a&gt;, I had already explained the steps that are needed for deployment in Azure using an empty template. Let's&amp;nbsp;explore further and see how we can deploy a storage account in Azure using ARM Templates.&lt;/p&gt;
&lt;h3 style="text-align: justify;"&gt;Step 1: Create the template file&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;Open any text editor and create a template like the one given below. Save it as a JSON file with name &lt;strong&gt;&lt;em&gt;StorageTemplate.json&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;What we are doing with this template is that we have defined two parameters named &lt;em&gt;&lt;strong&gt;storageName&lt;/strong&gt; &lt;/em&gt;and &lt;strong&gt;&lt;em&gt;&lt;g class="gr_ gr_18 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="18" data-gr-id="18"&gt;storageLocation&lt;/g&gt;&lt;/em&gt;&lt;/strong&gt; for accepting the name of the resource as well as the location where it needs to be provisioned&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;And, under the resource section, we will use these parameters to set the name and the location properties for the storage account. Also, we will set the values for the resource type, kind and SKU&lt;/p&gt;
&lt;pre&gt;{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.1",
    "parameters": {
        "storageName": {
            "type": "string"
        },
        "storageLocation": {
            "type": "string"
        }
    },
    "variables": {},
    "resources": [
        {
          "apiVersion": "2016-01-01",
          "type": "Microsoft.Storage/storageAccounts",
          "name":  "[parameters('storageName')]",
          "location": "[parameters('storageLocation')]",  
          "sku": {
            "name": "Standard_LRS"
          },
          "kind": "Storage",
          "properties": {
          }
        }
   
    ],
    "outputs": {}
}


&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;h3 style="text-align: justify;"&gt;Step 2: Deploy the template using Azure CLI&lt;/h3&gt;
&lt;p style="text-align: justify;"&gt;Open up Powershell/Command prompt and execute the following command. Make sure that Azure CLI is already installed in your machine and configured to access your Azure subscription&lt;/p&gt;
&lt;pre&gt;az group deployment create --name EmptyARMDeployment --resource-group TechRepResGrp --template-file .\storage-template.json --parameters storageName=storagedemoO365 storageLocation=SouthIndia&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;img width="1015" height="547" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/az-deployment-storage.png"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;&lt;img width="1018" height="549" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/azure-portal-storage-deploym-details.png"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;&lt;img width="1022" height="551" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/azure-portal-storage-deployment.png"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;This command is very much similar to the one we used in the earlier post, the only difference is that we supplied the values for the parameters that will be used by the template to provision the storage account&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p style="text-align: justify;"&gt;</description><pubDate>Tue, 24 Jul 2018 05:18:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/deploying-resources-to-azure-using-azure-resource-manager-templates-part-3</guid></item><item><title>Deploy to Azure using an Empty Azure Resource Manager Templates - Part #2</title><link>https://www.techrepository.in:443/deploy-to-azure-using-an-empty-azure-resource-manager-templates-part-2</link><description>&lt;p&gt;In the &lt;a href="https://techrepository.in/deploying-resources-to-azure-using-azure-resource-manager-templates-part-1" target="_blank"&gt;earlier post&lt;/a&gt;, I went through the basic concepts and terminologies for deploying resources using the Azure Resource Manager(ARM) templates. Please refer it using&amp;nbsp;&lt;a href="https://techrepository.in/deploying-resources-to-azure-using-azure-resource-manager-templates-part-1" target="_blank"&gt;this link&lt;/a&gt; for quick reference. In this post, I will show you how to perform a deployment using an empty ARM template.&lt;/p&gt;
&lt;h3&gt;Step 1: Create an empty template&lt;/h3&gt;
&lt;p&gt;Create an empty template like the one given below using any text editor. Save as a JSON file with any name you want. In my case, I named it as&amp;nbsp;&lt;strong&gt;&lt;em&gt;EmptyTemplate.json&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
  },
  "variables": {
  },
  "resources": [
  ],
  "outputs": {
  }
}
&lt;/pre&gt;
&lt;h3&gt;Step 2: Configure Azure CLI&lt;/h3&gt;
&lt;p&gt;I am going to use&amp;nbsp;&lt;a href="https://docs.microsoft.com/en-us/cli/azure/" target="_blank"&gt;Azure CLI&lt;/a&gt; for doing the deployment. Before you start deploying, make sure that your local machine has got Azure CLI installed and configured correctly. Azure CLI is a cross-platform tool is available for download from &lt;a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli" target="_blank"&gt;here&lt;/a&gt;, which helps you to connect to your Azure subscription and execute various commands to manage and monitor it.&lt;/p&gt;
&lt;p&gt;The best way to verify it's installed or not by executing the below command.&lt;/p&gt;
&lt;pre&gt;az --version&lt;/pre&gt;
&lt;p&gt;&lt;img width="682" height="404" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/az-version_thumb.png"&gt;&lt;/p&gt;
&lt;p&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;p&gt;If everything is fine with your machine, we can move on and connect to an Azure subscription using,&lt;/p&gt;
&lt;pre&gt;az login&lt;/pre&gt;
&lt;p&gt;When this command is executed, it will give you a code which needs to be entered into a page using the&amp;nbsp;URL provided in the message from the browser. Once you submit that, your request will be authenticated and will show the list of subscription(s) upon successful operation&lt;/p&gt;
&lt;p&gt;&lt;img width="684" height="350" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/az-login_thumb.png"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;&lt;img width="683" height="360" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/azure-device-login_thumb.png"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;
&lt;h3&gt;Step 3: Create a resource group&lt;/h3&gt;
&lt;p&gt;&lt;br&gt;As I mentioned in the earlier post, every resource must reside in a resource group in Azure. For that, let's create one&lt;/p&gt;
&lt;pre&gt;az group create --name TechRepResGrp --location "South India"&lt;/pre&gt;
&lt;h3&gt;&lt;img width="709" height="366" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/az-group-create_thumb.png"&gt;&amp;nbsp;&lt;/h3&gt;
&lt;p&gt;
&lt;p&gt;&lt;img width="707" height="374" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/azure-portal-res-group_thumb.png"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;h3&gt;Step 4: Deploy using Empty Template&lt;/h3&gt;
&lt;p&gt;Now in the PowerShell window, go to the folder where you have saved the template file and execute the below command.&lt;/p&gt;
&lt;pre&gt;az group deployment create --name EmptyARMDeployment --resource-group TechRepResGrp --location "South India" --template-file EmptyTemplate.json&lt;/pre&gt;
&lt;p&gt;&lt;img width="715" height="372" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/az-empty-deployment_thumb.png"&gt;&lt;/p&gt;
&lt;p&gt;This will create a deployment with the mentioned name in the resource group provided in the command. You can verify it by going to the portal and see our's under the Deployment section.&lt;/p&gt;
&lt;p&gt;&lt;img width="722" height="384" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/azure-portal-empty-deployment_thumb.png"&gt;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;Since we used an empty template it won't be creating any resources. So in the next post, I&amp;nbsp;will guide you to &lt;g class="gr_ gr_426 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="426" data-gr-id="426"&gt;provision&lt;/g&gt; various resources using ARM templates.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
&lt;p&gt;</description><pubDate>Tue, 10 Jul 2018 19:42:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/deploy-to-azure-using-an-empty-azure-resource-manager-templates-part-2</guid></item><item><title>Deploying Resources to Azure using Azure Resource Manager Templates - Part #1</title><link>https://www.techrepository.in:443/deploying-resources-to-azure-using-azure-resource-manager-templates-part-1</link><description>&lt;p&gt;A component provisioned in Azure can contain a set of resources, say for example a Virtual Machine in Azure can have components such as Storage Accounts, Virtual Networks, IP address etc. And most of the times you may want to manage, deploy and delete these interdependent resources as a single entity. Azure Resource Manager(ARM) will help you to work with these resources in a single, coordinated operation.&lt;/p&gt;
&lt;p&gt;ARM supports various tools for interacting with its management layer, the most used ones include Azure CLI, Azure Powershell, REST APIs, and Azure Cloud Shell. The portal gets the newly released functionalities with 180 days of the initial release.&lt;/p&gt;
&lt;p&gt;The tools interact with the Azure Resource Manager API, which then passes it to the Resource Manager Service to perform the authentication and authorization of the request. Once this is completed, the Resource Manager then routes the request to the appropriate service for performing the requested operation.&lt;/p&gt;
&lt;p&gt;&lt;img width="483" height="293" alt="" src="https://www.techrepository.in/Media/Default/images/arm-templates/arm-block-diagram.PNG"&gt;&lt;/p&gt;
&lt;p&gt;Source:&amp;nbsp;&lt;a href="https://docs.microsoft.com/en-gb/azure/azure-resource-manager/resource-group-overview" target="_blank"&gt;docs.microsoft.com&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;h3&gt;&lt;strong&gt;Glossary&lt;/strong&gt;&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Resource&lt;/strong&gt;: is a manageable item in Azure. Typical examples include web app, database, IP address, virtual machine etc&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Resource Group&lt;/strong&gt;: is a container that holds the resources. A resource can belong only on one resource group. It is possible to add/delete resources from a resource group at any time and is also possible to move from one group to another. Also, it can reside in different regions too&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Resource Provider&lt;/strong&gt;: A resource provider offers a set of operations and resources for working with an Azure service. Examples include Microsoft.Compute, Microsoft.Web, Microsoft.Storage.&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Resource Manager Template&lt;/strong&gt;: is a file in JSON format which contains a declarative syntax for defining the infrastructure as well as configuration for your solution. This file will help you to deploy your resources repeatedly and in a consistent manner.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;ARM Template&amp;nbsp;Format&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;Given below is the barebone format for the template and of the keys among it, only $schema and contentVersion is mandatory&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;$schema&lt;/strong&gt;: specifies the location of the schema file which defines the version of the template language&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;contentVersion&lt;/strong&gt;: specifies the version of the template file. You can give any number in there which can be used to document the changes made to the template&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;parameters&lt;/strong&gt;: specifies the values that can be provided during deployment&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;variables&lt;/strong&gt;: values that are used in the template for simplifying language expressions in the template&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;functions&lt;/strong&gt;: user-defined functions available in the template&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;resources&lt;/strong&gt;: Resources that are going to be created/updated during the deployment&lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;outputs&lt;/strong&gt;: values that can be returned after the deployment&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "",
    "parameters": {  },
    "variables": {  },
    "functions": {  },
    "resources": [  ],
    "outputs": {  }
}
&lt;/pre&gt;
&lt;p&gt;
&lt;h3&gt;&lt;strong&gt;Sample Template File&lt;/strong&gt;&lt;/h3&gt;
&lt;pre&gt;{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.1",
    "parameters": {
        &amp;ldquo;resourceGroupName": {
            "type": "string"
        },
        "resourceGroupLocation": {
            "type": "string"
        }
    },
    "variables": {},
    "resources": [
        {
            "type": "Microsoft.Resources/resourceGroups",
            "apiVersion": "2018-05-01",
            "location": "[parameters('resourceGroupLocation')]",
            "name": "[parameters('resourceGroupName')]",
            "properties": {}
        }
    ],
    "outputs": {}
}
&lt;/pre&gt;
&lt;p&gt;&lt;br&gt;These can be deployed using various tools such as Azure Powershell, Azure CLI, Azure Portal/Cloud Shell, REST APIs. In the next post, I will show you how to use Azure CLI for doing the deployment.&lt;/p&gt;</description><pubDate>Wed, 04 Jul 2018 15:43:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/deploying-resources-to-azure-using-azure-resource-manager-templates-part-1</guid></item><item><title>Creating NuGet Package using .NET Core CLI</title><link>https://www.techrepository.in:443/creating-nuget-package-using-net-core-cli</link><description>&lt;p style="text-align: justify;"&gt;NuGet is a great tool&amp;nbsp;in managing your third-party dependencies as well as in distributing your own libraries. The &lt;em&gt;&lt;strong&gt;dotnet pack&lt;/strong&gt;&lt;/em&gt; command available in .NET Core CLI toolset will help you to build the project and creates a NuGet package. The output of this command will be a .nupkg file which can be used to push to a public registry like nuget.org or to any other private registries.&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;Let's start with a .NET Core class library project and see how we can pack that using the CLI toolchain&lt;/p&gt;
&lt;pre&gt;dotnet new class --name SampleLib&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;img src="https://www.techrepository.in/Media/Default/images/dotnet-core/create-package/create-classlib.jpg" alt="" class="img-responsive" width="1048" height="223"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img src="https://www.techrepository.in/Media/Default/images/dotnet-core/create-package/dotnet-new-output.jpg" alt="" class="img-responsive" width="766" height="275"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;It will create a new project with one file in C# inside it. Let's create a package using the below command&lt;/p&gt;
&lt;p&gt;&lt;!--more--&gt;&lt;/p&gt;
&lt;pre&gt;dotnet pack&amp;nbsp;&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;img src="https://www.techrepository.in/Media/Default/images/dotnet-core/create-package/dotnet-pack.jpg" alt="" class="img-responsive" width="1062" height="124"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;When it's executed it will search for the project file in the current directory, then restores the dependencies, builds the project if it's found and packages it. If your project is in a different location then you need to specify the path along with the project name.&lt;/p&gt;
&lt;script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"&gt;&lt;/script&gt;
&lt;p&gt;&lt;ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-9668277581503568" data-ad-slot="9068263828"&gt;&lt;/ins&gt;&lt;/p&gt;
&lt;p&gt;
&lt;script&gt;// &lt;![CDATA[
(&lt;g class="gr_ gr_26 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="26" data-gr-id="26"&gt;adsbygoogle&lt;/g&gt; = window.adsbygoogle || []).push({});
// ]]&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;&lt;img src="https://www.techrepository.in/Media/Default/images/dotnet-core/create-package/package-output.jpg" alt="" class="img-responsive" width="797" height="222"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;You can avoid the building of the project while creating the package by specifying the &lt;em&gt;&lt;strong&gt;--no-build&lt;/strong&gt;&lt;/em&gt; parameter along with the &lt;em&gt;&lt;strong&gt;pack&lt;/strong&gt; &lt;/em&gt;command&lt;/p&gt;
&lt;pre&gt;dotnet pack --no-build&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;img src="https://www.techrepository.in/Media/Default/images/dotnet-core/create-package/dotnet-pack-no-build.jpg" alt="" class="img-responsive" width="921" height="348"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;From the above images, you will see that the version of the package is always 1.0.0, to change that use the&amp;nbsp;&lt;em&gt;&lt;strong&gt;PackageVersion&amp;nbsp;&lt;/strong&gt;&lt;/em&gt;parameter. Also, to create the package in a custom location,&amp;nbsp;you can see make use of the --output parameter as shown below.&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;dotnet pack --output package /p:PackageVersion=2.0.0&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;&lt;img src="https://www.techrepository.in/Media/Default/images/dotnet-core/create-package/package-version.jpg" alt="" class="img-responsive" width="1057" height="381"&gt;&lt;/p&gt;
&lt;p style="text-align: justify;"&gt;Note:&amp;nbsp;Please note that the &lt;strong&gt;&lt;em&gt;dotnet pack&amp;nbsp;&lt;/em&gt;&lt;/strong&gt;command won't work for web projects by default in .NET Core 2.X. In some scenarios say while building a DevOps pipeline for your web application you may need to package your web project too. To enable this you will need to add the following snippet in your &lt;strong&gt;&lt;em&gt;.csproj&lt;/em&gt;&lt;/strong&gt; file&lt;/p&gt;
&lt;pre&gt;&amp;lt;PropertyGroup&amp;gt;
  &amp;lt;IsPackable&amp;gt;true&amp;lt;/IsPackable&amp;gt;
&amp;lt;/PropertyGroup&amp;gt;
&lt;/pre&gt;
&lt;p style="text-align: justify;"&gt;
&lt;p&gt;&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/SteB7E3eXow" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="allowfullscreen"&gt;&lt;/iframe&gt;&lt;/p&gt;</description><pubDate>Wed, 06 Jun 2018 15:43:00 GMT</pubDate><guid isPermaLink="true">https://www.techrepository.in:443/creating-nuget-package-using-net-core-cli</guid></item></channel></rss>