avatarSukhpinder Singh | C# .Net

Summary

The website content provides an overview of five essential .NET automation scripts that enhance productivity and software quality by automating unit testing, database migrations, API testing, cloud deployments, and log monitoring.

Abstract

The article discusses the power of automation in .NET development, detailing five key scripts that can significantly improve a developer's workflow. It begins by emphasizing the importance of automation in streamlining repetitive tasks and ensuring code reliability. The first script involves unit testing with xUnit, which automatically runs tests after code changes. The second script automates database migrations using Entity Framework Core, ensuring schema consistency. The third script demonstrates how to use Newman with Postman for automated API testing. The fourth script covers the automation of Azure deployments using PowerShell, which simplifies the deployment process. Lastly, the article explains how to automate log monitoring and alerting using Serilog and Seq, enhancing the ability to quickly address critical issues. The article concludes by encouraging developers to integrate these automation scripts into their daily routines to boost efficiency and software quality.

Opinions

  • The author believes that automation is a time-efficient approach that also reduces the likelihood of missing important code issues.
  • Automating unit tests is likened to having a safety net, ensuring code works correctly and allowing developers to focus on development.
  • The use of Entity Framework Core for database migrations is highly recommended for maintaining schema consistency across environments.
  • Newman's integration with .NET for API testing is presented as a significant time-saver, especially for complex APIs.
  • Automating cloud deployments, particularly to Azure, is seen as a way to achieve quick, reliable, and up-to-date application releases.
  • The author advocates for the use of Serilog and Seq for log monitoring, highlighting the benefits of real-time alerts for critical issues to improve application uptime and reliability.
  • The article conveys that these automation practices are not just about saving time but also about enhancing the overall quality and reliability of software applications.

AUTOMATION

5 Must-Have .NET Automation Scripts to Supercharge Your Application

Discover five powerful automation scripts using .NET that streamline testing, database migrations, deployments, and more to boost your productivity as a developer

Created by Author using Canva

Have you ever known that you can use .NET to create mind-blowing automation scripts?

No matter whether you are testing, streamlining repetitive tasks, or integrating different tools into your workflow, automation can be incredibly power-boosting.

Richie Rich did Automation way before

In this article, we are going to explore five must-try automation scripts you can create with .NET and C#. These were implemented to tackle some real-world problems, provide avenues for efficiencies and improvements, and above all, they’re going to make you a more effective developer. Let’s dive right in!

1. Unit Testing with xUnit

Even though running a test might seem cumbersome and lengthy, especially for a scaled project, this is where automation comes in handy. Utilizing xUnit and C#, you can automate your unit test to ensure that your code is sound and free of errors all the time.

Here’s the simplest automation script that automatically runs all your xUnit tests after changes in your codebase.

First, you need to add xUnit as a dependency in your project:

dotnet add package xunit

Let’s create the simplest unit test with xUnit:

using Xunit;
public class CalculatorTests
{
    [Fact]
    public void Add_ReturnsCorrectSum()
    {
        var calculator = new Calculator();
        var result = calculator.Add(2, 3);
        Assert.Equal(5, result);
    }
}

Using dotnet-watch

You can run these tests automatically whenever a file changes, using dotnet-watch. This is a command-line tool that watches your project for changes.

Install dotnet-watch as a tool in your project.

dotnet tool install --global dotnet-watch

Now let’s run this command and begin to watch for changes and execute tests in perpetuity:

dotnet watch test

With this configuration, your unit tests will automatically run anytime you are saving a file. It just becomes an amazing way to be assured that your code is always within a tested state without having to run tests manually.

Automating tests is not only more time-efficient but also gives you a lower chance of missing some important issues in your code. It’s almost like the safety net about ensuring your code works correctly, leaving you free to focus on development.

2. Database Migrations — EF Core

Schema consistency must be kept across environments. This is something that is not easy for developers to cope with when working with a database. Entity Framework Core (EF Core) is a very popular ORM for .NET developers. It contains built-in support for migrations. You can even automate your database migrations so that the schema of your database will always be in sync with your models.

