How to Generate Thumbnail from a Video in C# Dotnet Core.

We have been generating thumbnails from image and we all know how easy is this in todays world with some awesome libraries available to us .

But when coming to generate a thumbnail from a video in C# we are left with very limited option.

But to our rescue is a beautiful library Xabe.FFmpeg by tomaszzmuda

This Library does more of what you can expect.

To understand more. This Library is a Cross-platform wrapper for FFmpeg.

FFmpeg – A complete, cross-platform solution to record, convert and stream audio and video. To read more about it click here

Please Note: ffmpeg is required to be present in your machine to use this package.

Downloading FFmpeg

We can Download it directly from the website

OR

You can use a beautiful Download Package and download it in runtime when required.

Using Xabe.FFmpeg.DOWNLOADER

using Xabe.FFmpeg.Downloader;

await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, @"c:\ffmpeg");

This will download the two files required to work with the above package. to the path you mentioned. In out case its c:\ffmpeg

USING Xabe.FFmpeg

Now you can just start using the library.

Set the Path for the package to find the executeables.

using Xabe.FFmpeg;

FFmpeg.SetExecutablesPath(@"c:\ffmpeg");

Now you can provide the video for with the thumbnail is to be generated.

using Xabe.FFmpeg;

var conversion = await FFmpeg.Conversions.FromSnippet.Snapshot(originPath, outputPath,TimeSpan.FromSeconds(0));
IConversionResult result = await conversion.Start();

And you are Done. You can now find the Thumbnail in the outputPath you mentioned. In case you want the image generated you can read as stream from the above path.

Thanks

Happy coding.

I didn’t know it was this easy to handle Exceptions in .Net Core Web API. EasyException !!

An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: trycatchfinally, and throw.

Now that we have come to an era on Middlewares we now use a middle to handle all kinds of Exception at one place.

This is where EasyExceptions comes in. Click here

This Lightweight Library removes your headache of defining a error response standard and just let you think about handling exceptions and what error code to be returned.

The library Implements the standard model suggested by Microsoft to handle errors/faults in system and correclty respond to it.

The Library lets you implement all the logics you want when an exception takes place in your system, and then later converts the ErrorResponse to client/users .

How to Use the Library?

Using the library is really simple.

You might have different exception in you system.

Say a domain Exception,

public class ProfileDomainException : Exception
{
   public ProfileDomainException(string message) : base(message)
   {
   }
}

and just like this many more.

So you Implement an interface Exposed by the EasyExtention library IErrorHandlingService as below\

you can Implement the above Interface like the below sample.

using EasyException.Abstractions;

 public class ErrorHandlingService : IErrorHandlingService
    {
        public Task<ErrorResponse> HandleException(Exception exception)
        {
            switch (exception)
            {
                case ProfileApiException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "ApiError", Message = exception.Message });

                case ProfileDomainException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "DomainError", Message = exception.Message });

                case ProfileApplicationException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "AppError", Message = exception.Message });

                default:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "InternalError", Message = exception.Message });
            }
        }
    }

