<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Satya Karki</title>
    <description>The latest articles on Forem by Satya Karki (@satyakarki).</description>
    <link>https://forem.com/satyakarki</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F911770%2Fdf2a83dd-3e56-4bff-af64-3d45f056f7b8.jpg</url>
      <title>Forem: Satya Karki</title>
      <link>https://forem.com/satyakarki</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/satyakarki"/>
    <language>en</language>
    <item>
      <title>Unlocking Sentiment Insights in .NET 9 with ML.NET</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Mon, 07 Apr 2025 02:33:45 +0000</pubDate>
      <link>https://forem.com/satyakarki/unlocking-sentiment-insights-in-net-9-with-mlnet-284f</link>
      <guid>https://forem.com/satyakarki/unlocking-sentiment-insights-in-net-9-with-mlnet-284f</guid>
      <description>&lt;p&gt;ML.NET is a tool for machine learning that was created by Microsoft. It’s designed for developers who are familiar with the .NET framework. With ML.NET, you can build, train, and deploy custom machine learning models without having to leave the .NET ecosystem. Thanks to the performance optimizations and seamless integration capabilities of .NET 9, ML.NET is an even better choice for adding intelligence to your applications. In this article, we’ll explore real-world use cases and provide sample code to help you implement them.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Makes ML.NET Special?
&lt;/h2&gt;

&lt;p&gt;Native .NET Integration: You can write machine learning code in C# or F#, using familiar tools like Visual Studio.&lt;br&gt;
Wide Range of Algorithms: It supports classification, regression, clustering, anomaly detection, and more.&lt;br&gt;
Model Builder: A GUI tool to simplify model creation for beginners.&lt;br&gt;
It can also handle large data sets and works with cloud-based .NET 9 apps. Pre-trained models work with ONNX, TensorFlow, and Azure Cognitive Services for more complex situations.&lt;/p&gt;
&lt;h2&gt;
  
  
  Sentiment Analysis
&lt;/h2&gt;

&lt;p&gt;Sentiment analysis is the process of determining the emotional tone behind text. It’s a powerful tool for businesses and developers. It can be used to gauge customer feedback, analyze social media trends, or enhance user experiences. Sentiment analysis can unlock valuable insights. With .NET 9 and ML.NET, Microsoft’s machine learning framework, developers can seamlessly integrate this capability into their applications without leaving the .NET ecosystem. In this article, we’ll show you how to create a sentiment analysis API in .NET 9 using ML.NET. We’ll provide practical code examples and tips for optimization.&lt;/p&gt;
&lt;h2&gt;
  
  
  Project Overview: Sentiment Analysis API
&lt;/h2&gt;

&lt;p&gt;We’ll build an ASP.NET Core Web API that predicts whether a piece of text expresses positive or negative sentiment. This example will use ML.NET to train a model and deploy it within a .NET 9 application, showing how simple and useful it is.&lt;/p&gt;

&lt;p&gt;For complete source code: Click &lt;a href="https://github.com/rijwanansari/dotnet9SentimentApi" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 1: Setting Up the Project
&lt;/h2&gt;

&lt;p&gt;Create a new ASP.NET Core Web API project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet new webapi -n dotnet9SentimentApi -f net9.0
cd dotnet9SentimentApi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open the folder in VS code. The project should be as shown below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F28v3tvhav3x9bnrssbdy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F28v3tvhav3x9bnrssbdy.png" alt="Image description" width="800" height="410"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s add the ML.NET NuGet package:&lt;/p&gt;

&lt;p&gt;You can either run command or do from VS code UI as illustrated below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet add package Microsoft.ML
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faphim6i7dz03gswssfzc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faphim6i7dz03gswssfzc.png" alt="Image description" width="799" height="601"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: Define the Data Models
&lt;/h2&gt;

&lt;p&gt;Create a folder named Models and add two classes: SentimentData and SentimentPrediction&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SentimentData.cs&lt;/strong&gt;: Represents the input data for the model.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace dotnet9SentimentApi.Models;