How To Install the EF Core Packages:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Now, you need to create a model and include that in your DbContext:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
}

Use the following command to create a migration:

dotnet ef migrations add InitialCreate

To make these database updates automatized, you could have a script that takes the migrations and applies them immediately when the application begins running.

public class Program
{
    public static void Main(string[] args)
    {
        using (var context = new BloggingContext())
        {
            context.Database.Migrate();
        }
    }
}

Every time you run your application, it’ll check for pending migrations and apply them automatically.

Automating database migrations assures you that your database is always in the correct state

3. API Testing with Newman and Postman

API testing with tools such as Postman saves lots of time, especially when dealing with large or complex APIs, or instead you could automate these tests. Newman is the CLI tool built by Postman, which lets you run collections of Postman tests from a command line, and you will able to integrate that with .NET for automating API testing.

How To Do It

First, export your Postman collection: Open Postman and select the collection you want to automate.

Click “Export” and save your collection as a JSON file. Now you will install Newman globally:

npm install -g newman

Lastly, you can write a simple c# script that calls Newman and runs your collection automatically:

var processInfo = new ProcessStartInfo("newman", "run path/to/collection.json")
{
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    UseShellExecute = false,
    CreateNoWindow = true
};

using (var process = Process.Start(processInfo))
{
    var output = process.StandardOutput.ReadToEnd();
    var error = process.StandardError.ReadToEnd();
    process.WaitForExit();

    Console.WriteLine(output);
    if (!string.IsNullOrEmpty(error))
    {
        Console.WriteLine($"Error: {error}");
    }
}

You can set up this script to run at regular periods via Task Scheduler (Windows) or cron (Linux)

This means you can steadily validate the functionality of your API without human intervention. This is especially useful in CI/CD pipelines as you catch issues early on before hitting production.

Giphy of a worker generating his clones

4. Azure Deployments - PowerShell

You can automate the application deployment with .NET and PowerShell.

How to Do It

Step 1: Install the Azure PowerShell module

Install-Module -Name Az -AllowClobber -Force

Step 2: Create a PowerShell script that deploys your application PowerShell

$resourceGroupName = "YourResourceGroup"
$webAppName = "YourWebApp"
$pathToZip = "path/to/your/app.zip"

# Login to Azure and deploy the app
az webapp create --resource-group $resourceGroupName --name $webAppName --plan YourAppServicePlan
az webapp deployment source config-zip --resource-group $resourceGroupName --name $webAppName --src $pathToZip
Write-Host "Deployment successful!"

You can automate this script by using a CI/CD tool like GitHub Actions or Azure Pipelines to trigger new code pushes.

Truly, automating cloud deployments eliminates the otherwise tiresome steps of manual deployment. It makes possible quick and reliable deployment, ensuring that your application is always live as it would be up to date with the latest changes.

5. Log Monitoring and Alerting - Serilog

You could automate log monitoring by using Serilog and any of the more reputable monitor tools such as Seq, and, using Seq, actually enables alerting of critical issues.

How to Do It

First, install Serilog and Serilog.Sinks.Seq:

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Seq

Configure Serilog in your application to log to Seq:

using Serilog;

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Seq("http://localhost:5341")
            .CreateLogger();
        try
        {
            Log.Information("Starting web host");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog() // use Serilog to log it
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

The alert will be triggered in Seq to be alerted whenever a certain error condition is encountered. These may include exceptions or error codes of a certain range.

By automating log monitoring and creating alerts, you would quickly catch critical issues in your application, thereby improving uptime and reliability.

Conclusion

These five automation scripts are just a start for all you can do with .NET and C#. Automating repetitive and critical tasks like testing, database migrations, deployment, API validation, and log monitoring saves time but also means that the overall quality and reliability of your software have improved.

You can easily implement these scripts in your day-to-day development workflow to make you a more efficient and productive developer.

Thank you for reading..!!
Csharp
Software Development
Programming
Automation
Web Development
Recommended from ReadMedium