Now , in the StartUp.cs you can then register your Implementation as a singleton

 public void ConfigureServices(IServiceCollection services)
 {
  services.AddSingleton<IErrorHandlingService,ErrorHandlingService>();
  ...
  

And then configuring the app builder you can tell the app to use the middleware.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
   app.UseEasyExceptionHandling();
   ...
   

Now we can see the response can be in the below format .

ErrorResponse : Object
PropertyTypeRequiredDescription
errorErrorThe error object.
Error : Object
PropertyTypeRequiredDescription
codeStringOne of a server-defined set of error codes.
messageStringA human-readable representation of the error.
targetStringThe target of the error.
detailsError[]An array of details about specific errors that led to this reported error.
innererrorInnerErrorAn object containing more specific information than the current object about the error.
InnerError : Object
PropertyTypeRequiredDescription
codeStringA more specific error code than was provided by the containing error.
innererrorInnerErrorAn object containing more specific information than the current object about the error.
{
    "code": "BadArgument",
    "message": "Previous passwords may not be reused",
    "target": "password",
    "innererror": {
      "code": "PasswordError",
      "innererror": {
        "code": "PasswordDoesNotMeetPolicy",
        "minLength": "6",
        "maxLength": "64",
        "characterTypes": ["lowerCase","upperCase","number","symbol"],
        "minDistinctCharacterTypes": "2",
        "innererror": {
          "code": "PasswordReuseNotAllowed"
        }
      }
    }
  }

ITs Done !! Its that easy. All you logic of handling the exceptions are now in one place.

Thanks

Happy Coding!

Execute a piece of C# code anytime in VS Code using .NET Interactive Notebooks

.Net Interactive Notebooks is an extension being developed by Microsoft, and this extension adds support for using .NET Interactive in a Visual Studio Code notebook.

The source code to this extension is available on https://github.com/dotnet/interactive and licensed under the MIT license.

Getting Started

  1. Install the latest Visual Studio Code.
  2. Install the latest .NET 5 SDK
  3. Install the .NET Interactive Notebooks extension from the marketplace.

Before this we used to go and find some online tools or LINQ Pad to run our C# code to check the output. But creating a sample project just to check a logic has never been easy. But now this has been made even simpler with the .NET Interactive.

Basically what it does is allow you to write your code and execute there itself, to check the output.

Screenshot of a Vs Code .Net Interactive Tab.

In the above screenshot we can see its so easy to just print Hello world there itself, This is quick and save a lot of time. You can also save this file and load and run the part of code you want to execute. You could also share this file with some one and make it easier to just execute the part of code he/she wants.

How to Use the Extention ?

Once you have installed the extension press Ctrl + Shift + P to open the Command tab and select the option .NET Interactive Create new blank notebook as shown below. This will create a new notebook which you can save and share.

Hope you loved this insight.

Happy Coding.

Introduction To SOLID Principles

SOLID is an acronym for 5 important design principles when doing OOP (Object Oriented Programming).

These 5 principles were introduced by Robert C. Martin (Uncle Bob), in his 2000 paper Design Principles and Design Patterns.

The actual SOLID acronym was, however, identified later by Michael Feathers.

The intention of these principles is to make software designs more understandable, easier to maintain and easier to extend. As a software engineer, these 5 principles are essential to know!

This tutorial will take you through step by step approach and examples using Java while learning Design Pattern concepts.

What is SOLID?

 SOLID stands for

  1. S- Single Responsible Principle (SRP).
  2. O- Open Closed Principle (OSP).
  3. L- Liskov Substitute Principle (LSP).
  4. I- Interface Segregation Principle (ISP).
  5. D- Dependency Inversion Principle (DIP).

Benefits of SOLID

  1. It makes software design more understandable, flexible, and maintainable.
  2. Best suitable principle can be used as per project requirement.
  3. Loosely coupled.
  4. Parallel Development.
  5. Testability.
  6. Code becomes smaller and cleaner
  7. Maintainability – Large Systems or Growing systems become complicated and difficult to maintain. This Principle helps us to create a maintainable system. A maintainable system is very important in industries.

S – Single Responsible Principle (SRP)

In programming, the Single Responsibility Principle states that every module or class should have responsibility over a single part of the functionality provided by the software.

A class should only have one responsibility. Furthermore, it should only have one reason to change

How does this principle help us to build better software? Let’s see a few of its benefits:

  1. Testing – A class with one responsibility will have far fewer test cases
  2. Lower coupling – Less functionality in a single class will have fewer dependencies
  3. Organization – Smaller, well-organized classes are easier to search than monolithic ones

Problem

To understand the SRP principle, let’s assume we have working on an application which involve working with employees. We have an interface IEmployeeStore and it’s implementation  EmployeeStore  which have following methods.

public class Employee 
{
    public string Name { get; set;}
    public string Address { get; set;}
    public string Organization { get; set;}
}
public interface IEmployeeStore 
{
    public Employee GetEmployeeById(Long id);
     
    public void AddEmployee(Employee employee);
     
    public void SendEmail(Employee employee, String content);
}
public class EmployeeStore : IEmployeeStore 
{
    public Employee GetEmployeeById(Long id) 
    {
        return null;
    } 

    public void AddEmployee(Employee employee)
    {        
    }

    public void SendEmail(Employee employee, String content)
    {
    }
}

Above class seems good on any normal application. using EmployeeStore, are able to get/add employees and send email to them.

Now suppose after product release, we got requirement that email content can be of two types i.e. HTML and text. Above class supprt only text content. What you will do?

One way to solve this issue is create another method sendHtmlEmail() – but what happens when we are asked to support different protocols for sending emails for both content types. Overall class will look very ugly and difficult to read and maintain.

And there is always a chance that during modification, some developer can change the logic used for get/add employee methods if they are shared.

Solution

public interface IEmployeeStore 
{
    public Employee GetEmployeeById(Long id);
     
    public void AddEmployee(Employee employee);
}
public class EmployeeStore : IEmployeeStore 
{
    public Employee GetEmployeeById(Long id) 
    {
        return null;
    } 

    public void AddEmployee(Employee employee)
    {        
    }
}
public interface IEmailSender 
{
    public void SendEmail(Employee employee, IEmailContent content);
}
public class EmailSender : IEmailSender
{
    public void SendEmail(Employee employee, IEmailContent content) 
    {       
        //logic
    }
}
public interface IEmailContent
{
    public String type;
    public String content;
}
public class EmailContent : IEmailContent 
{
    public String type;
    public String content;
}

Now if we want to change the email functionality, we will change EmailSender class only. Any change to employee CRUD operations will happen in EmployeeStore only. Any change in one capability will not change other one by mistake. They are not more easy to read and maintain as well.

O- Open Closed Principle (OSP)

Bertrand Meyer defines OCP in 1988, “Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.”

Let’s now discuss on what are the problems this principle solved, 

Simply put, classes should be open for extension, but closed for modification. In doing so, we stop ourselves from modifying existing code and causing potential new bugs in an otherwise happy application.

Of course, the one exception to the rule is when fixing bugs in existing code

OCP says a class should be,

  1. Open for extension – means we need to create a base class and that class will be available for extension. This class should have common functionality.
  2. Close for Modification – Instead of changing the base class, we will extend the base class and add/modify type-specific coding in the derived class.
O- Open Closed Principle (OSP)

Let’s explore the concept further with a quick code example. As part of a new project, imagine we’ve implemented a Guitar class.

It’s fully fledged and even has a volume knob:

public class Guitar {

    private String make;
    private String model;
    private int volume;

    //Constructors, getters & setters
}

We launch the application, and everyone loves it. However, after a few months, we decide the Guitar is a little bit boring and could do with an awesome flame pattern to make it look a bit more ‘rock and roll’.

At this point, it might be tempting to just open up the Guitar class and add a flame pattern – but who knows what errors that might throw up in our application.

Instead, let’s stick to the open-closed principle and simply extend our Guitar class:

public class SuperCoolGuitarWithFlames extends Guitar {

    private String flameColor;

    //constructor, getters + setters
}

By extending the Guitar class we can be sure that our existing application won’t be affected.

L-Liskov Substitution Principle (LSK)

Barbara Liskov introduced this principle in 1987 in the conference (Data abstraction and hierarchy) hence it is called the Liskov Substitution Principle (LSK). This principle is just an extension of the Open Close principle.

Robert C Martin also defines this principle. His definition of LSK is “Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it”.

Let’s just jump straight to the code to help wrap our heads around this concept:

public interface Car {

    void turnOnEngine();
    void accelerate();
}

Above, we define a simple Car interface with a couple of methods that all cars should be able to fulfill – turning on the engine, and accelerating forward.

Let’s implement our interface and provide some code for the methods:

public class MotorCar implements Car {

    private Engine engine;

    //Constructors, getters + setters

    public void turnOnEngine() {
        //turn on the engine!
        engine.on();
    }

    public void accelerate() {
        //move forward!
        engine.powerOn(1000);
    }
}

As our code describes, we have an engine that we can turn on, and we can increase the power. But wait, its 2019, and Elon Musk has been a busy man.

We are now living in the era of electric cars:

public class ElectricCar implements Car {

    public void turnOnEngine() {
        throw new AssertionError("I don't have an engine!");
    }

    public void accelerate() {
        //this acceleration is crazy!
    }
}

By throwing a car without an engine into the mix, we are inherently changing the behavior of our program. This is a blatant violation of Liskov substitution and is a bit harder to fix than our previous 2 principles.

One possible solution would be to rework our model into interfaces that take into account the engine-less state of our Car.

I-  Interface Segregation

Robert C Martin’s definition of ISP, “Clients should not be forced to depend upon interfaces that they do not use.”

The ‘I ‘ in SOLID stands for interface segregation, and it simply means that larger interfaces should be split into smaller ones. By doing so, we can ensure that implementing classes only need to be concerned about the methods that are of interest to them.

For this example, we’re going to try our hands as zookeepers. And more specifically, we’ll be working in the bear enclosure.

Let’s start with an interface that outlines our roles as a bear keeper:

public interface BearKeeper {
    void washTheBear();
    void feedTheBear();
    void petTheBear();
}

As avid zookeepers, we’re more than happy to wash and feed our beloved bears. However, we’re all too aware of the dangers of petting them. Unfortunately, our interface is rather large, and we have no choice than to implement the code to pet the bear.

Let’s fix this by splitting our large interface into 3 separate ones:

public interface BearCleaner {
    void washTheBear();
}

public interface BearFeeder {
    void feedTheBear();
}

public interface BearPetter {
    void petTheBear();
}

Now, thanks to interface segregation, we’re free to implement only the methods that matter to us:

public class BearCarer implements BearCleaner, BearFeeder {

    public void washTheBear() {
        //I think we missed a spot...
    }

    public void feedTheBear() {
        //Tuna Tuesdays...
    }
}

And finally, we can leave the dangerous stuff to the crazy people:

public class CrazyPerson implements BearPetter {

    public void petTheBear() {
        //Good luck with that!
    }
}

Going further, we could even split our BookPrinter class from our example earlier to use interface segregation in the same way. By implementing a Printer interface with a single print method, we could instantiate separate ConsoleBookPrinter and OtherMediaBookPrinter classes.

D – Dependency Inversion

Robert C Martin has defined DIP as, “High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions”. 

Let’s try to understand this principle with an example.

To demonstrate this, let’s go old-school and bring to life a Windows 98 computer with code:

public class Windows98Machine {}

But what good is a computer without a monitor and keyboard? Let’s add one of each to our constructor so that every Windows98Computer we instantiate comes pre-packed with a Monitor and a StandardKeyboard:

public class Windows98Machine {

    private final StandardKeyboard keyboard;
    private final Monitor monitor;

    public Windows98Machine() {
        monitor = new Monitor();
        keyboard = new StandardKeyboard();
    }

}

This code will work, and we’ll be able to use the StandardKeyboard and Monitor freely within our Windows98Computer class. Problem solved? Not quite. By declaring the StandardKeyboard and Monitor with the new keyword, we’ve tightly coupled these 3 classes together.

Not only does this make our Windows98Computer hard to test, but we’ve also lost the ability to switch out our StandardKeyboard class with a different one should the need arise. And we’re stuck with our Monitor class, too.

Let’s decouple our machine from the StandardKeyboard by adding a more general Keyboard interface and using this in our class:

public interface Keyboard { }
public class Windows98Machine{

    private final Keyboard keyboard;
    private final Monitor monitor;

    public Windows98Machine(Keyboard keyboard, Monitor monitor) {
        this.keyboard = keyboard;
        this.monitor = monitor;
    }
}

Here, we’re using the dependency injection pattern here to facilitate adding the Keyboard dependency into the Windows98Machine class.

Let’s also modify our StandardKeyboard class to implement the Keyboard interface so that it’s suitable for injecting into the Windows98Machine class:

public class StandardKeyboard implements Keyboard { }

Now our classes are decoupled and communicate through the Keyboard abstraction. If we want, we can easily switch out the type of keyboard in our machine with a different implementation of the interface. We can follow the same principle for the Monitor class.

Excellent! We’ve decoupled the dependencies and are free to test our Windows98Machine with whichever testing framework we choose.

Conclusion

In this tutorial, we’ve taken a deep dive into the SOLID principles of object-oriented design.

We started with a quick bit of SOLID history and the reasons these principles exist.

Letter by letter, we’ve broken down the meaning of each principle with a quick code example that violates it. We then saw how to fix our code and make it adhere to the SOLID principles.

Special Thanks to : Baeldung

Code Coverage in .NET Core Projects

If you have created a unit test project in .NET Core, then you must have noticed a NuGet package, coverlet.collector, is installed in the default project templates for MSTest and xUnit. What does this NuGet package do?

The coverlet documentation (link) tells us that coverlet is a cross platform code coverage framework for .NET, with support for line, branch and method coverage. It means that we are able to check the code coverage for .NET Core applications using coverlet.

Creating the Coverage Report

Install the NuGet package coverlet.msbuild to the MSTest project using the following command.
dotnet add package coverlet.msbuild
The pre-installed NuGet package coverlet.collector doesn’t work with the dotnet test command. Thus, we need to install the coverlet.msbuild package in order to generate coverage reports in the CI pipeline. This NuGet package integrates coverlet with the .NET build system, so that coverlet will compute code coverage after tests.

Run  dotnet test command to generate a coverage report.

dotnet test /p:CollectCoverage=true /p:CoverletOutput=TestResults/ /p:CoverletOutputFormat=lcov

Several parameters are passed into the dotnet test command. The first one, CollectCoverage=true, means we want to collect code coverage.

The second parameter, CoverletOutput, specifies the output file destination, which is in the TestResults folder. The most commonly available .gitignore file for .NET projects sets the TestResults folder to be ignored for version control. Thus, we will put testing related things into the TestResults folder, so that they won’t be accidentally committed to our code repository if coverage reports are generated locally.

The third parameter, CoverletOutputFormat, indicates the report file format, which is lcov in this case. The coverlet supports many formats, such as opencoverjsonlcovcoberturateamcity, and so on. In this project, we will stick with the lcov format, because the GitHub Actions for coveralls.io uses the lcov format.

If we run the command, then we will see the Console output like the following screenshot.

The Console output of dotnet test with coverlet

The Console output writes out the generated coverage report file path and the coverage metrics, which give us a glimpse of the coverage rates. The generated coverage.info file contains much more detailed information on the line hits, but it is not so readable as compared to the reports after parsing and transformation by specialized tools. We will use an online report service from coveralls.io to visualize the code coverage.

Open Source Testing Tools in C#

NUnit

NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit

Go To NUnit

NUnitForms

NUnitForms is an NUnit extension for unit and acceptance testing of Windows Forms applications.

Go To NUnitForms

dotunit

dotunit is a port of JUnit (www.junit.org) to the Microsoft .net platform. This testing framework allows for automated unit and functional tests which are vital for refactoring and regression testing.

Go To dotunit

VSNUnit

VSNUnit is an integration tool that allows you to execute your NUnit tests from within the IDE. Instead of dumping the results as a text stream to the output window, VSNUnit provides the graphical tree view that NUnit and JUnit users have come to love. The tree view is a dockable toolwindow inside the IDE, allowing you to integrate it with your standard development environment layout.

Go To VSNUnit

EasyMock.NET

EasyMock.NET is a class library that provides an easy way to use mock objects for given interfaces or remote objects

Go To EasyMock.NET

Dot NetUnit

An implementation of XUnit testing framework

Go To Dot NetUnit

MbUnit

MbUnit is an evolutive Unit Test Framework for .Net. It provides new fixtures as well as the framework to create new ones. MbUnit is based QuickGraph, a directed graph library for C#. MbUnit is a superset of NUnit. Now that NUnit has become mainstream and is evolving MbUnit is where much of the action is going on.

Go To MbUnit

Zanebug

Zanebug is an advanced unit testing application for .NET. It provides full support for existing NUnit tests, performance metrics, multiple test iterations, in-depth error information, pass / fail stats, perfmon integration, result graphing, etc.

Go To Zanebug

DotNetMock

DotNetMock is a framework and a library to facilitate the use of MockObjects for unit testing on the .NET platform. It supports the creation of your own MockObjects as well as the dynamic creation of MockObjects. It supports almost any version of NUnit, and MbUnit. DotNetMock DynamicMocks can mock interfaces at runtime and can even modify ref/out parameters.

Go To DotNetMock

Rhino.Mocks

Rhino.Mocks is an attempt to create easier way to build and use mock objects and allow better refactoring support from the current tools. It’s a hybrid approach between the pure Record/Replay of EasyMock.Net’s model and NMock’s expectation based model.

Go To Rhino.Mocks

csUnit

Inspired by JUnit, csUnit brings the power of unit testing to the .NET framework. csUnit is your key to unit testing and test-driven development using .NET languages such as C#, Visual Basic .NET, Visual J#, or Managed C++. csUnit provides versions for VS2002, VS2003, and VS2005 with add-in support. Of course there is also a stand-alone GUI application and a command line. csUnit is open-source but its license (zlib/libpng) also allows for using csUnit or parts of it in closed-source and commercial projects.

Go To csUnit

NUnitAddin

NUnitAddin is a simple addin for VisualStudio 2005 used in association with NUnit framework. The NUnit Addin allows you to run unit tests inside Visual Studio 2005. Features: * Read Visual Studio 2005 files: .sln * Build visual tree from .sln files * Run tests in Visual Studio 2005

Go To NUnitAddin

SystiN

System testing in .Net is a port of the Systir tool from ruby to C#. It allows users to specify plain english text software requirements that can then become executable tests.

Go To SystiN

XtUnit

XtUnit is a unit testing extension for .Net based frameworks. It uses the interception application block to provide runtime abilities of rolling back any changes that were made to the database during Data related unit tests.

Go To XtUnit

Gallio/MbUnit

The Gallio Automation Platform is an open, extensible, and neutral system for .NET that provides a common object model, runtime services and tools (such as test runners) that may be leveraged by any number of test frameworks.

Go To Gallio/MbUnit

Nester

Nester is a tool for mutation testing of your C# source code in order to assess the adequacy of your unit tests. It involves modification of programs to see if existing tests can distinguish the original program from the modified program.

Go To Nester

QAliber

QAliber includes 2 projects: a Visual Studio plug-in and Test Builder + Runner as execute framework. Visual Studio plug-in help writing automatic tests over GUI with control browser and record/play capabilities (but not only, since this project incorporate into development solution API testing is easy to do) The Test Builder is a framework for creating a scenario by simply drag and drop of created building blocks. It already provide big repository of test blocks performing most tasks without coding.

Go To QAliber

Get started with .NET Core

This article provides information on getting started with .NET Core. .NET Core can be installed on Windows, Linux, and macOS. You can code in your favorite text editor and produce cross-platform libraries and applications.

If you’re unsure what .NET Core is, or how it relates to other .NET technologies, start with the What is .NET overview. Put simply, .NET Core is an open-source, cross-platform implementation of .NET.

Create an application

First, download and install the .NET Core SDK on your computer.

Next, open a terminal such as PowerShellCommand Prompt, or bash. Type the following dotnet commands to create and run a C# application:.NET Core CLI

dotnet new console --output sample1
dotnet run --project sample1

You should see the following output:Console

Hello World!

Congratulations! You’ve created a simple .NET Core application. You can also use Visual Studio CodeVisual Studio (Windows only), or Visual Studio for Mac (macOS only), to create a .NET Core application.