public record SentimentData
{
    public string Text { get; set; } = string.Empty;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;SentimentPrediction.cs&lt;/strong&gt;: Represents the model’s output.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace dotnet9SentimentApi.Models;

public record SentimentPrediction
{
    public bool Prediction { get; set; } // True = Positive, False = Negative
    public float Probability { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 3: Training a Simple Sentiment Model with ML.NET
&lt;/h2&gt;

&lt;p&gt;For simplicity, we’ll use a pre-trained model approach here, but ML.NET allows you to train your own model with a dataset. Create a &lt;strong&gt;SentimentModelTrainer.cs&lt;/strong&gt; class in a Services folder to simulate model setup:&lt;/p&gt;

&lt;p&gt;To train the model with your own data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private void TrainModel()
    {
        // Simulated training data (in practice, load from a file or database)
        var data = BuildTrainingData();

        var dataView = _mlContext.Data.LoadFromEnumerable(data);

        // Enhanced pipeline with text preprocessing
        var pipeline = _mlContext.Transforms.Text.FeaturizeText("Features", new Microsoft.ML.Transforms.Text.TextFeaturizingEstimator.Options
        {
            WordFeatureExtractor = new Microsoft.ML.Transforms.Text.WordBagEstimator.Options(),
            StopWordsRemoverOptions = new Microsoft.ML.Transforms.Text.StopWordsRemovingEstimator.Options()
        }, nameof(SentimentTrainingData.Text))
            .Append(_mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(labelColumnName: nameof(SentimentTrainingData.Sentiment)));

        // Train the model
        _model = pipeline.Fit(dataView);

        // Optional: Save the model for reuse
        _mlContext.Model.Save(_model, dataView.Schema, "sentiment_model.zip");
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: In a real-world scenario, you’d train with a larger dataset (e.g., from a CSV file) and save the model using _mlContext.Model.Save().&lt;/p&gt;

&lt;p&gt;Complete &lt;strong&gt;SentimentModelTrainer.cs&lt;/strong&gt; class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;
using dotnet9SentimentApi.Models;
using Microsoft.ML;

namespace dotnet9SentimentApi.Services;

public &amp;lt;em&amp;gt;class&amp;lt;/em&amp;gt; SentimentModelTrainer
{
    private readonly MLContext _mlContext;
    private ITransformer _model;

    public SentimentModelTrainer()
    {
        _mlContext = new MLContext();
        TrainModel();

    }

    private void TrainModel()
    {
        // Simulated training data (in practice, load from a file or database)
        var data = BuildTrainingData();

        var dataView = _mlContext.Data.LoadFromEnumerable(data);
        // Enhanced pipeline with text preprocessing
        var pipeline = _mlContext.Transforms.Text.FeaturizeText("Features", new Microsoft.ML.Transforms.Text.TextFeaturizingEstimator.Options
        {
            WordFeatureExtractor = new Microsoft.ML.Transforms.Text.WordBagEstimator.Options(),
            StopWordsRemoverOptions = new Microsoft.ML.Transforms.Text.StopWordsRemovingEstimator.Options()
        }, nameof(SentimentTrainingData.Text))
            .Append(_mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(labelColumnName: nameof(SentimentTrainingData.Sentiment)));

        // Train the model
        _model = pipeline.Fit(dataView);

        // Optional: Save the model for reuse
        _mlContext.Model.Save(_model, dataView.Schema, "sentiment_model.zip");
    }

    public SentimentPrediction Predict(string text)
    {
        var predictionEngine = _mlContext.Model.CreatePredictionEngine&amp;lt;SentimentData, SentimentPrediction&amp;gt;(_model);
        return predictionEngine.Predict(new SentimentData { Text = text });
    }

    //build training data
    private List&amp;lt;SentimentTrainingData&amp;gt; BuildTrainingData()
    {
        return new List&amp;lt;SentimentTrainingData&amp;gt;
        {
            new() { Text = "I love this product!", Sentiment = true },
            new() { Text = "This is terrible.", Sentiment = false },
            new() { Text = "The weather is nice!", Sentiment = true },
            new() { Text = "Horrible service, never again.", Sentiment = false },
            new() { Text = "Absolutely fantastic experience!", Sentiment = true },
            new() { Text = "It’s a complete disaster.", Sentiment = false },
            new() { Text = "I’m so happy with this!", Sentiment = true },
            new() { Text = "Disappointing and awful.", Sentiment = false },
            new() { Text = "I’m so impressed!", Sentiment = true },
            new() { Text = "I’m never coming back.", Sentiment = false },
            new() { Text = "I’m so excited!", Sentiment = true },
            new() { Text = "I’m so disappointed.", Sentiment = false },
            new() { Text = "I’m so pleased with this!", Sentiment = true },
            new() { Text = "I’m so upset.", Sentiment = false },
            new() { Text = "I’m so satisfied with this!", Sentiment = true },
            new() { Text = "I’m so angry.", Sentiment = false },
            new() { Text = "I’m so grateful for this!", Sentiment = true },
            new() { Text = "I’m so annoyed.", Sentiment = false },
            new() { Text = "I’m so thankful for this!", Sentiment = true }
        };
    }


}
public record SentimentTrainingData
{
    public string Text { get; set; } = string.Empty;
    public bool Sentiment { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4: Build the API Controller
&lt;/h2&gt;

&lt;p&gt;Create a SentimentController in the Controllers folder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using dotnet9SentimentApi.Models;
using dotnet9SentimentApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace dotnet9SentimentApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public &amp;lt;em&amp;gt;class&amp;lt;/em&amp;gt; SentimentController : ControllerBase
    {
        private readonly SentimentModelTrainer _modelTrainer;

        public SentimentController(SentimentModelTrainer modelTrainer)
        {
            _modelTrainer = modelTrainer;
        }

        [HttpPost("analyze")]
        public ActionResult&amp;lt;SentimentPrediction&amp;gt; AnalyzeSentiment([FromBody] SentimentData input)
        {
            if (string.IsNullOrEmpty(input.Text))
                return BadRequest("Text cannot be empty.");

            var prediction = _modelTrainer.Predict(input.Text);
            return Ok(new { Sentiment = prediction.Prediction ? "Positive" : "Negative", Confidence = prediction.Probability });
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 5: Register Services in Program.cs
&lt;/h2&gt;

&lt;p&gt;Update &lt;strong&gt;Program.cs&lt;/strong&gt; to use minimal APIs and register the service:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Add services to the container
builder.Services.AddControllers();
builder.Services.AddSingleton&amp;lt;SentimentModelTrainer&amp;gt;();

// Configure the HTTP request pipeline
app.UseHttpsRedirection();
app.MapControllers();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Complete code for &lt;strong&gt;Program.cs&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using dotnet9SentimentApi.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

// Add services to the container
builder.Services.AddControllers();
builder.Services.AddSingleton&amp;lt;SentimentModelTrainer&amp;gt;();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

// Configure the HTTP request pipeline
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our solution is ready to test.&lt;/p&gt;

&lt;p&gt;For complete source code: &lt;a href="https://github.com/rijwanansari/dotnet9SentimentApi" rel="noopener noreferrer"&gt;Click here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Test the API&lt;br&gt;
&lt;code&gt;dotnet run&lt;/code&gt;&lt;br&gt;
You can use postman to test the api or http file in VS code. I will test using VS code .http file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@dotnet9SentimentApi_HostAddress = http://localhost:5288

# post analyze sentiment
POST {{dotnet9SentimentApi_HostAddress}}/api/sentiment/analyze
Content-Type: application/json

{
  "text": "I am not happy with the result!"
}

###
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result is shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9q0qqqggazgu082kgchu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9q0qqqggazgu082kgchu.png" alt="Image description" width="800" height="352"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The result is not as expected – indicates an issue with the sentiment analysis model’s training or configuration. Given the tiny dataset and simplistic setup in the original sample, the model isn’t learning meaningful patterns.&lt;/p&gt;

&lt;p&gt;However, we can improve the result with more training data and testing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Enhancing the Project
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Scalability: Deploy to Azure with container support for cloud-native scaling.&lt;/li&gt;
&lt;li&gt;Model Accuracy: Use a real dataset (e.g., IMDB reviews) and train with more sophisticated algorithms like FastTree.&lt;/li&gt;
&lt;li&gt;Performance: Cache predictions for frequently analyzed text using MemoryCache.&lt;/li&gt;
&lt;li&gt;Integration: Extend with Azure Cognitive Services or TensorFlow.NET for advanced AI capabilities.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Sentiment analysis in .NET 9 using ML.NET is easy to use and powerful. It lets developers add intelligence to their applications with little complexity. This API shows the basics, but there are many possibilities. You can integrate it with real-time data, use .NET 9’s cloud-native features, or enhance it with pre-trained models. As you explore further, you will see that ML.NET and .NET 9 together offer a robust platform for sentiment analysis and more.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>ai</category>
      <category>machinelearning</category>
      <category>dotnetcore</category>
    </item>
    <item>
      <title>Middleware Mastery in .NET with Essential Techniques and Hands-On Examples</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Thu, 20 Mar 2025 14:53:40 +0000</pubDate>
      <link>https://forem.com/satyakarki/middleware-mastery-in-net-with-essential-techniques-and-hands-on-examples-51ga</link>
      <guid>https://forem.com/satyakarki/middleware-mastery-in-net-with-essential-techniques-and-hands-on-examples-51ga</guid>
      <description>&lt;p&gt;Middleware is an essential component of the ASP.NET request pipeline. It allows developers to run code during both the request and response lifecycle. In this article, we will explore what middleware is, and how it works, and provide real-world practical use cases with complete code examples.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Middleware in .NET?
&lt;/h2&gt;

&lt;p&gt;Middleware in .NET is a software component that processes HTTP requests and responses. It is executed in a pipeline, where each middleware component can perform an action and decide whether to pass the request further or return a response.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Characteristics of Middleware
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Executes sequentially in the request pipeline.&lt;/li&gt;
&lt;li&gt;Can modify request and response objects.&lt;/li&gt;
&lt;li&gt;Can terminate request processing if needed.&lt;/li&gt;
&lt;li&gt;Supports dependency injection.&lt;/li&gt;
&lt;li&gt;Used for authentication, logging, rate limiting, and more.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How Middleware Works in .NET?
&lt;/h2&gt;

&lt;p&gt;Middleware components are registered in the Program.cs file using the UseMiddleware() method or inline with app.Use(). The middleware pipeline is executed in the order they are added.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Receives an HttpContext&lt;/li&gt;
&lt;li&gt;Performs operations (e.g., logging, authentication, etc.)&lt;/li&gt;
&lt;li&gt;Calls the next middleware in the pipeline (or short-circuits the request)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Real-world middleware Use Cases with Code Examples
&lt;/h2&gt;

&lt;h2&gt;
  
  
  1. Request Logging Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; Logging request and response details for debugging and monitoring.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger&amp;lt;RequestLoggingMiddleware&amp;gt; _logger;

    public RequestLoggingMiddleware(RequestDelegate next, ILogger&amp;lt;RequestLoggingMiddleware&amp;gt; logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        _logger.LogInformation($"Request: {context.Request.Method} {context.Request.Path}");
        await _next(context);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the middleware as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseMiddleware&amp;lt;LoggingMiddleware&amp;gt;(); //register here!!

app.Run(async (context) =&amp;gt;
{
    await context.Response.WriteAsync("Hello, Middleware!");
});

app.Run();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Custom Authentication Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; Checking if a request contains a valid API key before processing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string API_KEY = "123456"; // Hardcoded for demonstration

    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue("X-API-KEY", out var extractedApiKey) || extractedApiKey != API_KEY)
        {
            context.Response.StatusCode = 401; // Unauthorized
            await context.Response.WriteAsync("Invalid API Key.");
            return;
        }

        await _next(context);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the middleware&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.UseMiddleware&amp;lt;ApiKeyMiddleware&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Exception Handling Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; Global error handling to return meaningful error responses.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ExceptionHandlingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger&amp;lt;ExceptionHandlingMiddleware&amp;gt; _logger;

    public ExceptionHandlingMiddleware(RequestDelegate next, ILogger&amp;lt;ExceptionHandlingMiddleware&amp;gt; logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An unhandled exception occurred.");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsync("An unexpected error occurred.");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the middleware.&lt;br&gt;
&lt;code&gt;app.UseMiddleware&amp;lt;ExceptionHandlingMiddleware&amp;gt;();&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Rate Limiting Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case&lt;/strong&gt;: Preventing abuse by limiting the number of requests from a client in a given time period.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class RateLimitingMiddleware
{
    private static readonly Dictionary&amp;lt;string, (int Count, DateTime LastRequest)&amp;gt; _clients = new();
    private readonly RequestDelegate _next;
    private const int Limit = 5;
    private static readonly TimeSpan TimeWindow = TimeSpan.FromMinutes(1);

    public RateLimitingMiddleware(RequestDelegate next) =&amp;gt; _next = next;

    public async Task Invoke(HttpContext context)
    {
        var clientIP = context.Connection.RemoteIpAddress?.ToString();
        if (clientIP == null || !_clients.ContainsKey(clientIP) || DateTime.UtcNow - _clients[clientIP].LastRequest &amp;gt; TimeWindow)
            _clients[clientIP] = (1, DateTime.UtcNow);
        else if (_clients[clientIP].Count &amp;gt;= Limit)
        {
            context.Response.StatusCode = 429;
            await context.Response.WriteAsync("Rate limit exceeded. Try again later.");
            return;
        }
        else
            _clients[clientIP] = (_clients[clientIP].Count + 1, DateTime.UtcNow);

        await _next(context);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the middleware&lt;br&gt;
&lt;code&gt;app.UseMiddleware&amp;lt;RateLimitingMiddleware&amp;gt;();&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  5. Content Compression Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case&lt;/strong&gt;: Compressing responses to improve performance.&lt;/p&gt;

&lt;p&gt;We can use built-in Response Compression or custom Content Compression Middleware.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;:built-in&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var builder = WebApplication.CreateBuilder(args);

builder.Services.AddResponseCompression(options =&amp;gt;
{
    options.EnableForHttps = true; // Enable compression for HTTPS requests
    options.Providers.Add&amp;lt;BrotliCompressionProvider&amp;gt;(); // Brotli compression
    options.Providers.Add&amp;lt;GzipCompressionProvider&amp;gt;();  // Gzip compression
});

builder.Services.Configure&amp;lt;GzipCompressionProviderOptions&amp;gt;(options =&amp;gt;
{
    options.Level = System.IO.Compression.CompressionLevel.Fastest; // Adjust compression level
});

var app = builder.Build();

app.UseResponseCompression(); // Enable middleware

app.MapGet("/", async context =&amp;gt;
{
    var responseText = new string('A', 1000); // Large response for compression testing
    await context.Response.WriteAsync(responseText);
});

app.Run();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. Custom Content Compression Middleware
&lt;/h2&gt;

&lt;p&gt;If you need more control over compression, you can write a custom middleware.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CustomCompressionMiddleware
{
    private readonly RequestDelegate _next;

    public CustomCompressionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var originalBodyStream = context.Response.Body;
        using var compressedStream = new MemoryStream();
        using var gzipStream = new GZipStream(compressedStream, CompressionMode.Compress, true);

        context.Response.Body = gzipStream;
        context.Response.Headers.Add("Content-Encoding", "gzip"); // Indicate compression

        await _next(context);

        gzipStream.Close();
        compressedStream.Seek(0, SeekOrigin.Begin);
        await compressedStream.CopyToAsync(originalBodyStream);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  7. Request Timing Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case&lt;/strong&gt;: Measuring the time taken to process a request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger&amp;lt;RequestTimingMiddleware&amp;gt; _logger;

    public RequestTimingMiddleware(RequestDelegate next, ILogger&amp;lt;RequestTimingMiddleware&amp;gt; logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        var stopwatch = Stopwatch.StartNew();
        await _next(context);
        stopwatch.Stop();

        _logger.LogInformation($"Request took {stopwatch.ElapsedMilliseconds} ms");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the middleware&lt;br&gt;
&lt;code&gt;app.UseMiddleware&amp;lt;RequestTimingMiddleware&amp;gt;();&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  8. Maintenance Mode Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case&lt;/strong&gt;: Temporarily disabling access to an application during updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class MaintenanceMiddleware
{
    private readonly RequestDelegate _next;
    private readonly bool _isUnderMaintenance = true; // Change to false to disable maintenance mode

    public MaintenanceMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (_isUnderMaintenance)
        {
            context.Response.StatusCode = 503;
            await context.Response.WriteAsync("The site is under maintenance. Please try again later.");
            return;
        }

        await _next(context);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the middleware&lt;br&gt;
&lt;code&gt;app.UseMiddleware&amp;lt;MaintenanceMiddleware&amp;gt;();&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  9. Geo-Blocking Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case&lt;/strong&gt;: Restricting access to specific countries based on IP address.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class GeoBlockingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly List&amp;lt;string&amp;gt; _blockedCountries = new() { "CN", "RU", "IR" }; // Example blocked countries

    public GeoBlockingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        string userCountry = GetUserCountry(context); // Implement this based on an IP lookup service

        if (_blockedCountries.Contains(userCountry))
        {
            context.Response.StatusCode = 403;
            await context.Response.WriteAsync("Access denied for your region.");
            return;
        }

        await _next(context);
    }

    private string GetUserCountry(HttpContext context)
    {
        // Placeholder logic, use a third-party API or database lookup to determine the country from IP
        return "US"; // Assume US for this example
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register middleware&lt;br&gt;
&lt;code&gt;app.UseMiddleware&amp;lt;GeoBlockingMiddleware&amp;gt;();&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  10. Request IP Logger Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case&lt;/strong&gt;: Logging the IP address of every client making a request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class RequestIpLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger&amp;lt;RequestIpLoggingMiddleware&amp;gt; _logger;

    public RequestIpLoggingMiddleware(RequestDelegate next, ILogger&amp;lt;RequestIpLoggingMiddleware&amp;gt; logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        var ip = context.Connection.RemoteIpAddress?.ToString();
        _logger.LogInformation($"Request received from IP: {ip}");

        await _next(context);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register middleware&lt;br&gt;
&lt;code&gt;app.UseMiddleware&amp;lt;RequestIpLoggingMiddleware&amp;gt;();&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  11. User Activity Tracking Middleware
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class UserActivityMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger&amp;lt;UserActivityMiddleware&amp;gt; _logger;

    public UserActivityMiddleware(RequestDelegate next, ILogger&amp;lt;UserActivityMiddleware&amp;gt; logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        var user = context.User.Identity?.Name ?? "Anonymous";
        var path = context.Request.Path;
        _logger.LogInformation($"User: {user} accessed {path} at {DateTime.UtcNow}");

        await _next(context);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Register middleware&lt;br&gt;
&lt;code&gt;app.UseMiddleware&amp;lt;UserActivityMiddleware&amp;gt;();&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  12. Dark Mode Cookie Middleware
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use Case&lt;/strong&gt;: Storing user preferences (like dark mode) in cookies.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DarkModeMiddleware
{
    private readonly RequestDelegate _next;

    public DarkModeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Cookies.ContainsKey("DarkMode"))
        {
            context.Response.Cookies.Append("DarkMode", "false");
        }

        await _next(context);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Likewise, we can use middleware in .NET for several other use cases.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Middleware is a powerful feature in .NET applications that allows developers to enhance security, optimize performance, and improve user experience. The examples above demonstrate how middleware can be used for logging, authentication, exception handling, rate limiting, rate timing response compression, and caching.&lt;/p&gt;

&lt;p&gt;By leveraging middleware effectively, developers can build scalable, maintainable, and high-performance applications. Whether you’re securing APIs, optimizing request handling, or improving efficiency, middleware provides a flexible and extensible solution for modern .NET applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reference&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dotnetcopilot.com/mastering-middleware-in-net-practical-use-cases-with-full-code-examples/" rel="noopener noreferrer"&gt;dotnetcopilot.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>aspdotnet</category>
      <category>dotnetcore</category>
      <category>csharp</category>
    </item>
    <item>
      <title>ASP.NET Core Security: Using Azure Key Vault for Secret Storage</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Mon, 17 Mar 2025 09:31:32 +0000</pubDate>
      <link>https://forem.com/satyakarki/aspnet-core-security-using-azure-key-vault-for-secret-storage-2eb5</link>
      <guid>https://forem.com/satyakarki/aspnet-core-security-using-azure-key-vault-for-secret-storage-2eb5</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In modern cloud applications, securely managing sensitive data like API keys, database connection strings, and certificates is crucial. Hardcoding secrets in configuration files pose security risks, making applications vulnerable to breaches. Azure Key Vault offers a secure and centralized solution to store and manage secrets, ensuring they are protected and accessible only to authorized services.&lt;/p&gt;

&lt;p&gt;This article provides a step-by-step guide to implementing Azure Key Vault in an ASP.NET Core application. You’ll learn how to store secrets in Key Vault, retrieve them dynamically in .NET applications, and configure secure access using Managed Identity. By following this approach, you can enhance security, simplify secret management, and ensure compliance with best practices in cloud security.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Azure Key Vault?
&lt;/h2&gt;

&lt;p&gt;Azure Key Vault is a cloud-based service that securely stores and manages secrets, such as API keys, passwords, certificates, and cryptographic keys. It enhances security by controlling access to sensitive data and allows applications to retrieve secrets securely.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Use Azure Key Vault?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Centralized Security Management: Store secrets in one place instead of in appsettings.json or environment variables.&lt;/li&gt;
&lt;li&gt;Access Control with RBAC: Uses Azure Active Directory (AAD) authentication for access.&lt;/li&gt;
&lt;li&gt;Automatic Secret Rotation: Easily update and manage secrets without modifying the application code.&lt;/li&gt;
&lt;li&gt;Compliance &amp;amp; Auditing: Meets security standards like ISO 27001, FedRAMP, and GDPR.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Implementing in ASP.NET Core project
&lt;/h2&gt;

&lt;h2&gt;
  
  
  Step 1. Create an Azure Key Vault
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt; Go to Azure Portal → Create a resource → Search for “Key Vault”.&lt;br&gt;
&lt;strong&gt;Step 2.&lt;/strong&gt; Click Create, and enter the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Resource Group: Select an existing one or create a new one.&lt;/li&gt;
&lt;li&gt;Key Vault Name: Example: MyAppKeyVault&lt;/li&gt;
&lt;li&gt;Region: Choose your Azure region.&lt;/li&gt;
&lt;li&gt;Pricing Tier: Standard is fine for most cases.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt; Click Review + Create → Create.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 2. Add Secrets to Azure Key Vault
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Open Key Vault → Secrets → Click Generate/Import.&lt;/li&gt;
&lt;li&gt;Enter Name (e.g., DatabaseConnection) and Value (e.g., Server=myserver;Database=mydb;User Id=myuser;Password=mypassword;).&lt;/li&gt;
&lt;li&gt;Click Create.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Step 3. Assign Permissions (Managed Identity)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt; Enable Managed Identity for Your App:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Go to Azure App Service → Identity → Enable System-Assigned Identity → Save.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt; Grant Access in Key Vault:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Go to Key Vault → Access Control (IAM) → Add Role Assignment.&lt;/li&gt;
&lt;li&gt;Select Key Vault Secrets User.&lt;/li&gt;
&lt;li&gt;Assign to Your App Service.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Step 4. Create a new ASP.NET Core Web API project and Install the below NuGet Packages
&lt;/h2&gt;

&lt;p&gt;Note: If you need to implement this in your existing project you don’t need to create a new project.&lt;/p&gt;

&lt;p&gt;Run these commands to install the required dependencies:&lt;br&gt;
&lt;code&gt;dotnet add package Azure.Security.KeyVault.Secrets&lt;br&gt;
dotnet add package Azure.Identity&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 5. Add the below code to Configure in appsettings.json
&lt;/h2&gt;

&lt;p&gt;Add your Key Vault URL:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "AzureKeyVault": {
    "VaultUri": "https://myappkeyvault.vault.azure.net/"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 6. Load Azure Key Vault Secrets in the Program.cs
&lt;/h2&gt;

&lt;p&gt;Modify Program.cs to fetch secrets securely:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Get Key Vault URL from configuration
var keyVaultUrl = builder.Configuration["AzureKeyVault:VaultUri"];

if (!string.IsNullOrEmpty(keyVaultUrl))
{
    var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

    // Retrieve and load secrets into IConfiguration
    var secrets = client.GetPropertiesOfSecrets();
    foreach (var secret in secrets)
    {
        var secretValue = client.GetSecret(secret.Name);
        builder.Configuration[secret.Name] = secretValue.Value.Value;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 7. Retrieve Secrets in a Controller
&lt;/h2&gt;

&lt;p&gt;Create SecretsController.cs to test Key Vault secret retrieval:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace KeyVaultDemo.Controllers
{
    [ApiController]
    [Route("api/secrets")]
    public class SecretsController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public SecretsController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpGet("{secretName}")]
        public IActionResult GetSecret(string secretName)
        {
            var secretValue = _configuration[secretName];
            if (string.IsNullOrEmpty(secretValue))
            {
                return NotFound($"Secret '{secretName}' not found.");
            }

            return Ok(new { secretName, secretValue });
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 8. Run &amp;amp; Test the API
&lt;/h2&gt;

&lt;p&gt;Now we can run and check the secrets value.&lt;/p&gt;

&lt;p&gt;If you are using Visual Studio you can simply run the project or can use command.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;dotnet run&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then we can use the http file or Postman to call the API. Below is the output of calling GetSecret API from the http file.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa20ta4k2g4w8e2suty00.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa20ta4k2g4w8e2suty00.jpg" alt="Image description" width="800" height="239"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The sample code for this can be found &lt;a href="https://github.com/SatyaKarki/SampleAzureKeyVault" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Azure Key Vault is an essential tool for securing sensitive information such as API keys, database credentials, and certificates in cloud applications. By integrating it into an ASP.NET Core application, we eliminate the risks of storing secrets in configuration files or hardcoding them in source code. In this guide, we covered the step-by-step implementation of Azure Key Vault in .NET 9, from creating a Key Vault to retrieving secrets dynamically using Azure.Identity and Azure.Security.KeyVault.Secrets.&lt;/p&gt;

&lt;p&gt;We also demonstrated how to secure access using Managed Identity. By leveraging Azure Key Vault, your application benefits from enhanced security, centralized secret management, automatic secret rotation, and compliance with industry standards. Implementing this best practice ensures your applications remain secure, scalable, and manageable in a cloud environment.&lt;/p&gt;

</description>
      <category>dot</category>
      <category>aspdotnet</category>
      <category>dotnetcore</category>
      <category>csharp</category>
    </item>
    <item>
      <title>A Complete Guide to Quartz.NET Job Scheduling in ASP.NET Core</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Sun, 16 Mar 2025 11:49:17 +0000</pubDate>
      <link>https://forem.com/satyakarki/a-complete-guide-to-quartznet-job-scheduling-in-aspnet-core-al0</link>
      <guid>https://forem.com/satyakarki/a-complete-guide-to-quartznet-job-scheduling-in-aspnet-core-al0</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Quartz.NET is an open-source job scheduling library for .NET applications, enabling developers to execute background tasks at specified times or intervals. This article explains what is quartz, it’s applications and use cases. Additionally, it will demonstrate how to implement it in a .NET application with an example and code sample.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Quartz.NET?
&lt;/h2&gt;

&lt;p&gt;Quartz.NET is an open-source job scheduling library for .NET applications. It provides a robust, feature-rich, and scalable scheduling solution that enables developers to execute background tasks at specific times or intervals. Quartz.NET is a port of the Java-based Quartz Scheduler and is widely used in enterprise applications to handle scheduled jobs efficiently.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Use Quartz.NET?
&lt;/h2&gt;

&lt;p&gt;In many software applications, there is a need to execute tasks at scheduled times, such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Running background maintenance tasks (e.g., cleaning logs, updating records, generating reports)&lt;/li&gt;
&lt;li&gt;Sending scheduled notifications (emails, push notifications, SMS reminders)&lt;/li&gt;
&lt;li&gt;Processing queued jobs asynchronously&lt;/li&gt;
&lt;li&gt;Automating workflows and batch processing&lt;/li&gt;
&lt;li&gt;Quartz.NET helps to achieve these functionalities with its flexible scheduling capabilities, making it an essential tool for developers.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Key Features of Quartz.NET
&lt;/h2&gt;

&lt;p&gt;Quartz.NET provides several powerful features for developers for examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Flexible Scheduling: Supports simple intervals (e.g., every 10 minutes) and complex Cron-like expressions.&lt;/li&gt;
&lt;li&gt;Persistent Jobs: Jobs can be stored in a database for reliability and resilience.&lt;/li&gt;
&lt;li&gt;Clustered Execution: Supports job execution across multiple servers to ensure high availability.&lt;/li&gt;
&lt;li&gt;Dependency Injection Support: Works seamlessly with .NET Core dependency injection.&lt;/li&gt;
&lt;li&gt;Scalability: Can handle thousands of scheduled jobs with high performance.&lt;/li&gt;
&lt;li&gt;Transactional Support: Ensures that jobs are executed reliably within a transactional context.&lt;/li&gt;
&lt;li&gt;Multiple Job Types: Supports one-time jobs, recurring jobs, and jobs triggered by events.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Common use cases of Quartz.NET
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Automated Report Generation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Many businesses require periodic reports (e.g., daily sales reports and system health reports). Quartz.NET can schedule jobs to generate and send these reports automatically.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Email and Notification Scheduling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Applications often send reminders, promotional emails, or system alerts at specific times. With Quartz.NET, you can schedule and manage email campaigns efficiently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Database Maintenance Tasks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Background jobs like data cleanup, indexing, or archiving old records can be scheduled using Quartz.NET, ensuring the database remains optimized.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Batch Processing and Data Synchronization&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Enterprise applications often require data synchronization between different systems. Quartz.NET can execute these tasks at defined intervals to maintain data consistency.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Automating Business Processes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Businesses use workflows for tasks like invoice generation, order processing, and billing cycles. Quartz.NET allows developers to schedule these processes efficiently.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Quartz.NET Works?
&lt;/h2&gt;

&lt;p&gt;Quartz.NET operates based on three core components:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Jobs: Define the task to be executed.&lt;/li&gt;
&lt;li&gt;Triggers: Determine when the job should run (e.g., every hour, once a day, specific dates).&lt;/li&gt;
&lt;li&gt;Schedulers: Manage and execute jobs based on their triggers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, let’s move for implementation of Quartz.NET.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing Quartz.NET in ASP.NET core web API
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1.&lt;/strong&gt; Create ASP.NET Core Web API project using Visual Studio or VS code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2.&lt;/strong&gt; Install the following packages for Quartz.NET&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Install-Package Quartz&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you need JSON Serialization, just add the either &lt;em&gt;Quartz.Serialization.SystemTextJson&lt;/em&gt; or &lt;em&gt;Quartz.Serialization.Json&lt;/em&gt; package the same way.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3.&lt;/strong&gt; Code implementation&lt;/p&gt;

&lt;p&gt;In Program.cs add the following line to register Quartz.NET as a hosted service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Add Quartz.NET as a hosted service
builder.Services.AddQuartzHostedService(options =&amp;gt;
{
    options.WaitForJobsToComplete = true;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4.&lt;/strong&gt; We will create Interface and service for Quartz Scheduler as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IQuartzJobScheduler
{
    Task ScheduleJobAsync&amp;lt;TJob&amp;gt;(TimeSpan delay, string userId, string message, CancellationToken cancellationToken) where TJob : IJob;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class QuartzJobScheduler(ISchedulerFactory schedulerFactory, ILogger&amp;lt;QuartzJobScheduler&amp;gt; logger) : IQuartzJobScheduler
{
    private readonly ISchedulerFactory _schedulerFactory = schedulerFactory;
    private IScheduler? _scheduler;
    private readonly ILogger&amp;lt;QuartzJobScheduler&amp;gt; _logger = logger;

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        _scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
        await _scheduler.Start(cancellationToken);
    }

    public async Task ScheduleJobAsync&amp;lt;TJob&amp;gt;(TimeSpan delay, string userId, string message, CancellationToken cancellationToken) where TJob : IJob
    {
        _logger.LogInformation("Scheduling job {JobName} for user {UserId} with message {Message}", typeof(TJob).Name, userId, message);

        var jobDetail = JobBuilder.Create&amp;lt;TJob&amp;gt;()
            .WithIdentity($"{typeof(TJob).Name}-{userId}")
            .UsingJobData("userId", userId)
            .UsingJobData("message", message)
            .Build();

        var scheduler = await _schedulerFactory.GetScheduler();
        var trigger = TriggerBuilder.Create()
            .StartAt(DateTimeOffset.Now.Add(delay))
            .Build();

        await scheduler.ScheduleJob(jobDetail, trigger, cancellationToken);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, we will register Dependency in the services in Program.cs, as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//add dependency injection for QuartzJobScheduler
builder.Services.AddSingleton&amp;lt;IQuartzJobScheduler, QuartzJobScheduler&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is a sample controller for the Schedular.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.AspNetCore.Mvc;
using QuartzSceduleSample.Jobs;

namespace QuartzSceduleSample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestSceduleController : ControllerBase
    {
        private readonly IQuartzJobScheduler _quartzJobScheduler;
        public TestSceduleController(IQuartzJobScheduler quartzJobScheduler)
        {
            _quartzJobScheduler = quartzJobScheduler;
        }
        [HttpPost]
        public async Task&amp;lt;IActionResult&amp;gt; PostAsync(CancellationToken cancellationToken)
        {
            //create a new job sample job
            await _quartzJobScheduler.ScheduleJobAsync&amp;lt;EmailReminderJob&amp;gt;(TimeSpan.FromSeconds(10), "123", "Hello World", cancellationToken);
            return Ok("Job is scheduled");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we schedule the job after 10 seconds.&lt;/p&gt;

&lt;p&gt;Below is the project structure.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frp2iafnc78og1cy5u6s5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frp2iafnc78og1cy5u6s5.png" alt="Image description" width="329" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, let’s call the API and check the output of the controller is given below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvho80ms360vt2dcrf02q.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvho80ms360vt2dcrf02q.jpg" alt="Image description" width="800" height="275"&gt;&lt;/a&gt;&lt;br&gt;
We will see the job will be executed after 10 seconds.&lt;/p&gt;

&lt;p&gt;Here is the repository with the complete code, &lt;a href="https://github.com/SatyaKarki/QuartzSceduleSample" rel="noopener noreferrer"&gt;Click here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Quartz.NET is a powerful and flexible job scheduling library that seamlessly integrates with ASP.NET Core. It enables developers to automate background tasks, schedule recurring jobs, and manage workflows efficiently. By implementing Quartz.NET, you can improve application performance, optimize resource utilization, and ensure timely execution of critical tasks. Whether you’re handling database cleanups, email notifications, or report generation, Quartz.NET provides a reliable solution for job scheduling in ASP.NET Core applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reference&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://rijsat.com/introduction-to-quartz-net-and-how-to-implement-in-asp-net-core-for-job-scheduling/" rel="noopener noreferrer"&gt;Quartz.NET&lt;/a&gt;&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>dotnetcore</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>Features of .NET 8</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Tue, 16 Jan 2024 10:17:38 +0000</pubDate>
      <link>https://forem.com/satyakarki/features-of-net-8-3om2</link>
      <guid>https://forem.com/satyakarki/features-of-net-8-3om2</guid>
      <description>&lt;p&gt;Microsoft released and introduced the .NET 8 on Nov 14th, 2023, the latest Long-Term Support (LTS) version of a premier development platform. .NET 8 brings forth numerous enhancements in performance, stability, and security. Additionally, it incorporates improvements in platforms and tools, fostering increased developer productivity and innovation velocity.&lt;/p&gt;

&lt;p&gt;In this latest release, .NET transforms the landscape of constructing intelligent, cloud-native applications and high-traffic services designed to scale dynamically. Whether you opt for deployment on Linux or Windows, utilize containers, or follow a preferred cloud app model, .NET 8 simplifies the process of building such applications. It encompasses a collection of established libraries currently employed by numerous high-scale services at Microsoft. These libraries address fundamental challenges related to observability, resiliency, scalability, manageability, and beyond.&lt;/p&gt;

&lt;p&gt;.NET 8 seamlessly incorporates extensive language models such as OpenAI’s GPT into your .NET application. Leverage a unified and robust component model for addressing all your web UI requirements through Blazor. Furthermore, you can effortlessly deploy your mobile applications on the newest versions of iOS and Android using .NET MAUI. Additionally, you can explore enhanced language features in C# 12 that enhance code conciseness and expressiveness.&lt;/p&gt;

&lt;p&gt;You can download the .NET 8 SDK from &lt;a href="https://aka.ms/get-dotnet-8"&gt;here &lt;/a&gt;or you can use Visual Studio 2022 latest release &lt;a href="https://aka.ms/vs/v178GA"&gt;Visual Studio 2022 17.8 release&lt;/a&gt;. If you have already Visual Studio 2022, then you can just upgrade to Visual Studio 2022 17.8 from the Visual Studio installer itself.&lt;/p&gt;

&lt;p&gt;The features of .NET 8, as announced on the official &lt;a href="http://devblogs.microsoft.com/dotnet/announcing-dotnet-8/"&gt;Microsoft DevBlog&lt;/a&gt;, encompass a myriad of advancements. This release is characterized by thousands of improvements in performance, stability, and security.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Some of the Key Features are:&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;C# 12&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;.NET 8 release with C#12. In C# 12, any class or struct can now have primary constructors created with a concise syntax, eliminating the need for boilerplate code to initialize fields and properties. More here: Primary Constructor in C#&lt;/li&gt;
&lt;li&gt;Additionally, we can use new default values for parameters in lambda expressions, which enhance code expressiveness.&lt;/li&gt;
&lt;li&gt;You don’t need more overloading or null checks to handle optional arguments.&lt;/li&gt;
&lt;li&gt;Moreover, can use the using directive to alias any type, not just named types.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;ASP.NET Core 8&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In ASP.NET Core 8 application you can see significant performance improvements, up to 18%, compared to .NET 7.&lt;/li&gt;
&lt;li&gt;Native Ahead-of-Time (AOT) support for producing self-contained apps compiled into native code, resulting in smaller deployment size, quicker startup, and reduced memory usage.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Entity Framework Core 8&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Entity Framework Core 8 supports for complex types for value objects (without identity), for example Address or Coordinate is included.&lt;/li&gt;
&lt;li&gt;You can find the added support for lazy-loading of no-tracking queries for your program.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Performance Enhancements&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Introduction of Dynamic Profile-Guided Optimization (PGO), optimizing code based on real-world usage, improving app performance by up to 20%.&lt;/li&gt;
&lt;li&gt;Rewriting certain methods for better performance, including List.AddRange(IEnumerable) and Int32.ToString().&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Cloud-Native Stack (.NET Aspire)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;.NET Aspire is another cool feature added in the .NET 8.&lt;/li&gt;
&lt;li&gt;The .NET 8 has first preview of .NET Aspire, an opinionated stack for building resilient, observable, and configurable cloud-native applications.&lt;/li&gt;
&lt;li&gt;You can develop specific components for cloud-native development, such as a dashboard, telemetry, configuration, health checks, orchestration, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Getting started with cloud native app with .NET Aspire can be found &lt;a href="https://dotnetcopilot.com/getting-started-with-net-aspire-app-for-cloud-native-applications/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Artificial Intelligence&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;.NET 8 makes ease of use of AI via first-class out of the box AI features in it’s SDK.&lt;br&gt;
.NET 8 brings several enhancements to the System.Numeric library to enhance compatibility with Generative AI into .NET application. You can infuse AI into your .NET applications easily.&lt;br&gt;
Large language Model integration with semantic Kernel.&lt;br&gt;
It is simple to get started with Azure Open AI and Azure Cognitive Search SDKs in .NET 8.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Blazor Enhancements&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Now, you can use Blazor for both client-side (Blazor WebAssembly) and server-side (Blazor Server) rendering in the same app.&lt;/li&gt;
&lt;li&gt;It supports stateless server-side rendering, streaming rendering, progressive enhancement for navigation and form handling, and interactivity per component.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;.NET MAUI&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;.NET MAUI is Successor to Xamarin.Forms, enabling the creation of projects for different platforms (WinUI, Mac, iOS, Android) with a single codebase.&lt;/li&gt;
&lt;li&gt;.NET MAUI supports targeting iOS-like platforms.&lt;/li&gt;
&lt;li&gt;.NET 8 release has introduced a new Visual Studio Code extension for .NET MAUI.&lt;/li&gt;
&lt;li&gt;Elevated performance, reliability, and developer experience for .NET MAUI applications&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Moreover, improved quality and significant feature enhancement for ARM64 platform and many other enhancements and improvements. More details about the release can be found &lt;a href="https://devblogs.microsoft.com/dotnet/announcing-dotnet-8/"&gt;here&lt;/a&gt;. And .NET 8 release notes can be found &lt;a href="https://github.com/dotnet/core/blob/main/release-notes/8.0/8.0.0/8.0.0.md?WT.mc_id=dotnet-35129-website"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>dotnetcore</category>
      <category>aspdotnet</category>
      <category>development</category>
    </item>
    <item>
      <title>Dependency Injection In .NET 6 For Windows Forms Development</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Mon, 15 Jan 2024 08:59:38 +0000</pubDate>
      <link>https://forem.com/satyakarki/dependency-injection-in-net-6-for-windows-forms-development-514g</link>
      <guid>https://forem.com/satyakarki/dependency-injection-in-net-6-for-windows-forms-development-514g</guid>
      <description>&lt;p&gt;In the rapidly changing world of software development, one thing remains constant: the perpetual challenge of managing the complexity that naturally arises as applications grow in size and complexity. As our projects expand to encompass more features, functionalities, and interconnected parts, the need for maintainable, testable, and adaptable code becomes more critical than ever before.&lt;/p&gt;

&lt;p&gt;Consider it this way: picture a sprawling metropolis, a city that started as a small village but has grown into a vast and intricate network of roads, buildings, and infrastructure. This city represents a software application, with each road and building symbolizing a component or piece of code.&lt;/p&gt;

&lt;p&gt;In the early stages of the city’s development, it was relatively straightforward to navigate and manage. The roads were simple, and the buildings were few and far between. However, as time passed, the city grew in size and complexity. New roads were built, buildings sprouted up, and the once-simple layout became a labyrinth of interconnected streets and structures.&lt;/p&gt;

&lt;p&gt;Similarly, in software development, a project that begins as a small, manageable codebase can quickly evolve into a sprawling application with many interconnected components, modules, and libraries.&lt;/p&gt;

&lt;p&gt;Dependency Injection (DI) is a fundamental concept in modern software development that helps manage the complexity of large applications by promoting loose coupling between components. It’s widely used in .NET applications, including WinForms, to improve maintainability, testability, and code reuse. In this article, we’ll explore how to implement Dependency Injection in a .NET 6 Windows Forms application with real-world examples.&lt;/p&gt;

&lt;p&gt;In this article, we explore dependency injection and how to implement it into Windows Forms Applications. The following topics will be covered in this article.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What is Dependency Injection?&lt;/li&gt;
&lt;li&gt;Why Use Dependency Injection in Windows Forms?&lt;/li&gt;
&lt;li&gt;Setting Up a .NET 6 Windows Forms Project&lt;/li&gt;
&lt;li&gt;Implementing Dependency Injection&lt;/li&gt;
&lt;li&gt;Registering Services&lt;/li&gt;
&lt;li&gt;Resolving Dependencies&lt;/li&gt;
&lt;li&gt;Constructor Injection&lt;/li&gt;
&lt;li&gt;Property Injection&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is Dependency Injection?
&lt;/h2&gt;

&lt;p&gt;Dependency Injection is a design pattern that enables the separation of concerns in an application by providing a way to inject dependencies (such as services, objects, or configurations) into a component rather than letting the component create them. This promotes modularity, testability, and code maintainability.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why to Use Dependency Injection?
&lt;/h2&gt;

&lt;p&gt;In Windows Forms applications, using Dependency Injection offers several advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Testability :&lt;/strong&gt;&lt;br&gt;
Components can be tested in isolation by injecting mock or fake dependencies, allowing for unit testing.&lt;br&gt;
**&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Loose Coupling:&lt;/strong&gt;&lt;br&gt;
Dependencies are not hard-coded, making it easier to change or extend functionality without modifying existing code.&lt;br&gt;
Readability and Maintainability: The code becomes more readable and maintainable as dependencies are explicitly defined and injected.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Code Reuse:&lt;/strong&gt;&lt;br&gt;
Dependencies can be reused across multiple components.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Scalability:&lt;/strong&gt;&lt;br&gt;
The application can scale by adding new services without affecting existing code.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Setting Up a .NET 6 Windows Forms Project
&lt;/h2&gt;

&lt;p&gt;Before implementing Dependency Injection, create a .NET 6 Windows Forms project using Visual Studio or the .NET CLI. Ensure you have the necessary tools and SDK installed.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visual Studio 2022&lt;/li&gt;
&lt;li&gt;.NET 6 SDK&lt;/li&gt;
&lt;li&gt;Windows Development Workload in Visual Studio
We will commence by creating a Windows Forms Project from Visual Studio.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc6pmirdtfz4xjrapley4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc6pmirdtfz4xjrapley4.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Give a name to the project. I have named as DIWinFormsSample. Choose .Net Framework, .NET 6.&lt;/p&gt;

&lt;p&gt;Now our Windows Forms application is created.&lt;/p&gt;
&lt;h2&gt;
  
  
  Implementing Dependency Injection
&lt;/h2&gt;

&lt;p&gt;To implement DI in the above Windows Forms application, follow these steps:&lt;/p&gt;

&lt;p&gt;Add Required NuGet Packages&lt;br&gt;
In the WinForms project, add the following NuGet packages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Microsoft.Extensions.DependencyInjection&lt;/li&gt;
&lt;li&gt;Microsoft.Extensions.Hosting&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyo8yafmt5h74awe71tpl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyo8yafmt5h74awe71tpl.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Tips&lt;/strong&gt;: better to get the latest version of NuGet Packages.&lt;/p&gt;

&lt;p&gt;We will navigate &lt;strong&gt;program.cs&lt;/strong&gt; file and add a function &lt;strong&gt;CreateHostBuilder&lt;/strong&gt;, as shown below.&lt;/p&gt;

&lt;p&gt;Create a host builder to build the service provider.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static IServiceProvider ServiceProvider { get; private set; }
static IHostBuilder CreateHostBuilder()
{
    return Host.CreateDefaultBuilder()
        .ConfigureServices((context, services) =&amp;gt; {
            services.AddTransient&amp;lt;IBlobStorageService, BlobStorageService&amp;gt;();
            services.AddTransient&amp;lt;IErrorMessageLog, ErrorMessageLog&amp;gt;();
            services.AddTransient&amp;lt;IFileMigrationService, FileMigrationService&amp;gt;();
            services.AddTransient&amp;lt;IAttachmentDataAccess, AttachmentDataAccess&amp;gt;();
            services.AddTransient&amp;lt;MainForm&amp;gt;();
        });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register Services&lt;/p&gt;

&lt;p&gt;In the &lt;strong&gt;ConfigureServices **method, use **services.AddScoped()&lt;/strong&gt; to register your services and interfaces. Replace &lt;strong&gt;IMyService&lt;/strong&gt; and &lt;strong&gt;MyService&lt;/strong&gt; with your actual interface and service implementation.&lt;/p&gt;

&lt;p&gt;We will call the Host Builder to build the services provider in Main function as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var host = CreateHostBuilder().Build();
ServiceProvider = host.Services;

Application.Run(ServiceProvider.GetRequiredService&amp;lt;MainForm&amp;gt;());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Complete &lt;strong&gt;Program.cs&lt;/strong&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace DIWinFormsSample
{
    internal static class Program
    {
        /// &amp;lt;summary&amp;gt;
        ///  The main entry point for the application.
        /// &amp;lt;/summary&amp;gt;
        [STAThread]
        static void Main()
        {
            // To customize application configuration such as set high DPI settings or default font,
            // see https://aka.ms/applicationconfiguration.
            ApplicationConfiguration.Initialize();
            var host = CreateHostBuilder().Build();
            ServiceProvider = host.Services;

            Application.Run(ServiceProvider.GetRequiredService&amp;lt;Form1&amp;gt;());
        }

        public static IServiceProvider ServiceProvider { get; private set; }
        /// &amp;lt;summary&amp;gt;
        /// Create a host builder to build the service provider
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
        static IHostBuilder CreateHostBuilder()
        {
            return Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =&amp;gt; {
                    //services.AddScoped&amp;lt;TInterface, TImplementation&amp;gt;();
                    services.AddTransient&amp;lt;Form1&amp;gt;();
                });
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s create an interface and implement it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMessageService&lt;/strong&gt; – Interface class &lt;strong&gt;MessageService&lt;/strong&gt; – Implementation Class&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IMessageService.cs&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace DIWinFormsSample.Services
{
    public interface IMessageService
    {
        string GetSuccessMessage();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;MessageService.cs&lt;/strong&gt; class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace DIWinFormsSample.Services
{
    public class MessageService : IMessageService
    {
        public string GetSuccessMessage()
        {
            return "Successful Operation!!";
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we will register the service into container in **program.cs **file.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5bzgmgth6z76lhobth9o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5bzgmgth6z76lhobth9o.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Let's just Rename Form1 into Mainform.&lt;/p&gt;

&lt;p&gt;Code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;static IHostBuilder CreateHostBuilder()
  {
      return Host.CreateDefaultBuilder()
          .ConfigureServices((context, services) =&amp;gt; {
              services.AddTransient&amp;lt;IMessageService, MessageService&amp;gt;();
              services.AddTransient&amp;lt;MainForm&amp;gt;();
          });
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create and Inject Services
&lt;/h2&gt;

&lt;p&gt;We have already created the **Message **service. In the Windows Forms or components, you can now inject services using constructor injection.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sample code&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public partial class MainForm : Form
{
    private readonly IMyService _myService;

    public MainForm(IMyService myService)
    {
        _myService = myService;
        InitializeComponent();
    }

    // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will inject the **MessageService **in our **MainForm **through a constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using DIWinFormsSample.Services;
namespace DIWinFormsSample
{
    public partial class MainForm : Form
    {
        private readonly IMessageService _messageService;
        public Form1(IMessageService messageService)
        {
            _messageService = messageService;
            InitializeComponent();
            lblMessage.Text = _messageService.GetSuccessMessage();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's run and see output. Output screen for the above solution.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6chb2f98svodx05a380s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6chb2f98svodx05a380s.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Constructor Injection&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Constructor injection is the preferred way to inject dependencies. It ensures that required dependencies are available when an object is created. In our example, the Form1 constructor expects an instance of &lt;strong&gt;IMessageService&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Alternatively, &lt;strong&gt;Property injection&lt;/strong&gt; can be used when you need optional dependencies. You can create properties in your form and set them through the DI container. However, constructor injection is recommended for mandatory dependencies.&lt;/p&gt;

&lt;p&gt;Complete Source code: &lt;a href="https://github.com/SatyaKarki/DIWinFormsSample" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Dependency Injection is a powerful technique for improving the structure, testability, and maintainability of .NET Windows Forms applications. With .NET 6, setting up DI has become easier than ever, thanks to &lt;strong&gt;Microsoft.Extensions.DependencyInjection&lt;/strong&gt; library. By following the steps outlined in this article, you can harness the benefits of DI in your Windows Forms projects, making them more robust and maintainable.&lt;/p&gt;

&lt;p&gt;Remember to register your services, use constructor injection for mandatory dependencies, and enjoy the benefits of a loosely coupled and easily testable application architecture.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-usage" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-usage&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://rijsat.com/simplify-dependency-injection-in-net-6-for-windows-forms-development/" rel="noopener noreferrer"&gt;https://rijsat.com/simplify-dependency-injection-in-net-6-for-windows-forms-development/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>dotnet</category>
      <category>windowsform</category>
      <category>development</category>
      <category>dotnet6</category>
    </item>
    <item>
      <title>Stratis Smart Contract Development using Visual Studio Code and C#</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Sun, 03 Sep 2023 06:28:44 +0000</pubDate>
      <link>https://forem.com/satyakarki/stratis-smart-contract-development-using-visual-studio-code-and-c-4i6o</link>
      <guid>https://forem.com/satyakarki/stratis-smart-contract-development-using-visual-studio-code-and-c-4i6o</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Visual Studio Code (VS Code) is a source code editor developed by Microsoft. It is most popular with several developers and educational institutions worldwide. It can be used for various programming languages, for instance, C, C#, C++, Java, Go, JavaScript, Python, Node.js, rust, and many more. These days VS code is getting more popular. It is a handy IDE for developing applications of any platform and is open source and entirely free for any development.&lt;/p&gt;

&lt;p&gt;Moreover, it is available for Windows, Linux, and macOS. We can get several extensions and packages to develop applications in several languages inside it. Additionally, it is lightweight in comparison to Visual Studio.&lt;/p&gt;

&lt;p&gt;This article will teach us to create the &lt;a href="https://www.stratisplatform.com/"&gt;Stratis &lt;/a&gt; Smart Contarct program with Visual Studio code in the .NET 6 framework. Stratis Smart Contract must be written in C# language, and Stratis Blockchain is fully developed in .NET and C# language. However, some SDKs can be utilized for other programming languages, such as python SDK for python developers, Unity SDK for unity developers, JavaScript SDK, and Unreal Engine SDK, etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visual Studio Code&lt;/li&gt;
&lt;li&gt;.NET 6 SDK and C# extension to be installed&lt;/li&gt;
&lt;li&gt;Knowledge of C#&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Create a Solution using VS Code
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Open VS code and the folder where you want to create a project. From the main menu, select File-&amp;gt; Open Folder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6QcO5HC7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3i7ir6qehqfyq1fuvgi.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6QcO5HC7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3i7ir6qehqfyq1fuvgi.jpg" alt="Image description" width="341" height="681"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Open the Terminal by selecting View, then go to Terminal from the menu or(Ctrl+Shift+P), or simply click on the Terminal. Then the Terminal opens with the command prompt with the folder name.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kaseMZ88--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jo033dceu6op1kebgc2m.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kaseMZ88--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jo033dceu6op1kebgc2m.jpg" alt="Image description" width="612" height="462"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3&lt;/strong&gt;&lt;br&gt;
Run the below command to create a solution in the Terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet new sln
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The solution will be created as shown below with the name of the folder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WXRWLVTz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brbph5lsz8foxussjh2h.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WXRWLVTz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brbph5lsz8foxussjh2h.jpg" alt="Image description" width="686" height="213"&gt;&lt;/a&gt;&lt;br&gt;
Now, we will create a Class Library project.&lt;/p&gt;
&lt;h2&gt;
  
  
  Create a Class library project
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the Terminal, you must run the command below to create a class library project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet new classlib -o YourClassLibraryprojectname
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Below is an example of creating a HelloWorld class library project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet new classlib -o HelloWorld
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will create a class library project with the name HelloWorld.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0myBEqcD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmhalxzkwycs5vw1vgnh.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0myBEqcD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmhalxzkwycs5vw1vgnh.jpg" alt="Image description" width="800" height="190"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Step 2&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Add class lib project to the solution.&lt;/p&gt;

&lt;p&gt;Run the below command to add the class lib project to the solution.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet sln add HelloWorld/HelloWorld.csproj
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xRRt-FbR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/407a92g34bzc297gx7i6.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xRRt-FbR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/407a92g34bzc297gx7i6.jpg" alt="Image description" width="800" height="134"&gt;&lt;/a&gt;&lt;br&gt;
The default Project structure will be like the one below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3TJLN7V_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtmnr4hsclau8ofaa3mz.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3TJLN7V_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtmnr4hsclau8ofaa3mz.jpg" alt="Image description" width="422" height="368"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Install Stratis Smart Contract NuGet Package
&lt;/h2&gt;

&lt;p&gt;To add the NuGet package, you can use a command in the Terminal like the one below. The below command installs the Stratis.SmartContracts.NET6 package from NuGet store.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet add HelloWorld package Stratis.SmartContracts.NET6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HdaQFwu8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nsufootmwpwlfsojpdud.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HdaQFwu8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nsufootmwpwlfsojpdud.jpg" alt="Image description" width="800" height="259"&gt;&lt;/a&gt;&lt;br&gt;
Now, we are ready to write the Stratis Smart Contract program.&lt;/p&gt;
&lt;h2&gt;
  
  
  Write Smart Contract Program in C
&lt;/h2&gt;

&lt;p&gt;Now, we will write a simple Smart contract program that returns Greeting value. Rename the default Class1.cs to HelloWorld.cs and Write below the HelloWorld contract program.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Stratis.SmartContracts;
[Deploy]
public class HelloWorld: SmartContract {
    private string Greeting {
        get {
            return this.State.GetString("Greeting");
        }
        set {
            this.State.SetString("Greeting", value);
        }
    }
    public HelloWorld(ISmartContractState smartContractState): base(smartContractState) {
        this.Greeting = "Namaste!";
    }
    public string SayHello() {
        return this.Greeting;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the contract code is ready, we must validate it for format and determinism. We must use the Stratis Smart Contract tool (Sct) for that.&lt;/p&gt;

&lt;h2&gt;
  
  
  Smart Contract Tool
&lt;/h2&gt;

&lt;p&gt;The smart contract tool is powered by the Stratis platform, which is used to validate and generate the byte code of the Smart contract.&lt;/p&gt;

&lt;p&gt;After completing the Smart Contract code based on the requirement, we must validate it. Stratis has provided an Sct tool to validate whether the smart contract is correct. The validation process is mandatory to verify the valid constraints used in the contract. It validates the determinism and constraints used in the Smart Contract, i.e., validates the format and deterministic element of the contract. Determinism and format validation rules can be found in the &lt;a href="https://academy.stratisplatform.com/Architecture%20Reference/SmartContracts/contracts-in-depth.html"&gt;Startis Academy&lt;/a&gt;. You can download the Sct tool from &lt;a href="https://github.com/stratisproject/Stratis.SmartContracts.Tools.Sct"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Or clone the Stratis.SmartContracts.Tools.Sct repository by running the below command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/stratisproject/Stratis.SmartContracts.Tools.Sct.git
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Validating the Contract&lt;/strong&gt;&lt;br&gt;
Open the command terminal, and then you can go to the Smart Contract tool directly by running the below command.&lt;br&gt;
&lt;code&gt;cd src/Stratis.SmartContracts.Tools.Sct&lt;/code&gt;&lt;br&gt;
After that, run the below command to validate the contract.&lt;/p&gt;

&lt;p&gt;dotnet run — validate [Contract_PATH]&lt;/p&gt;

&lt;p&gt;e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -- validate "C:\Users\rijsat\Desktop\Desktop\SampleDotnetProject\HelloWorld\HelloWorld\HelloWorld.cs"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once you run the command, you can see the success or error of validation. On the success of validation, you will get the below information in the Terminal.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5vhKRymL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sj914yjtckctb9mn1wu8.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5vhKRymL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sj914yjtckctb9mn1wu8.jpg" alt="Image description" width="800" height="493"&gt;&lt;/a&gt;&lt;br&gt;
If you get an error in the validation step, based on the error message, you can correct your smart contract code or &lt;a href="https://academy.stratisplatform.com/Architecture%20Reference/SmartContracts/contracts-in-depth.html#contract-validation"&gt;check validation rules&lt;/a&gt; and again do validation as above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Compiling Contract&lt;/strong&gt;&lt;br&gt;
Once the Contract is validated, we must compile the Smart Contract code and generate the byte code. This smart contract byte code is the code that we need to deploy in the Blockchain.&lt;/p&gt;

&lt;p&gt;To compile the code, run the below command.&lt;/p&gt;

&lt;p&gt;dotnet run – – validate [CONTRACT_PATH] -sb&lt;/p&gt;

&lt;p&gt;example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -- validate "C:\Users\rijsat\Desktop\Desktop\SampleDotnetProject\HelloWorld\HelloWorld\HelloWorld.cs" -sb
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command first validates the Smart contract and then compiles the code. On the success of your compilation, you will get hash and byte code in your Terminal, as illustrated below. We will need the hash and byte code while deploying the contract on the Blockchain. So, copy and keep the hash and Contract Byte code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qi7Xfn4l--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qd46sy18t6jrsftjui5d.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qi7Xfn4l--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qd46sy18t6jrsftjui5d.jpg" alt="Image description" width="800" height="488"&gt;&lt;/a&gt;&lt;br&gt;
For Stratis Smart Contract deployment and interaction we can use Cirrus core wallet, for that you can refer to the previous article &lt;a href="https://www.c-sharpcorner.com/article/how-to-deploy-and-interact-with-smart-contract-using-cirrus-core-wallet-on-strat/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Hence, this article explained us to develop Stratis Smart Contract using Visual Studio code and .NET 6 framework. Additionally, we learned what is Stratis Smart Contract tool (SCT) is and how to validate, compile and generate the bytecode of a Stratis Smart Contract.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://rijsat.com/2023/03/21/smart-contract-development-with-visual-studio-code-and-c-language/"&gt;Rijsat.com&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://academy.stratisplatform.com/"&gt;Stratis Academy&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>csharp</category>
      <category>smartcontract</category>
      <category>web3</category>
      <category>blockchain</category>
    </item>
    <item>
      <title>Beginners Guide to Get Started with Smart Contract in C#</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Mon, 16 Jan 2023 11:56:22 +0000</pubDate>
      <link>https://forem.com/satyakarki/beginners-guide-to-get-started-with-smart-contract-in-c-3c7e</link>
      <guid>https://forem.com/satyakarki/beginners-guide-to-get-started-with-smart-contract-in-c-3c7e</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;A smart contract is a computer program where the parties have consent on predetermined conditions of the agreement. Smart contract stores and self-executes in the blockchain network. It runs when the predefined conditions are met. Smart Contract allows transactions to be made without the need of a middle man and those transactions are irreversible, transparent, and traceable. This article describes how to get started with Smart Contract in C# using Stratis blockchain. In the article I will cover, setting up an environment for the development of Smart Contract in C# using Stratis blockchain which includes the setting up of Stratis Smart Contract template in Visual Studio. Additionally, I will explain how to get and set up all the necessary tools for Contract Validation and running up Stratis private blockchain network in the development environment. This article is the guide for newbies to set up and get ready for Smart Contract development in C# using Stratis Blockchain.&lt;/p&gt;

&lt;p&gt;The article will cover the following things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stratis Smart Contract Template setup in Visual Studio&lt;/li&gt;
&lt;li&gt;Create Smart Contract Project in C# using Stratis Smart Contract Template&lt;/li&gt;
&lt;li&gt;What is Sct Tool&lt;/li&gt;
&lt;li&gt;How to Validate Smart Contract&lt;/li&gt;
&lt;li&gt;How to generate Smart Contract Bytecode&lt;/li&gt;
&lt;li&gt;What is Full Node&lt;/li&gt;
&lt;li&gt;How to run Full Node in Development Environment&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, let’s begin. We need the following things to develop Smart Contract in C# utilizing Stratis blockchain in the development machine.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stratis Smart Contract Template in Visual Studio&lt;/li&gt;
&lt;li&gt;Sct Tool&lt;/li&gt;
&lt;li&gt;Full Node&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visual Studio 2019 or Later&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Visual Studio
&lt;/h2&gt;

&lt;p&gt;We need Visual Studio 2019 or a later version either Community or any edition for Stratis Smart Contract development. If you don’t have you can download it and install it on your machine from &lt;a href="https://visualstudio.microsoft.com/vs/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Once you have installed Visual Studio, you can set up Stratis Smart Contract Template. Let’s move for this.&lt;/p&gt;

&lt;h2&gt;
  
  
  Stratis Smart Contract Template Setup in Visual Studio
&lt;/h2&gt;

&lt;p&gt;Stratis has provided a Smart Contract template for those who want to create a Smart Contract using C# and .NET in Visual Studio. To set up Stratis Smart Contract Template run the below command in your Visual Studio command terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet new --install Stratis.SmartContracts.Templates.CLI
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once, the command is successful you can see the Stratis Smart Contract template in the list as depicted below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fusx59vpaw9wej26eur1h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fusx59vpaw9wej26eur1h.png" alt="Image description" width="800" height="159"&gt;&lt;/a&gt;&lt;br&gt;
You can run the below command to view the list of new templates installed in visual studio.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet new --list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you are interested in watching a video for the same below is a video for you.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/uqamhPUNlI4"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Smart Contract In C# Using Stratis Smart Contract Template
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1- Create Smart Contract Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a new project in Visual Studio and search Stratis Smart Contract template by typing Stratis in the search textbox. You can see the template in the list. Select the Stratis Smart Contract Template (Stratis Group Ltd) and click on Next.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2w8qosdltvchf5sujhc1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2w8qosdltvchf5sujhc1.png" alt="Image description" width="800" height="527"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you can find the Smart Contract Template in the list then move to Step 2. Otherwise, you need to do a quick fix. If you still cannot find the Stratis Smart Contract template in Visual Studio then go to Tool–&amp;gt;Options as shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1t40nungn333b73qqg02.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1t40nungn333b73qqg02.png" alt="Image description" width="669" height="499"&gt;&lt;/a&gt;&lt;br&gt;
Then under Environment go to Preview Features and select “Show all .NET Core templates in the New Project dialog (requires restart)” and click on OK.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F56u2ijylwexbigvx1jk8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F56u2ijylwexbigvx1jk8.png" alt="Image description" width="765" height="474"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you enable this, restart your Visual Studio.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2- Give Project Name&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Once you select the Stratis Smart Contract Template while creating the project then, give the project name, folder location, and solution name and click on Create to create your first Stratis Smart Contract Project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdqm279yl0aey61cel43m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdqm279yl0aey61cel43m.png" alt="Image description" width="800" height="531"&gt;&lt;/a&gt;&lt;br&gt;
When Project is created you can see My Contract Class as shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1j6ujqm8cv40yyg3423h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1j6ujqm8cv40yyg3423h.png" alt="Image description" width="800" height="258"&gt;&lt;/a&gt;&lt;br&gt;
Stratis Smart Contract Template setup and project creation are completed. Now, you can write your contract code based on your requirement. You can get a Sample of Stratis Smart Contract from the repository &lt;a href="https://github.com/stratisproject/StratisSmartContractsSamples" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
However, for this article we will go for the next steps on how to validate and generate the bytecode of the Smart Contract.&lt;/p&gt;
&lt;h2&gt;
  
  
  Sct Tool
&lt;/h2&gt;

&lt;p&gt;We need the Sct tool to validate the Stratis Smart Contract and generate the byte code of the Contract. After the completion of the code of our Smart Contract based on the requirement, we need to validate it. Stratis has provided Sct tool to validate the smart contract whether is correct. The validation process is mandatory to verify the valid constraints used in the contract. It validates for the determinism and constraints used in the Smart Contract i.e. validates format and deterministic element of the contract. You can download Sct tool from &lt;a href="https://github.com/stratisproject/Stratis.SmartContracts.Tools.Sct" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  How to Validate Smart Contract Using Sct Tool
&lt;/h2&gt;

&lt;p&gt;Open Sct Tools solution in Visual Studio, you will see two projects there one is the main project, and another is tests project as illustrated below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjytgvlocmevejqy0ql0l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjytgvlocmevejqy0ql0l.png" alt="Image description" width="332" height="259"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Right-click on “Stratis.SmartContracts.Tools.Sct” and go to the terminal then run the following command.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa9m59d0fkbrt3lmv16up.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa9m59d0fkbrt3lmv16up.png" alt="Image description" width="800" height="407"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -- validate [Contract_PATH]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -- validate “F:\Blockchain\Demo Stratis Contract\Demo Stratis Contract\MyContract.cs”
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
from CLI you can run below commands&lt;/p&gt;

&lt;p&gt;&lt;em&gt;cd src/Stratis.SmartContracts.Tools.Sct&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -- validate [Contract_PATH]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once you run the command you can see the success or error of validation. On the success of validation, you will get the below information in the terminal.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsuz2d6ao9x1d3302ot6s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsuz2d6ao9x1d3302ot6s.png" alt="Image description" width="624" height="265"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you get an error while validating the contract, then based on the error message you can correct your smart contract code and then again do validation as above.&lt;/p&gt;

&lt;h2&gt;
  
  
  Compiling Contract using Sct tool
&lt;/h2&gt;

&lt;p&gt;Once, Contract is validated, after that, we have to compile the Smart Contract code and generate the byte code. This smart contract bytecode is the code that we have to deploy in the Blockchain.&lt;/p&gt;

&lt;p&gt;To compile the code run the below command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -- validate [CONTRACT_PATH] -sb
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -- validate "F:\Blockchain\Demo Stratis Contract\Demo Stratis Contract\MyContract.cs”-sb
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command-line first validates the Smart contract and then compiles the code. On the success of your compilation, you will get hash and byte code in your terminal as illustrated below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F08jatjg0llxzltqeh7ri.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F08jatjg0llxzltqeh7ri.png" alt="Image description" width="800" height="337"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Stratis Full Node
&lt;/h2&gt;

&lt;p&gt;Stratis Full Node is the core of Stratis private blockchain. This is the very crucial step to set up and run the Stratis Full Node on your development machine to run the project locally and interact with the Stratis Blockchain. For more details on Full Node visit this &lt;a href="https://academy.stratisplatform.com/Architecture%20Reference/FullNode/full-node-introduction.html" rel="noopener noreferrer"&gt;Stratis Academy&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You can download Stratis Full Node from &lt;a href="https://github.com/stratisproject/StratisFullNode" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Run the Stratis Full Node in Development Environment
&lt;/h2&gt;

&lt;p&gt;Once downloaded, go to the folder and open the Stratis Full Node solution in Visual studio, there you will see many projects; however, you need to run the Stratis.CirusMinerD project with the -devmode parameter by executing the below command from CLI.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;cd StratisFullNode\src\Stratis.CirrusMinerD&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -devmode=miner
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;/p&gt;

&lt;p&gt;Right-click on “&lt;em&gt;Stratis.CirrusMinerD&lt;/em&gt;” Project and click on Open in Terminal then run below command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet run -devmode=miner
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command runs a single block-producing node using the PoA (Proof-of-Authority) consensus algorithm. After the success of the above command open the &lt;a href="http://localhost:38223/swagger" rel="noopener noreferrer"&gt;http://localhost:38223/swagger&lt;/a&gt; on your device where you can see a list of APIS. These API endpoints will be used to interact with the blockchain.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foxk7umd1qxvlvj0dflas.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foxk7umd1qxvlvj0dflas.png" alt="Image description" width="800" height="414"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Congratulations, your machine is set up for Stratis Smart Contract development and deployment for private blockchain which can be used for both development and testing purposes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Hence, this article has described how to set up a template and get started with Smart Contract in C# using Stratis Blockchain. Moreover, the article explained what is Sct tool is, how to validate and generate Smart contract bytecode, how to run Stratis Full Node for development, and the testing environment locally using C#, dotNet, and visual studio.&lt;/p&gt;

&lt;p&gt;The article was initially published on &lt;a href="https://rijsat.com/2021/08/20/getting-started-with-smart-contract-in-c-using-stratis-blockchain/" rel="noopener noreferrer"&gt;rijsat.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>mcp</category>
      <category>api</category>
      <category>security</category>
      <category>backend</category>
    </item>
    <item>
      <title>Develop Minimal APIs in .NET 7 using Entity Framework Core 7</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Thu, 15 Dec 2022 11:46:18 +0000</pubDate>
      <link>https://forem.com/satyakarki/develop-minimal-apis-in-net-7-using-entity-framework-core-7-522h</link>
      <guid>https://forem.com/satyakarki/develop-minimal-apis-in-net-7-using-entity-framework-core-7-522h</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Minimal APIs are designed to create HTTP APIs with minimal dependencies. Minimal APIs are suitable for microservices and applications that include minimum files, features, and dependencies with ASP.NET Core. Minimal APIs were there since .NET 6 and it helps you to easily create API. At the time of this article write up .NET 7 is recently released.  It has included several improvements in performance, new features for C#11 &amp;amp;F#, .Net MAUI, ASP.NET Core/Blazor improvement, Web APIs, and many more. Additionally, you can easily containerize your .NET 7 projects as well as configure CI/CD workflows for GitHub actions. Moreover, .NET MAUI is a part of the .NET 7. .NET 7 is officially supported by Microsoft for only 18 months, and it is labeled as Standard term support. This article demonstrates how to create Minimal APIs using .NET 7 and Entity Framework Core 7.&lt;/p&gt;

&lt;p&gt;In this article, we will cover the followings:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create Minimal APIs using .NET 7&lt;/li&gt;
&lt;li&gt;Get familiar with Minimal APIs&lt;/li&gt;
&lt;li&gt;Get Familiar with Entity Framework and use Entity Framework in Minimal API&lt;/li&gt;
&lt;li&gt;Create APIs for CRUD operation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visual Studio 2022&lt;/li&gt;
&lt;li&gt;.NET 7 SDK
If you don’t have these prerequisites, you can download and install Visual Studio 2022 from here and .NET 7 SDK from &lt;a href="https://dotnet.microsoft.com/download/dotnet/7.0" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you are new to .NET 7, you can get the previous article Getting Started with ASP.NET Core 7 and  Some key features of.NET 7 &lt;a href="https://rijsat.com/2022/11/10/getting-started-with-asp-net-core-7/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create Minimal API Project
&lt;/h2&gt;

&lt;p&gt;Follow the below steps to create a Minimal API.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1&lt;/strong&gt; - Open Visual Studio and click on create a new project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvuc67y9ecco62o6lrlwf.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvuc67y9ecco62o6lrlwf.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Step 2&lt;/strong&gt; - Select ASP.NET Core Web API as depicted below. You can see that this template comes with an example of a RESTFul HTTP service as well as it can be used for ASP.NET Core MVC Views and Controllers ( APIs with controller).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fztppu1him0fgjktgnja3.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fztppu1him0fgjktgnja3.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Step 3&lt;/strong&gt; - Give the project name, and directory of the project and then click on Next as illustrated below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frxcys25wxz5jvx6n6mkd.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frxcys25wxz5jvx6n6mkd.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Step 4&lt;/strong&gt; - Select Framework:  .Net 7.0 (Standard Term Support), uncheck Use Controller to use minimal APIs. uncheck Do not use top-level Statements. Select others as illustrated in the image below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsud5lj9pazkuvlbao685.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsud5lj9pazkuvlbao685.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Step 5&lt;/strong&gt; - Exploring Default Program.cs code&lt;/p&gt;

&lt;p&gt;Now, let’s explore the code of program.cs.&lt;/p&gt;

&lt;p&gt;Below is the default code of Program.cs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =&amp;gt;
{
    var forecast = Enumerable.Range(1, 5).Select(index =&amp;gt;
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

app.Run();

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF =&amp;gt; 32 + (int)(TemperatureC / 0.5556);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The MapGet method in Minimal APIs can be used to handle the HTTP Get request. Meaning the weather forecast API is an HTTP Get endpoint: “/weatherforecast”.&lt;/li&gt;
&lt;li&gt;The default Weather forecast displays the date, temperature, summary, and temperature.
Default project Structure of Minimal API project.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyat3jukz8ma1qx0cvl86.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyat3jukz8ma1qx0cvl86.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Now, let’s run the default project. Below is the view of a Swagger page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8y767ronj8enprvrwhdv.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8y767ronj8enprvrwhdv.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
You can see in the above image that Minimal API comes with a default weather forecast and Swagger Documentation for Web API same as ASP.NET Core Web API with Controller.&lt;/p&gt;

&lt;p&gt;Up to now we have only created and explored the default Minimal API. Now, we will go for creating new APIs.&lt;/p&gt;
&lt;h2&gt;
  
  
  Adding/Creating New APIs
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1&lt;/strong&gt;- Add Entity Framework&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Entity Framework Core&lt;/strong&gt;: Entity Framework core is part of Entity Framework. After the Entity Framework 6.x it is labeled as Entity Framework core. Entity Framework core is an open-source, lightweight, extensible, and cross-platform version of Entity Framework. It works as an Object-relational mapper (ORM) which helps developer to work with database and .Net objects easily. With the use of EF, developers don’t need to write most of the data access code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Memory database&lt;/strong&gt;: EF core has the ability to store and retrieve data from in memory. In memory database is used to test the application. It doesn’t store data in the physical database, it just stores data in the in-memory and it is volatile. We can use it just for testing whether our API is working perfectly or not in this demo Minimal API project.&lt;/p&gt;

&lt;p&gt;So here we will install two components:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Microsoft.EntityFrameworkCore.InMemory&lt;/li&gt;
&lt;li&gt;Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
Now, let’s move to add EF Core.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Right-click on Project and Go to Manage NuGet Package for the solution as shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F60zgaj2v1kaqr11lati1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F60zgaj2v1kaqr11lati1.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Then go to the Browse tab. In the Search box enter &lt;strong&gt;Microsoft.EntityFrameworkCore.InMemory&lt;/strong&gt; select &lt;strong&gt;Microsoft.EntityFrameworkCore.InMemory&lt;/strong&gt; and then install it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7zwxz22aln7g27nn6ewz.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7zwxz22aln7g27nn6ewz.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Similarly, Go to the Browse tab -&amp;gt; In the Search box enter: &lt;strong&gt;Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore&lt;/strong&gt; then you select it and install it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0onk3z68a7820tih9uju.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0onk3z68a7820tih9uju.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Step 2&lt;/strong&gt; - Add Model class.&lt;/p&gt;

&lt;p&gt;Now, let’s add the Student model class. Create a Model folder and add the Student class there.&lt;/p&gt;

&lt;p&gt;Write the below code in your Student.cs class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Student
{
    public int Id { get; set; }
    [Required]
    public string? Name { get; set; }
    [Required]
    public string? Email { get; set; }
    public string? Phone { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3&lt;/strong&gt; - Add DbContext.&lt;/p&gt;

&lt;p&gt;Then let’s create a folder Data and add a class for data context. Let’s say MyDataContext class.&lt;/p&gt;

&lt;p&gt;Code of MyDataContext&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class MyDataContext:DbContext
{
    public MyDataContext(DbContextOptions&amp;lt;MyDataContext&amp;gt; options)
   : base(options) { }

    public DbSet&amp;lt;Student&amp;gt; Students =&amp;gt; Set&amp;lt;Student&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add Datacontext in Program.cs as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Add dbContext, here you can we are using In-memory database.
builder.Services.AddDbContext&amp;lt;MyDataContext&amp;gt;(opt =&amp;gt; opt.UseInMemoryDatabase("Student"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 4 - Create New APIs&lt;/p&gt;

&lt;p&gt;In Minimal API we write all the API code inside the Program.cs file. So now, let’s go and add a basic API endpoint for a CRUD operation of the Student class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Save API:&lt;/strong&gt; Write the below code to Save Student data using entity framework core 7 in Minimal API. Here the Save API is HTTP Post endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.MapPost("/SaveStudent", async (Student student, MyDataContext db) =&amp;gt;
{
    db.Students.Add(student);
    await db.SaveChangesAsync();

    return Results.Created($"/save/{student.Id}", student);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;GetAll&lt;/strong&gt;: Below is the code of the GetAll Student API endpoint. This is HTTP Get API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.MapGet("/GetAllStudent", async (MyDataContext db) =&amp;gt;
    await db.Students.ToListAsync());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Update: Below is the update code for Student detail which is HTTP Put API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.MapPut("/UpdateStudents/{id}", async (int id, Student studentinput, MyDataContext db) =&amp;gt;
{
    var student = await db.Students.FindAsync(id);

    if (student is null) return Results.NotFound();

    student.Name = studentinput.Name;
    student.Phone = studentinput.Phone;

    await db.SaveChangesAsync();

    return Results.NoContent();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A complete code of Program.cs with Post, Get, Put, and Delete APIs for Student is given below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.EntityFrameworkCore;
using SampleMinimalAPI.Data;
using SampleMinimalAPI.Model;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//Add dbContext
builder.Services.AddDbContext&amp;lt;MyDataContext&amp;gt;(opt =&amp;gt; opt.UseInMemoryDatabase("Student"));
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =&amp;gt;
{
    var forecast = Enumerable.Range(1, 5).Select(index =&amp;gt;
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

//Student APIs
app.MapPost("/SaveStudent", async (Student student, MyDataContext db) =&amp;gt;
{
    db.Students.Add(student);
    await db.SaveChangesAsync();

    return Results.Created($"/save/{student.Id}", student);
});

app.MapGet("/GetAllStudent", async (MyDataContext db) =&amp;gt;
    await db.Students.ToListAsync());

app.MapGet("/GetStudentById/{id}", async (int id, MyDataContext db) =&amp;gt;
    await db.Students.FindAsync(id)
        is Student student
            ? Results.Ok(student)
            : Results.NotFound());

app.MapPut("/UpdateStudents/{id}", async (int id, Student studentinput, MyDataContext db) =&amp;gt;
{
    var student = await db.Students.FindAsync(id);

    if (student is null) return Results.NotFound();

    student.Name = studentinput.Name;
    student.Phone = studentinput.Phone;

    await db.SaveChangesAsync();

    return Results.NoContent();
});

app.MapDelete("/DeleteStudent/{id}", async (int id, MyDataContext db) =&amp;gt;
{
    if (await db.Students.FindAsync(id) is Student student)
    {
        db.Students.Remove(student);
        await db.SaveChangesAsync();
        return Results.Ok(student);
    }

    return Results.NotFound();
});

app.Run();

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF =&amp;gt; 32 + (int)(TemperatureC / 0.5556);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, our Student APIs are ready, we can run and test APIs.&lt;/p&gt;

&lt;p&gt;Below is an image of testing for Save API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fceq5a9a20a358d6rx0wa.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fceq5a9a20a358d6rx0wa.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx8dhwwt0umdra5fa557e.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx8dhwwt0umdra5fa557e.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Below is an image of testing for the GetAll Student API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl89072n6ncoasluuvbm2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl89072n6ncoasluuvbm2.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
In this way, we can test all the APIs of our minimal API project using an in-memory database.&lt;/p&gt;

&lt;p&gt;The source code for Minimal APIs demonstrated in this article can be found &lt;a href="https://github.com/SatyaKarki/SampleMinimalAPIs" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;In a nutshell, Minimal APIs are designed to create HTTP APIs with minimal dependencies. Minimal APIs are suitable for microservices and applications that include minimum files, features, and dependencies with ASP.NET Core. Minimal APIs were available since .NET 6. Hence, the article described what is Minimal API and how to get started with Minimal API in .NET 7. Additionally, the article has demonstrated to create a new Custom API with an example of Student API. Furthermore, we have got an idea about Entity Framework Core 7 and implemented entity framework in the Minimal API project as well as created minimal API for CRUD operation using entity framework and in-memory database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reference&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://rijsat.com/2022/11/23/minimal-api-in-net-7-and-entity-framework-core-7/" rel="noopener noreferrer"&gt;rijsat.com&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>aspnet</category>
      <category>dotnet</category>
      <category>webapi</category>
      <category>csharp</category>
    </item>
    <item>
      <title>Receiving Real-Time Data In An ASP.NET Core Client Application Using SignalR JavaScript Client</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Fri, 18 Nov 2022 05:32:58 +0000</pubDate>
      <link>https://forem.com/satyakarki/receiving-real-time-data-in-an-aspnet-core-client-application-using-signalr-javascript-client-54eb</link>
      <guid>https://forem.com/satyakarki/receiving-real-time-data-in-an-aspnet-core-client-application-using-signalr-javascript-client-54eb</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;SignalR is an open-source library that facilitates to add real-time functionality to web applications. Using this, the server application can push real-time data to the client.&lt;/p&gt;

&lt;p&gt;This article explains how to connect with SignalR Server hub and receive the message data from the server to the client application using the SignalR JavaScript client in ASP.NET Core 6 application. There are several ways to receive the data from SignalR server application to the client using different reference packages. Among them, we already learned one in the &lt;a href="https://dev.to/satyakarki/receive-real-time-data-in-net-6-client-application-using-signalr-kpj"&gt;previous part&lt;/a&gt; of the article series where we used SignalR .NET Client. However, in this article, we will explore SignalR JavaScript client and use it in .NET6 application to receive the data from the server hub. In this example, we will focus on a client application. Same as the &lt;a href="https://dev.to/satyakarki/receive-real-time-data-in-net-6-client-application-using-signalr-kpj"&gt;previous article&lt;/a&gt;, the scenario is useful when we have two different applications for SignalR server and client, and we need to use SignalR JavaScript client for ASP.NET Core 6 application where we need to use client-side JavaScipt code only. In the previous part of the article series, we used server-side code to receive data in the SignalR client application; however, in this part, we will use client-side code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visual Studio 2022&lt;/li&gt;
&lt;li&gt;Functioning SignalR Server Application
If you have already an existing client application in .NET6.0 and you need to only implement the SignalR part using JavaScript Client in the client application to receive the real-time data from your server application using SignalR JavaScript client, then you can directly jump into Step 2.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Source code for client application check this &lt;a href="https://github.com/SatyaKarki/SampleSignalRClientApp"&gt;Git Repo&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1 - Create an ASP.NET Core6 project as usual.
&lt;/h2&gt;

&lt;p&gt;Open Visual Studio and click on Create a new project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--yjTT_GeG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/er1edfpdaks8gn7skkqm.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--yjTT_GeG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/er1edfpdaks8gn7skkqm.jpg" alt="Image description" width="850" height="586"&gt;&lt;/a&gt;&lt;br&gt;
Select ASP.NET Core web app (MVC) as illustrated below and click on Next.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RuLQF5Yz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ew3hob0zxs7cpxwlrvuf.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RuLQF5Yz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ew3hob0zxs7cpxwlrvuf.jpg" alt="Image description" width="850" height="694"&gt;&lt;/a&gt;&lt;br&gt;
Give the project name, location of the project, and click on Next.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--eTphr0M9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsoz83kz7trf0m72isro.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--eTphr0M9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsoz83kz7trf0m72isro.jpg" alt="Image description" width="850" height="692"&gt;&lt;/a&gt;&lt;br&gt;
Then select the Framework: .NET 6.0(Long-term support) as shown below and click on Create.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--KT-uL-KG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1aqrm89ww0vr7z57mob.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KT-uL-KG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1aqrm89ww0vr7z57mob.jpg" alt="Image description" width="850" height="712"&gt;&lt;/a&gt;&lt;br&gt;
Then, your default SignalR client app will be created. Which you can run and see the default design in the browser.&lt;/p&gt;

&lt;p&gt;Now, we will move to SignalR client part.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 2 – Install SignalR JavaScript Client
&lt;/h2&gt;

&lt;p&gt;Now, we will need to install SignalR JavaScript client. Open package manager console as depicted below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jxOeoygG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eo3pkpwqr78n8agdjmr1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jxOeoygG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eo3pkpwqr78n8agdjmr1.jpg" alt="Image description" width="577" height="550"&gt;&lt;/a&gt;&lt;br&gt;
Then run the below bash commands from the package manager console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y
npm install @microsoft/signalr
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally, you can install it with LibMan from here.&lt;/p&gt;

&lt;p&gt;Once installed: Create folder signalr under &lt;strong&gt;&lt;em&gt;wwwroot/lib&lt;/em&gt;&lt;/strong&gt; and go to &lt;em&gt;node_modules\@microsoft\signalr\dist\browser&lt;/em&gt; folder and copy and paste the &lt;strong&gt;&lt;em&gt;signalr.js&lt;/em&gt;&lt;/strong&gt; file in the signalr folder as shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6t8UreGD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5h3992zsd9caumj7gor.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6t8UreGD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5h3992zsd9caumj7gor.jpg" alt="Image description" width="438" height="662"&gt;&lt;/a&gt;&lt;br&gt;
Now, your signalr file is ready we can reference the SignalR JavaScript client in the script element such as.&lt;br&gt;
&lt;code&gt;&amp;lt;script src="~/lib/signalr/signalr.js"&amp;gt;&amp;lt;/script&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 3 - Add SignalR Client JavaScript
&lt;/h2&gt;

&lt;p&gt;Now we will add a new JavaScript file under the js folder which we will use to connect with the SignalR Server hub and customize all our code in this file.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4tsl7M_s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pe8p1lh3miz3a1fhsqrf.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4tsl7M_s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pe8p1lh3miz3a1fhsqrf.jpg" alt="Image description" width="850" height="626"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 4 –  Connecting to Hub (SignalR Server application)
&lt;/h2&gt;

&lt;p&gt;Similar to the &lt;a href="https://dev.to/satyakarki/receive-real-time-data-in-net-6-client-application-using-signalr-kpj"&gt;previous article&lt;/a&gt;, in this step, we will get familiar with the connection hub builder, which we will be required to connect with the server hub. Only the difference is we are using JavaScript to connect with the Server.&lt;/p&gt;

&lt;p&gt;To make a connection, we need to create HubConnectionBuilder and start the Build, where we have to provide the server URL and message event. The below example withUrl contains the SignalR server URL and SignalR event hub name. You need to provide the correct value in the WithUrl in order to connect with the server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var connection = new signalR.HubConnectionBuilder().withUrl(“http://localhost:53150/ChatHub”)
    .configureLogging(signalR.LogLevel.Information)
    .build();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally, to reconnect automatically when the server connection gets lost, we can use WithAutomaticReconnect() method as well. Moreover, we can use StartAsync() method to start the connection asynchronously.&lt;/p&gt;

&lt;p&gt;The complete code for the connection is given below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:39823/ChatHub", {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
    }).withAutomaticReconnect() //when server get disconnects it reconnects with the serevr
    .configureLogging(signalR.LogLevel.Information).build();
connection.start().then(function() {}).catch(function(err) {
    return console.error(err.toString());
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: You should have CORS enabled in your server app for the signalR client app to be connected.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 5 - Calling Client Method from the hub
&lt;/h2&gt;

&lt;p&gt;Now, it’s time to call the client method to receive messages from the hub. For this, we will use on method of the HubConnection&lt;/p&gt;

&lt;p&gt;We need two things for this.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Name of client method&lt;/li&gt;
&lt;li&gt;Argument(s) that need to pass to the method
Based on my client method name and argument on the method, the connection on code becomes:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;connection.on("receiveEvent", function (message) {
  //receive your message here
 var value = message.Val1;
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Below is the complete code of signalrConnection.js file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use strict"
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:39823/events-hub", {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
    }).withAutomaticReconnect() //when server get disconnects it reconnect with the serevr
    .configureLogging(signalR.LogLevel.Information).build();
connection.start().then(function() {}).catch(function(err) {
    return console.error(err.toString());
});
//Below method is for Receiving message
connection.on("receiveEvent", function(message) {
    var value = message.headerHeight;
    if (message.headerHeight) {
        document.getElementById('lblHeight').innerHTML = ` ${message.headerHeight}`;
    }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 6 - Link the js file
&lt;/h2&gt;

&lt;p&gt;To get and display the received message data in your page, you need to just link the js file on the page where you require showing the message data.&lt;/p&gt;

&lt;p&gt;For the simplicity of this demo, I have just shown the value of the message in the Index.asp page as portrayed below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--iFrcEWgS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/53mnx4xptt9yghzu64au.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iFrcEWgS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/53mnx4xptt9yghzu64au.jpg" alt="Image description" width="797" height="330"&gt;&lt;/a&gt;&lt;br&gt;
In my design page, I have just created a division and label to display the received message on the page.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Checking the output&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now we can run and open the Devtool or inspect the elements in the browser and see the received message. Below is the output of my client application after successfully connecting to the server hub and receiving real-time data from the server.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--m2t1l0BG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6jrsior91lfmleh80wv.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--m2t1l0BG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6jrsior91lfmleh80wv.jpg" alt="Image description" width="850" height="649"&gt;&lt;/a&gt;&lt;br&gt;
On successfully connecting to SignalR hub and receiving the message data, you can work on the design to display the messages on the page according to your need.&lt;/p&gt;

&lt;p&gt;The Git repo of this example can be found here.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;In a nutshell, the article has described and demonstrated how to get real-time data in ASP.NET Core client application from the server application using the SignalR JavaScript client. This article will help you when you have two different applications for SignalR server and client, and you need to use SignalR JavaScript client for your client application.&lt;/p&gt;

&lt;p&gt;Thanks for reading the article.&lt;/p&gt;

&lt;p&gt;If you like to implement the .NET Client for the same purpose, you can refer to the previous article &lt;a href="https://rijsat.com/2022/09/27/how-to-receive-real-time-data-in-an-asp-net-core-client-application-using-javascript-client/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://rijsat.com/2022/09/27/how-to-receive-real-time-data-in-an-asp-net-core-client-application-using-javascript-client/"&gt;Rijsat.com&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&amp;amp;tabs=visual-studio"&gt;Microsoft Learn&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>aspnet</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Receive Real-Time Data In .NET 6 Client Application Using SignalR</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Thu, 10 Nov 2022 12:24:54 +0000</pubDate>
      <link>https://forem.com/satyakarki/receive-real-time-data-in-net-6-client-application-using-signalr-kpj</link>
      <guid>https://forem.com/satyakarki/receive-real-time-data-in-net-6-client-application-using-signalr-kpj</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;SignalR is an open-source library that facilitates to add real-time functionality to web applications. Using this, the server application can push real-time data to the client.&lt;/p&gt;

&lt;p&gt;Microsoft has provided different ways to connect with the SignalR Server application from a client application using various client libraries. This article explains how to connect with the SignalR Server hub and receive message data from the server to the client application using the SignalR .NET client in ASP.NET Core 6 application. There are different ways to receive data from the SignalR server application to the client utilizing different reference packages. In this article we will explore SignalR .NET client and use it in the .NET 6 application to receive the data from the server hub. In this example, we will focus on a client application. This article explains and provides the code sample for the scenario where we have two different applications for the SignalR server and the client. We need to use the .NET client library for the ASP.NET Core 6 application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visual Studio 2022&lt;/li&gt;
&lt;li&gt;Functioning SignalR Server Application
If you already have an existing client application in .NET 6.0, you will need only to implement the signalR .NET client in order to receive the real-time data from your server application. Then you can directly jump into Step Two.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://github.com/SatyaKarki/DemoSignalRClientApp"&gt;Source code&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's get start.&lt;br&gt;
&lt;strong&gt;Step 1 - Create an ASP.NET Core 6 project as usual&lt;/strong&gt;&lt;br&gt;
Open Visual Studio and click on Create a new project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mm9QQOyg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/87kffrzh38r1kssbd5ag.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mm9QQOyg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/87kffrzh38r1kssbd5ag.jpg" alt="Image description" width="880" height="425"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Select ASP.NET Core web app as illustrated below and click on Next.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--s4BRRxzk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ukc39en331uqrzy89s8.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--s4BRRxzk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ukc39en331uqrzy89s8.jpg" alt="Image description" width="880" height="469"&gt;&lt;/a&gt;&lt;br&gt;
Give the project name, location of the project, and click Next.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xbDHFkjb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0slvcv8aseftu45ap5x.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xbDHFkjb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0slvcv8aseftu45ap5x.jpg" alt="Image description" width="880" height="469"&gt;&lt;/a&gt;&lt;br&gt;
Then select the Framework: .NET 6.0(Long-term support) as shown below and click Create.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--r_EuDf-N--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxfts4sxuki0txy8lymj.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--r_EuDf-N--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxfts4sxuki0txy8lymj.jpg" alt="Image description" width="880" height="469"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, your default SignalR client app will be created. You will be able to run it and see the default design in the browser.&lt;/p&gt;

&lt;p&gt;Now, let’s move to SignalR client part.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2 - Install SignalR .NET Client&lt;/strong&gt;&lt;br&gt;
Once the project is created, we can now move to the SignalR .NET client steps.&lt;/p&gt;

&lt;p&gt;You can open the terminal in Visual Studio, and can install the SignalR .NET client using the command given below.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Install-Package Microsoft.AspNetCore.SignalR.Client&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZE7prTKg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4n41kpm661i9j6044sg.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZE7prTKg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4n41kpm661i9j6044sg.jpg" alt="Image description" width="880" height="469"&gt;&lt;/a&gt;&lt;br&gt;
Alternatively, you can search and install it from the NuGet Package manager.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8O5MShXV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q6i068mwjngh192o1q1s.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8O5MShXV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q6i068mwjngh192o1q1s.jpg" alt="Image description" width="880" height="423"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3 - Connecting to Hub (SignalR Server application)&lt;/strong&gt;&lt;br&gt;
Here, we will become familiar with the connection hub builder. This is required for connecting with the server hub.&lt;/p&gt;

&lt;p&gt;To make a connection, we need to create HubConnectionBuilder and start the Build. There we must provide the server URL and message event. The example below, withUrl, contains the signalR server URL and signalR event hub name. You need to provide the correct value in the WithUrl in order to connect with the server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var connection = new HubConnectionBuilder()
                .WithUrl("http://localhost:53150/ChatHub")
                .Build();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally, to reconnect automatically when the server connection gets lost, we can use WithAutomaticReconnect() method. Moreover, we can use the StartAsync() method to start the connection asynchronously.&lt;/p&gt;

&lt;p&gt;The complete code for the connection is given below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;connection = new HubConnectionBuilder().WithUrl("http://localhost:39823/events-hub", options =&amp;gt; {
    options.Transports = HttpTransportType.WebSockets;
}).WithAutomaticReconnect().Build();
await connection.StartAsync();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s go to the project and create a connection with the Server and receive the message. For simplicity, I will use the Privacy Action Controller. In a real application, you can keep the connection and data receive code in your service class and call it in wherever you need it.&lt;/p&gt;

&lt;p&gt;For simplicity, let’s go to the Privacy Action of HomeController and create a connection with the SignalR server.&lt;/p&gt;

&lt;p&gt;Here is the code of my HomeController Privacy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task &amp;lt; IActionResult &amp;gt; PrivacyAsync() {
    var connection = new HubConnectionBuilder().WithUrl("http://localhost:39823/events-hub", options =&amp;gt; {
        options.Transports = HttpTransportType.WebSockets;
    }).WithAutomaticReconnect().Build();
    await connection.StartAsync();
    return View();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.SignalR.Client;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: The above should be included in the controller, and the HubConnection connection should be defined in the Home Controller.&lt;/p&gt;

&lt;p&gt;Now, we need to change the default Privacy ActionResult to the Async as well.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--PUlfx_Cw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lo2jfprc50gl7aifiv0q.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PUlfx_Cw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lo2jfprc50gl7aifiv0q.jpg" alt="Image description" width="855" height="443"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Up until now, we have created the connection to the Server. Now we will move to receiving data in the client application.&lt;/p&gt;

&lt;p&gt;To receive the data, write the following code just below the connection code in the same controller action.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task &amp;lt; IActionResult &amp;gt; PrivacyAsync() {
    var connection = new HubConnectionBuilder().WithUrl("http://localhost:39823/events-hub", options =&amp;gt; {
        options.Transports = HttpTransportType.WebSockets;
    }).WithAutomaticReconnect().Build();
    await connection.StartAsync();
    string newMessage1;
    connection.On &amp;lt; object &amp;gt; ("receiveEvent", (message) =&amp;gt; {
        Console.WriteLine(message);
        var newMessage = JsonConvert.DeserializeObject &amp;lt; dynamic &amp;gt; (message.ToString());
        newMessage1 = $ "{newMessage.chainTip}";
    });
    return View();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In my case, the server will send data to the client with the name receiveEvent. In the chat application, it can appear as ReceiveMessage. You can check your server code for your own case.&lt;/p&gt;

&lt;p&gt;Once receive the message, I have deserialized the it.&lt;/p&gt;

&lt;p&gt;The complete code can be found below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using DemoSignalRClientApp.Models;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR.Client;
using Newtonsoft.Json;
using System.Diagnostics;
namespace DemoSignalRClientApp.Controllers {
    public class HomeController: Controller {
        private readonly ILogger &amp;lt; HomeController &amp;gt; _logger;
        HubConnection connection;
        public HomeController(ILogger &amp;lt; HomeController &amp;gt; logger) {
            _logger = logger;
        }
        public IActionResult Index() {
            return View();
        }
        public async Task &amp;lt; IActionResult &amp;gt; PrivacyAsync() {
                var connection = new HubConnectionBuilder().WithUrl("http://localhost:39823/events-hub", options =&amp;gt; {
                    options.Transports = HttpTransportType.WebSockets;
                }).WithAutomaticReconnect().Build();
                await connection.StartAsync();
                string newMessage1;
                connection.On &amp;lt; object &amp;gt; ("receiveEvent", (message) =&amp;gt; {
                    Console.WriteLine(message); //write in the debug console
                    var newMessage = JsonConvert.DeserializeObject &amp;lt; dynamic &amp;gt; (message.ToString());
                    newMessage1 = $ "{newMessage.chainTip}";
                });
                return View();
            }
            [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error() {
            return View(new ErrorViewModel {
                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
            });
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, our client application is ready now. We can run client and server applications at once and test whether the client app is able to receive data from the server or not.&lt;/p&gt;

&lt;p&gt;Below is the result of my Client application successfully receiving the data from the server.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TFhAwKpd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4gt2e3xl9nbxjhlyu3u.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TFhAwKpd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4gt2e3xl9nbxjhlyu3u.jpg" alt="Image description" width="809" height="229"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we have learned to how get the data in a client application from the server application using SignalR .Net client in ASP.NET Core web application.&lt;/p&gt;

&lt;p&gt;As Microsoft has provided different ways to connect with the SignalR Server application from a client application, using various client libraries such as .NET Client, JavaScript Client, Java Client, and so on. In the next part of this series, we will learn how to use a JavaScript client library for the same purpose. If you have any queries, concerns, or feedback, please feel free to write them in the comment section.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://docs.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-6.0&amp;amp;tabs=visual-studio"&gt;Microsost Docs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://rijsat.com/2022/07/22/how-to-receive-data-in-asp-net-core-client-application-from-the-server-using-asp-net-core-signalr-client/"&gt;Rijsat.com&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>dotnet</category>
      <category>signalr</category>
      <category>csharp</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Global AI Developer Days 2022- Philippines</title>
      <dc:creator>Satya Karki</dc:creator>
      <pubDate>Wed, 19 Oct 2022 11:29:05 +0000</pubDate>
      <link>https://forem.com/satyakarki/global-ai-developer-days-2022-philippines-2pbl</link>
      <guid>https://forem.com/satyakarki/global-ai-developer-days-2022-philippines-2pbl</guid>
      <description>&lt;p&gt;We are going to organize the Global AI developer days in the Philippines on October 26th 2022. It's a free webinar so If you would like to join the session please register in the provided link &lt;a href="https://www.eventbrite.com/e/global-ai-developer-days-philippines-2022-tickets-433420822347"&gt;here &lt;/a&gt;and save the date.&lt;/p&gt;

&lt;p&gt;Details can be found:&lt;br&gt;
&lt;a href="https://rijsat.com/2022/10/06/global-ai-developer-days-philippines-2022/"&gt;https://rijsat.com/2022/10/06/global-ai-developer-days-philippines-2022/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>developer</category>
      <category>webinar</category>
      <category>globalaideveloperdays</category>
      <category>ai</category>
    </item>
  </channel>
</rss>
