fabiochiu/medium-articles huggingface dataset:
Ampere’s Shower Power is a Bluetooth speaker that operates on water power
Tags: Streaming, Surveillance, Connected Home, Gear

Ampere’s Shower Power is a Bluetooth speaker that operates on water power Tracy Jan 15·2 min read

Shower singers rejoice: There’s a Bluetooth speaker built just for you. The $100 Ampere Shower Power attaches to your showerhead and is powered by the water flowing through it.



Run the water and a small generator inside the speaker fires up and turns the speaker on. The generator simultaneously charges a small battery inside the speaker, allowing the music maker to run for up to 20 hours even if the water is turned off.



[ Further reading: The best Bluetooth speakers ]Conservation-minded singers will also appreciate the materials that go into the Shower Power’s construction: Its housing is fabricated entirely from recycled ocean plastic, further shrinking the product’s environmental footprint.



Ampere The Shower Power Bluetooth speaker can be used with both fixed and handheld showerheads.



Despite its diminutive dimensions—3 x 2 inches (HxW)—Ampere says the Shower Power produces impressive sound. A proprietary amplifier radiates sound evenly in all directions, and you can pair the Shower Power with Ampere’s other waterproof speaker—the Droplet—for a more immersive audio experience.



Ampere says it partnered with audio experts who have worked with well-known Bluetooth speaker manufacturers including Monster and Braven, because the company wanted to focus on audio quality.



The Shower Power will be available in three colors to coordinate with your showerhead: white, matte black, and chrome. Ampere also announced this week that it has an LED-light edition of the speaker in development. The Shower Power Shine produces a light show in sync with your music. That's expected to ship it later in 2021.



If you can’t wait for our review of the Shower Power, Ampere is taking pre-orders for the speaker through its crowd-funding campaign at Indiegogo. The speaker is expected to ship sometime in the first quarter of 2021.



Note: When you purchase something after clicking links in our articles, we may earn a small commission. Read our affiliate link policy for more details.
How to Build an Event-Driven ASP.NET Core Microservice Architecture
By: Christian Zink
Tags: C Sharp Programming, Microservices, Rabbitmq, Software Architecture, Aspnetcore

1. Create the .NET Core Microservices

In the first part of this guide, you will create the User and Post Microservice. You will add the Entities and basic Web APIs. The entities will be stored and retrieved via Entity Framework from Sqlite DBs. Optionally you can test the User Microservice with the Swagger UI in the browser.

Let’s get started.

Install Visual Studio Community (it’s free) with the ASP.NET and web development workload.

Create a solution and add the two ASP.NET Core 5 Web API projects “UserService” and “PostService”. Disable HTTPS and activate OpenAPI Support.

For both projects install the following NuGet packages:

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Sqlite

Newtonsoft.Json

RabbitMQ.Client

Implement the UserService

Create the User Entity:

Create the UserServiceContext:

Edit Startup.cs to configure the UserServiceContext to use Sqlite and call Database.EnsureCreated() to make sure the database contains the entity schema:

Create the UserController (It implements only the methods necessary for this demo):

Debug the UserService project and it will start your browser. You can use the swagger UI to test if creating and reading users is working:

Implement the PostService

Create the User and Post entities:

Create the PostServiceContext:

Edit startup.cs to configure the UserServiceContext to use Sqlite and call Database.EnsureCreated() to make sure the database contains the entity schema:

Create the PostController:

Currently, you can’t insert posts, because there are no users in the PostService database.

2. Use RabbitMQ and Configure Exchanges and Pipelines

In the second part of this guide, you will get RabbitMQ running. Then you will use the RabbitMQ admin web UI to configure the exchanges and pipelines for the application. Optionally you can use the admin UI to send messages to RabbitMQ.

This graphic shows how the UserService publishes messages to RabbitMQ and the PostService and a potential other service consume those messages:

The easiest way to get RabbitMQ running is to install Docker Desktop. Then issue the following command (in one line in a console window) to start a RabbitMQ container with admin UI :

C:\dev>docker run -d -p 15672:15672 -p 5672:5672 --hostname my-rabbit --name some-rabbit rabbitmq:3-management

Open your browser on port 15672 and log in with the username “guest” and the password “guest”. Use the web UI to create an Exchange with the name “user” of type “Fanout” and two queues “user.postservice” and “user.otherservice”.

It is important to use the type “Fanout” so that the exchange copies the message to all connected queues.

You can also use the web UI to publish messages to the exchange and see how they get queued:
Blazor: switching Server and WebAssembly at runtime
By: Sergey Zaikin
Tags: C Sharp Programming, Grpc, Aspnetcore, Blazor, Webassembly

Part 1: running Server and WebAssembly simultaneously

We need to start by hosting WebAssembly application inside an ASP.NET Core application and then enabling Pre-rendering.

With this configuration, Blazor starts up in the file _Host.cshtml by adding a component to the page that will create a DOM of our application, and downloading the script that makes our application interactive.

For Server it looks like this:

And for WebAssembly like this:

Therefore, nothing prevents us from loading them at the same time:

Of course this will not work. The point is that the <component> tag turns into html like this:

During application initialization, Blazor looks for this fragment and then replaces it with the application’s DOM. If the scripts blazor.server.js and blazor.webassembly.js are run at the same time, they will both compete for the first component, ignoring the second.

This is easily avoided if we start running blazor.webassembly.js only after blazor.server.js has finished, something like this:

Now both applications start, but do not work correctly. The problem is that both applications subscribe to events (click, submit, onpush, etc.) on document and window . Because of this, Server and WebAssembly try to handle each other's events.

We only want them to listen for events inside their <srvr-app> and <wasm-app> nodes. To do this, we will have to break js best practices and override addEventListener for window and document:

Both apps are now working. All that remains is to wait for WebAssembly to load and enable it by hiding <srvr-app> and displaying <wasm-app> :

Let’s put this logic in a file blazor.hybrid.js and connect it to _Host.cshtml instead of the first two scripts. In the same file we will place a function that will switch the placement model based on a signal from the application. We will call it from the c# code of our application.

From the side of the c# application, let’s create a RuntimeHeader.razor component with the following content:

That’s it, the hybrid app is working. It remains to add a few conveniences, for example, the ability to set the type of the running application in appsettings.json
How to Sign-In with Google in Angular and use JWT based .NET Core API Authentication (RSA)
By: Christian Zink
Tags: Authentication, Angular, Google, Aspnetcore, Jwt

3. Authentication API in the .NET Core Backend

The authentication API will use the idToken from google and verify it. Then it creates an access token that grants access to the other APIs of your app.

You will have to increase security before you run this code in a production environment: Shorter token lifetime and refreshs, maybe use sessions instead of tokens, etc.

Install Visual Studio Community (it’s free) with the ASP.NET and web development workload. Create an ASP.NET Core Web API project.

Verification of the idToken

Use the Visual Studio package manager to install the google Auth Package:

Install-Package Google.Apis.Auth

Create an API to verify the idToken.

Change the value in settings.Audience to your google client ID, that you created in the first step of this guide:

The call to GoogleJsonWebSignature.ValidateAsync will throw in case of an error. The Authenticate method uses the JwtGenerator class to create and return a custom access token.

Create Custom Access Tokens in .NET Core Using Asymmetric Signatures

With asymmetric JWT signing, only the authentication service knows the private key. The authentication service uses the private key to sign the access token and other APIs use only the public key to verify the access token.

Add the JwtGenerator class, that generates the token:

The JwtGenerator uses the private key, that it gets passed from the UserController. Add the key to appsettings.json, where the UserControler reads it from.

You can use my private key for testing but you will have to create your own private-public key pair for production use. You will also have to adjust token lifetime, etc. for production use.

Further reading: JWT Authentication with Asymmetric Encryption using certificates in ASP.NET Core by Eduard Stefanescu. This story also shows how to create your own public-private key pair.

Edit Startup.cs, which configures the ASP.NET Core backend to use the config, allow access from the Angular client, etc.:
DB Sharding & Scaling a NET Core Microservice Arch
By: Christian Zink
Tags: C Sharp Programming, Microservices, Software Architecture, Aspnetcore, Database

1. Usecases and Datamodell

The example application consists of a user and a post microservice. They communicate via messages:

See also my previous article How to Build an Event-Driven ASP.NET Core Microservice Architecture

The User microservice handles adding and modifying users. The Post microservices handles viewing and adding posts. There is far more interaction with the Post microservice. So when the load to the app increases the Post microservice will be the first microservice that needs to scale.

The name of the author is part of the PostService bounded context and therefore the Post microservice. Adding and modifying authors is done in the User microservice. The User microservice sends events when a new user is added or a username changes.

Logical Data Model of the PostService

Users can write posts in categories. They can also read the posts by category including the author name. Newest posts are on top. The categories are fixed and change seldom.

Based on these use-cases I decided to shard by category:
The Outbox Pattern in Event-Driven ASP.NET Core Microservice Architectures
By: Christian Zink
Tags: C Sharp Programming, Microservices, Rabbitmq, Software Architecture, Aspnetcore

1. Create the .NET Core Microservices and Exchange Messages

See my previous article for how to create the Microservices and configure RabbitMQ.

This will give you the following components and workflow:

Now both microservices and the RabbitMQ container “some-rabbit” should be running. Use the REST API of the User service to create and modify users and make sure everything is working. The User service should be sending events to the event bus and the Post service handles them. And the users in the user database are in sync with the users in the post database.

Messages Getting Lost

Stop the RabbitMQ container:

C:\dev>docker stop some-rabbit

Use the Swagger UI to create a user in the UserService:

{

"name": "Chris2",

"mail": "chris2@chris2.com",

"otherData": "Some other data"

}

The RabbitMQ server can’t be reached:

The user is in the user database:

The event is lost and therefore the user is not in the post database and the microservices are now inconsistent. In the next step of this guide, you will see how to solve this problem.
Hardening ASP.NET Core 3.1 Docker Images
By: Michael Dimoudis
Tags: Security, Docker, Aspnetcore

In this blog post I’ll be consolidating a few already available resources online to harden a docker image to specifically run ASP.NET Core workloads. There are open source and commercial 3rd party products out there to help with this, and those should definitely be considered, but this blog is specifically aimed at doing the least amount of work at no extra cost to achieve something better than the default. Note I am not a security expert, and the end result is just consolidated from multiple resources online.

I’ve had this blog post saved in my bookmarks for well over a year now, “Minimising your attack surface by building highly specialised docker images — example for .NET Core 2.1 applications”, but as the title says it’s for .NET Core 2.1 and it was written in 2018. I could not get this approach to work with the current crop of.NET Core 2.2 to 3.1 official Microsoft docker images.

However this week I got a Medium push notification for this blog post “Containerize your .NET Core app — the right way” and it reignited my desire to try and harden an ASP.NET Core 3.1 docker image again. This blog post has one of the most important actions you can take right away though, which is to not run your container as root. But there’s more that can be done as we learned fro the 2018 blog post above.

Starting my research again I stumbled across the GitHub account of “ironPeak services”, a Belgian cybersecurity consulting company, with various hardened docker container image repositories. What really caught my eye was that the hardening commands in the ironPeak docker images were nearly identical to the commands in the above blog post from 2018. Is there a common, known list of hardening commands online somewhere? Probably.

If you are running an ASP.NET Core 3.1 app in a docker container, it’s very likely you’ll be using the standard mcr.microsoft.com/dotnet/core/aspnet:3.1 image. Pushing your app with that image to AWS ECR (Elastic Container Repository) will give you this vulnerability report…

That doesn’t look quite appealing. The high and medium vulnerabilities are listed below, even though they probably have little impact on an ASP.NET Core app itself, I still rather them not be there, and if your app is compromised, an attacker might be able to leverage them.
Bulk Delete documents from Azure Cosmos DB using ASP.NET Core.
By: Sai Vaibhav Medavarapu
Tags: Cosmos, Documentdb, Aspnetcore, Azure

Consuming the Stored procedure on .NET

If you follow the repository design pattern in your application. Create a method inside the repository and later call it in service.

Link for the gist

First, we have to open the connection by using statement. The using statement is actually a syntactic convenience. At compile time, the language compiler implements the intermediate language (IL) for a try/catch block. To connect, we have to use DocumentClient Class from Microsoft.Azure.Documents. This Client has all the methods to create document, query for documents etc. More documentation for document client class can be found here.

Now you connected to the database on the cosmos. Next step is to know where the proc is in that database. So, we can use the CreateStoredProcedureQuery to get proc. This method takes in URI of the database and collection ID, stored proc name and other feed options(we need these during cross partition querying). And, it returns the Query result of type IQueryable<dynamic>.

After we have the proc. We can call ExecuteStoredProcedureAsync on document client class to execute the proc. This method takes in the GUID of the proc and NOT the proc name. We will have access to the GUID from the createstoredprocquery method we wrote previously, which is stored in sprocLink variable. How to use the GUID from it? there is property on it ‘_self’ we can pass in sprocLink._self and what ever inputs the proc takes.

NOTE: If you have the partition keys on your collection, you should query for the partition keys and pass in the partition key as the request options for the proc. (Let me know if there is any other optimal solution, I’m open to learn.)

Conclusion

In this post, we learnt how to write the stored procedures on Azure Cosmos and also how to integrate and use the procedures on .NET.

Thank you for reading the post,

Something somewhere incredible is waiting to be known!
ASP.NET Core 2.2 returning 500.30 on Azure App Service: a debugging story
By: Marco De Sanctis
Tags: Keyvault, Debug, App Service, Aspnetcore, Azure

Last Friday I spent some time investigating an annoying bug we had in production: we have a relatively standard Single Page Web Application, in which a ASP.NET Core 2.2 Web API serves a React.js front-end. The Web API is runs on Azure App Service, using the InProcess hosting mode.

The issue: from time to time, the API would hang and start raising an HTTP 500.30 status code on any endpoint.

When that happened, either a restart or the proactive auto-healing of Azure App Service would eventually fix the issue and restore the functionality. However, this obviously wasn’t something we could live with, so I started doing some digging to understand it a bit further.

It was quite an interesting journey, especially because I was able to investigate the bug without any changes in the code, so I thought it could’ve been useful if I shared it.

What does a 500.30 mean?

Just to be clear and set the context, it’s probably best to clarify that a 500.30 isn’t your average 500 error :) it’s not caused by a controller throwing an exception during the execution, it means something more profound: the unhandled exception is happening during the boot of the application, which therefore is not starting at all.
A few ways to handle errors in .NET
By: George Machaidze
Tags: Error Handling, Csharp, Aspnetcore, Aspnet, Design Patterns

Error handling is always an essential part of an application. When processing some business logic requests, it’s always necessary to let a user know whether the execution result succeeded or failed.

Let’s assume that a user sends you a request for an endpoint, and you have a service that processes the request, but it fails due to the business validation. The easiest way to handle the situation is to create a response model where you input the errors and the status for the execution result to find out whether it succeeded or failed.

I will give you a simple example.

Let’s assume that we have an ExampleController.cs where we have a Test endpoint.

In the test method, we are calling the CreateAsync method that processes the request.

Let’s assume we have some business validations to make where one of them failed, the Controller will need to be notified about the error to return the appropriate status code to the caller. As you can see above, we’ve created an ExampleResponse class that contains all the necessary information for the Controller to return the status code.

But if our codebase grows, we will end up with a big ball of mud. It will also make the development harder.

Let’s take a look at another solution.

A better way to avoid repetitive code, we can create a generic class where we can separate data from the execution result status.

Here is an example of the Result class.

As you can see, the data model and the execution result are separated. This way, we don’t need to add extra properties to our data model. Also, we can create an abstract class for our services, where we can handle the creation of the result class.

In the above example, we’ve created the base service that we can use in our previous service.

We can refactor the ExampleService

Now you can easily add more validations and read the code.

But what if you want to use the existing method in another method? With the above solution, you will end up with a lot of unnecessary validations. Also, the result class is created for the Controllers to notify the client about the execution result. Once you use the existing method, you have to maintain it. First of all, you have to check it against any failures. If it failed, you have to pass the result errors to the current method. A better solution for the problem is to use exceptions.

There are many ways to implement the above solution. For example, you can throw an exception from a method or have an abstract class with appropriate methods. I prefer to use the abstract class; because it’s easier to read and use.

First of all, let’s refactor our base service.

We’ve removed the Succeeded method from the service because we don’t have the result class. If it succeeds, we can return data directly. Also, I’m using generic methods here for readability. Everything else will stay the same in our ExampleService. You can handle exceptions either in a controller or in a middleware.

A few resourceful links:
ASP.NET Core 6.0 Minimal API with Entity framework core
Tags: Entity Framework Core, Asp, Aspnetcore, Executeautomation

Install EF Core within our project

To install EF Core within our existing project, lets add the following Nuget packages

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.8" />



<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.8">



<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.8" />

Create DBContext access class

DBContext will set the EF context for data access and set the DataSet for our model to access data from data source. We are going to call it as EmployeeDbContext

Here we will create the following

//Constructor with DbContextOptions and the context class itself

public EmployeeDbContext(DbContextOptions<EmployeeDbContext> options) : base(options)

{ } //Create the DataSet for the Employee public DbSet<Employee> Employee { get; set; }

Once created, we need to override the OnConfiguring method to read the connection string of database from SQL server via appsettings.json file

Set Dependency Injection with service container

This is done in our Program.cs file

var connectionString = builder.Configuration.GetConnectionString("AppDb"); builder.Services.AddDbContext<EmployeeDbContext>(x => x.UseSqlServer(connectionString));

Finally, Entity Framework Database update via dotnet-ef

Pre-requisite:

Make sure you have already installed the dotnet-ef tool, which can be done something like this

Lets run the command from Powershell/Commandline as to start adding the database and create our first initial tables

To Add Database

dotnet ef database update

To add the migration

dotnet ef migrations add initialDb

The above will create the migration script for us

Complete video demonstration

Here is the complete video of the above article demonstration in action
How to keep startup file lean and clean in Dotnet core
By: Vikas Sharma
Tags: Single Responsibility, Extension Method, Csharp, Clean Code, Aspnetcore

How to keep startup file lean and clean in Dotnet core Vikas Sharma Follow Mar 22 · 3 min read

If you are reading this you are already using Asp.Net Core and the Startup file is your go-to place to register dependencies, setting up third-party dependencies, and configure your app behavior.

One file and so many responsibilities 🤔

Startup file juggling with so many responsibilities

If your Startup file contains more than 100 lines of code then you really need to think it through and make it leaner and cleaner.

Why should I care?

First of all, it is harder to read and maintain lengthy files

It's not very organized and it is tough to find related things

With time and increase in the code base, the startup file becomes the God file

It’s hard to set up a convention for the junior developers or new joiners in the team

It’s violating the Single Responsibility Principle

Making Startup file lean and clean

Let’s take a peek into a God Startup file

If your startup file looks similar to the above one then it’s time to do some cleaning.

There’s nothing wrong with having a startup file shown here but the real problem arises when your codebase starts to become bigger and more developers join the team.

Extension Method to the rescue

The simple technique to make startup file lean is to use extension methods. Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

We can create separate extension methods to have specific functionalities like we can create one extension method to keep all code related to authentication, similarly, one method to have all the swagger-related code.

Let’s do some cleanup

Creating extension methods to register services/repositories dependencies:

Typically a web project contains separate dll projects for repository and services. Both the projects can contain their own Startup.cs file that can be used to register dependencies

Project Structure

Let’s create separate Startup files for Repository and Services in their respective projects.

Create a Startup to register repository dependencies:

Repository Startup.cs

Create a Startup to register services dependencies:

Services Startup.cs

Let’s also create a Swagger extension method to move all the swagger-related configurations.

What we did so far is simple, we just split the one startup into multiple startups with their responsibilities.

Let’s see the final version of the original startup.cs:

Improvements:

Reduce no of using statements (namespaces)

Better readability

Separation of responsibility

Final Words

The code shown is very simple and you must be already doing it but I know there are people who still struggle with lengthy startup files and my suggestion to them is just take a little and start cleaning up as it is very simple to achieve with minimum efforts.
ASP.NET Core Serverless Web API running in AWS Lambda, using API Gateway HTTP API, with a Lambda Warmer
By: Michael Dimoudis
Tags: AWS, AWS Lambda, Aspnetcore, Serverless, Aws Api Gateway

ASP.NET Core Serverless Web API running in AWS Lambda, using API Gateway HTTP API, with a Lambda Warmer Michael Dimoudis Jul 7, 2020·2 min read

Back in April 2019 I blogged about running an ASP.NET Core 2.2/3.0 Serverless Web API in AWS Lambda with a Custom Runtime and Lambda Warmer.

Things have changed since then; AWS Lambda now supports .NET Core 3.1 (custom runtime no longer required) and AWS released HTTP APIs for Amazon API Gateway which GA’d in March 2020.

Both announcements are huge for .NET developers wanting to host an ASP.NET Core Web API in the cloud, serverless and cheap. HTTP APIs for Amazon API Gateway offer up to 71% cost savings and 60% latency reduction compared to REST APIs. If you do not need the more advanced features a REST API gives you, it makes a lot of sense to use the new HTTP APIs for API Gateway.

I will keep this blog very concise, all the code to deploy this serverless Web API with 1 line of code is in this sample GitHub repo.

The only code change required to support HTTP APIs for Amazon API Gateway is updating the base class in the LambdaEntryPoint to APIGatewayHttpApiV2ProxyFunction .

Regarding the CloudFormation template file, serverless.template , the change required there is to change the Events in AWS::Serverless::Function from Api to HttpApi . I have also extended the built in template to add an API Gateway Domain Name with a mapping, including updating Route53 with the A alias record for your API’s domain name. This will allow you to serve the API off your own domain name.

Simply specifying DomainName , CertificateArn , and Route53 HostedZoneId in aws-lambda-tools-defaults.json , and then running dotnet lambda deploy-serverless will spin up the entire infrastructure (HTTP API for Amazon API Gateway / Lambda) and an ASP.NET Core Web API in minutes, ready to serve requests in a serverless and scalable way.

As a bonus I updated the Lambda Warmer in my previous blog post to work with the new API Gateway HTTP APIs, doing an effective job in forgoing cold starts by specifying the number of instances you want to keep warm.

A CodeBuild buildspec.yaml file is also provided to deploy this out. I recommend choosing the aws/codebuild/amazonlinux2-x86_64-standard:3.0 environment image, as PublishReadyToRun is set to true to further improve the performance of the API.

Once deployed just hit the API endpoint https://api.mydomain.com/api/values to make sure it’s all working. (remember to use your own domain name)

https://github.com/michaeldimoudis/aspnetcore-lambda-httpapi-serverless

More in depth reading about .NET Core 3.1 in Lambda and API Gateway HTTP APIs can be found at:
ASP.NET Core 2.2 & 3 REST API #28 — Resource Filtering
By: Theodoros Ntakouris
Tags: Software Engineering, Microsoft, Csharp, Aspnetcore, Rest Api

In this use case, we want to filter posts by owner id (user id). Just pass a new query parameter on our controller method, and then change the PostService to include it.

In our service, we can refactor it a bit to make it easy to use for our filtering, extracting a queryable ( DbSet<> ) in order to be able to optionally apply a predicate before hitting the database, with the filter actually being as simple as x => x.UserId == userId

This is fine and all, working as expected, but what happens when you want to add a second and a third and a fourth… filter? We are not going to add more and more query parameters, the namespace is going to be polluted with such big method signature. We are going to extract a new filter object, the same way we did with our pagination.

Under Contracts/V1/Requests/Query create a GetAllPostsQuery class.

The next logical step would be to also change the signature of our controller method, and the service method as well.

Go ahead and create the GetAllPostsFilter , in our domain objects, and then just register this with the auto mapper, ending up with the following map and endpoint code:

Everything is set up properly, with the last thing to change being userId => filter?.UserId .

Realistically, we should extract the if statement in it’ s own method, because it would get chaotic with multiple filters, and nobody could tell what our method is doing by just taking a glance. Extract that method and call it AddFiltersOnQuery
Tutorial: ASP.NET Core First Console Application
By: Alpesh Patel
Tags: Dotnet Core, Dotnet, Aspnetcore

Steps 1 ASP.NET Core — Environment Setup

To use ASP.NET Core in your application, the following must be installed in your system:

Microsoft Visual Studio 2019 Community (Download VS2019)

Step 2 New Project

Once you have installed the Visual Studio 2019, you can start building a new ASP.NET Core Console Application.

Open VS2019

On the start page, choose Create a new project.

On the Create a New Project dialog box, you will see the following different templates for Web projects. Now select the Console App (.NET Core) template with C#:

In the Configure your new project dialog, enter HelloWorldConsoleApp in the Project name box and select you location where it will save. Then choose Create.

Now, you can see your new project is created and opened.

Step 3 Run Project

Let us run this application, you can do that by pressing Ctrl+F5 or Click on Play button on top.

Reference Code: static void Main(string[] args) { Console.WriteLine(“Hello World!”); }

A console window opens with the text “Hello World!” printed on the screen and some Visual Studio debug information.

Press any key to close the console window.

Step 4 Enhance the application

Enhance the application to prompt the name which you entered and display it along with the date and time.

Console.WriteLine is use for output and Console.ReadLine is use for input. So let’s use both combination and Enhance our app.

In Program.cs replace the contents of the Main method, which is the line that calls Console.WriteLine, with the following code:

Reference Code: static void Main(string[] args) { Console.WriteLine(“Hello!”); Console.WriteLine(“

Who are you there?”); Console.WriteLine(“

waiting…for your good name.”); var name = Console.ReadLine(); var date = DateTime.Now; Console.WriteLine($”

Hello, {name}, on {date:d} at {date:t}!”); Console.Write(“

Press any key to exit…”); Console.ReadKey(true); }

Now, Again Run Application by pressing Ctrl+F5 or Click on Play button on top.

Respond to the prompt by entering a name and pressing the Enter key.

key. Press any key to close the console window.
Configuring Serilog in ASP.NET Core 2.2 web API
By: Matthew Bajorek
Tags: Webapi, Web Development, Programming, Serilog, Aspnetcore

For this post, we will be using .NET Core version 2.2’s web api.

Click here to learn how to create a new web API

Why use Serilog?

Serilog provides basic diagnostic logging for many sinks including, but not limited to, the console, files, Amazon, Azure, etc. This article will demonstrate the console and file sinks. It is easy as 1, 2, 3 to set up with appsetting configurations.

1. Install Serilog Packages

To install packages either run:

dotnet add package

Or in Visual Studio go to Project > Add Nuget Packages…

Serilog.AspNetCore — the main driver

Serilog.Settings.Configuration — the provider that reads the appsetting configurations

Serilog.Sinks.Async — an async wrapper for other sinks, especially the file sink, that reduces the overhead of logging calls by delegating work to a background thread

Serilog.Sinks.Console — the default sink and most suitable for development

Serilog.Sinks.File — a suitable sink for production

2. Configuration Files

Replace “Logging” with “Serilog” in appsettings.json as shown below:

The “Default” minimum level limits the logging of specify project code. This is different from the “Override” key that limits the ASP.NET Core framework’s log events.

The “Name” key specifies the sink desired. To write to multiple sinks, add another object to the “WriteTo” array.

Note that the async sink wraps subsequent sinks. Even though the async sink will not offer much performance gain to the console, it will allow you to brag to all your friends of your elite async coding skills.

When you are ready for the production settings, add the following appsetting.Production.json to the root directory of your project next to the other appsettings.

The “MinimumLevel” is being overwritten here since debug is not too useful in production.

How can I roll my logs you may ask?

Well since the Serilog.Sinks.RollingFile package has been deprecated, it is now handled by the Serilog.Sinks.File package, which we downloaded earlier.

This example shows a rolling interval of a day and keeping logs for the last 7 days.

The “retainedFileCountLimit” deletes old files older the interval count specified. The default is 31 intervals if left null.

Buffered set to true improves write performance by permitting the underlying stream to buffer writes.

3. Hook Serilog into the Web API

Add the lines 2, 10, and 11 to Program.cs:

And that is it! You can now log anywhere in your application by importing Serilog and using the available Log class functions just as the examples below show:

Click here for more possible Serilog configuration settings
Announcing Prise, a plugin framework for .NET Core
By: Maarten Merken
Tags: Plugins, Dotnet Core, Aspnetcore, Microservices

Prise logo

📣 Prise [/Prease/] is a versatile and highly customizable plugin framework for .NET Core applications, written in .NET Core.

For those who are wondering where the name Prise comes from, pries is a bastardized word in Flemish that means ‘the wall socket’: http://www.vlaamswoordenboek.be/definities/geschiedenis/378

Who do we need (another) plugin framework ?

Over the past years, I’ve worked in various environments where a plugin framework would have been beneficial to the overall structure of the software. For example. In the industry of Payroll, the calculation of net wages for employees can be horrid😱. Not only does the Belgian law makes this difficult, but also, the wage is calculated in four tiers. Wage, Brute, Taxable and Net.

Each tier has its own set of rules, that, depending on the context, produce a different result. In this kind of calculation, it is advised to separate these calculations out into small, testable components and inject them when needed, based on the context of the calculation.

Does this sound familiar to you? Then you might just benefit by using a plugin framework.

Another example would be a large desktop application that loads different UI components based on whatever permissions the user has. If a component can’t be loaded, the rest of the application could still continue to function as normal, until this component is fixed.

Again, we see that the loading of components is context-driven, the context being; the permissions of the user.

Calculation of car insurance and house insurance all depend on the context: the state of the house, the cost of the purchase, the income of the person requesting the insurance, and so on. When the context changes, different components need to come into play and change the outcome of the premium that needs to be payed.

If you’d write a traditional monolithic application, you’d be changing calculation rules on a weekly basis. Separating this out into components that you can hot-load and plugin on demand, is key to the maintainability and stability of the application.

If you’re writing an integration platform that interacts with data from different third party providers, you don’t want to highly couple these providers into your system. Each provider will have it’s own plugin that you load at runtime in order to connect to that provider when it is required, based on the context.

I believe, in this microservice world, a decent plugin system can help us keep focus on what really matters, writing good quality software.

With the footnote that you write tests for your plugins, obviously😁
Include XML Comments in Swagger under ASP.NET Core 2.2
By: Ali Benchaaban
Tags: Xml, Webapi, Microsoft, Aspnetcore, Swagger

The minimum configuration of Swagger is nice to get started but let’s add some more customization.

Before you start reading this article, we recommend to take a look to this article about building up swagger in asp.net core 2.2 Web API.

XML Documentation

First, enable the creation of XML documentation. In the Solution Explorer, right-click the Web API project and click Properties. Click the Build tab and navigate to Output. Make sure that the XML documentation file option is checked. You can leave the default file path.

Next, we need to make some changes to our Startup.cs file to tell swagger to use those comments.

Writing XML Comments

Back in our ValuesController, let’s write some XML comments for methods. Here’s what the sample project has:

Here’s the tags in use:

summary : A high-level summary of what the method/class/field is or does.

: A high-level summary of what the method/class/field is or does. remarks : Additional detail about the method/class/field.

: Additional detail about the method/class/field. param : A parameter to the method, and what it represents.

: A parameter to the method, and what it represents. returns: A description of what the method returns.

Once all of this in place, we are ready to run the project.

The source code for this tutorial is available on GitHub.

Did you catch something I did wrong, or can you make my implementation better? Let me know in the comments!

Happy Documenting!
The “alien 👽 engine” for real-time .NET & Blazor apps gets .NET Standard 2.0 / .NET Framework support
By: Alex Yakunin
Tags: Dotnet, Aspnetcore, Blazor, Aspnet, Dotnet Core

As you might guess, the “alien engine” is Fusion — I still struggle to find a perfect one-line description for it :)

Thanks to Dmitry Filippov (̶g̶i̶r̶l̶s̶, just look at this huge pull request!), Fusion got .NET Standard 2.0 / .NET Framework 4.7+ support. Crazy, but almost every test runs on .NET Framework as well now — even the ones that use Fusion’s distributed features! To make it happen, Dmitry added .NET Standard 2.0 support to every Fusion’s assembly except Stl.Fusion.Server , which had to be re-implemented as Stl.Fusion.Server.NetFx due to quite significant API difference between ASP.NET Core and regular ASP.NET.

The only missing piece is .NET Framework-compatible server-side controllers for IAuthService and ISandboxedKeyValueStore , i.e. some of built-in (but totally optional) Fusion services can’t be exposed on .NET Framework-based servers just yet, but the rest seem to work perfectly, and I guess this gap will be closed soon as well.

So if you’re still using .NET Framework, you might try to use Fusion as:

transparent in-memory cache, that’s always in sync with the ground truth

as a UI state management library on the client-side

and finally, you can use it to deliver real-time updates to every client connected to your servers.

Enjoy! The best place to ask questions: https://discord.gg/EKEwv6d

P.S. It also worth mentioning that this is the first really big external contribution to Fusion’s codebase. It’s hard to claim it’s “100% external” — I know Dmitry personally, as well as the company he works for, but this backporting effort was driven solely by their desire to use Fusion in a product that runs on .NET Framework, but relies on a huge set of real-time features. As you might guess, the hope to see such contributions was the main reasons to open-source Fusion. So if you like the library, but see something is missing there — your help is always welcome! And I’ll do whatever I can to help you too: Dmitry’s PR with 130+ files changes was reviewed and merged in less than 1 week.
Using WebApplicationFactory with NUnit
By: Daniel Edwards
Tags: Dotnet, Nunit, Aspnetcore, Testing, Integration

To start off, you’ll need to have a Web App created with a Startup. I imagine if you are reading this you have already created it (especially as it’s in every new starter template for Web Apps).

Next, create a Test project for NUnit. You can either do this through the GUI or through the dotnet cli

If you don’t have the templates, you may need to install them with the first command below.

dotnet new -i NUnit3.DotNetNew.Template dotnet new nunit --framework netcoreapp2.2

Now you will need to install some NuGet Packages in that project.

Microsoft.AspNetCore.App Microsoft.AspNetCore.Mvc.Testing

Finally, edit the .csproj file removing the Version tag from the Microsoft.AspNetCore.App package reference and change the Sdk property of the root to Microsoft.NET.Sdk.Web

It should look something like the following

With your new test project now set up, create a file for that will inherit from WebApplicationFactory. In this example, I’m going to assume it’s an API of some sort.

Finally, you can write your test. Now there are a few ways of going about this.

You can write a SetUpFixture which creates your application once and is used throughout all the tests Each set of tests can have a OneTimeSetUp which do the same thing A mix of the two!

For this scenario I’m just going to demonstrate the second but if you’re familiar with NUnit it should be very easy to adapt.

The key parts here being in the set up and tear down.

In the OneTimeSetUp you create a new factory and then an HttpClient from that. In the OneTimeTearDown remember to dispose.

That’s all there is to it, happy testing!
We were platinum sponsor of Techorama 2019!
By: Alper Ebiçoğlu
Tags: Conference, Csharp, Aspnetcore, Framework, Events

Last week we were in the Netherlands to participate in Techorama 2019 Conference. Techorama is an international software development conference which takes place in Ede. It was a quite big organization with over 30 partners and over 1000 attendees. The venue was a cinema and whole venue was closed for this event. Volosoft is proud to be a Platinum Partner of Techorama.

It started on Tuesday, October 1 and continued with the next day. So 2 full days from 07:30 to 18:00 and 10 parallel sessions. There were many different topics like AI & IOT & ML, Cloud Services, Data Platform and BI, Developer trends, Dev-Ops and Architecture, Motivational and self-improvement, Back-end and Front-end technologies…

There were 90 speakers from different parts of the world like Mads Torgersen, Scott Allen, Dan Wahlin, Jimmy Bogard, Pinal Dave, Richard Campbell and also our lead architect Halil Ibrahim Kalkan had a session about “Implementing Domain Driven Design”. The room was full and even some visitors were standing on the walls to listen to Halil’s talk. It was really great to see this high of reaction.

We were the only company who was there for an open-source product. ABP.IO is our new approach to a micro-service compatible & multi tenancy enabled solution. It has numerous of cool features to start a new project rather than a scratch ASP.NET Core project. We had a lot of people visiting our booth, people were all interested in this open-source ASP.NET Core 3.0 compatible web application framework!

We brought lots of cool swags to the Netherlands. Nice colorful Bluetooth speakers, hand-made chocolates. As always, we had some great fun during the drawing of our Play Station 4 raffle. Besides we made a present of ASP.NET Zero Ultimate License which costs like $4499.

Check out Techorama Netherlands 2019 by pictures:
Versioning a .NET Core 2.2 application
By: Dominic Burford
Tags: Dotnet, Version Control, Aspnetcore, Aspnet, Dotnet Core

Following on from an earlier article[^] I wrote about versioning a .NET Core 2.0 application, I have now had to revise this since the method I used for that version of the application is not supported in .NET Core 2.2. In that article, I demonstrated how to use a tool called setversion[^] for versioning a .NET Core 2.0 application. After upgrading our application to .NET Core 2.2 I found out that this is not currently supported any more.

Instead of using the setversion tool, I am using the dotnet publish command-line utility. When using this command-line utility, you are able to specify a version number.

I am still using the same build script as described in my previous article, and this is invoked from our TFS build server in the same manner. Just to reiterate, within TFS you have the ability to pass arguments to your Windows batch files. I am passing the build version number $(Build.BuildNumber) as the argument.

I then invoke my Windows batch file (called setversion.bat)

Hide Copy Code

@echo off

cls ECHO Setting version number to %1 cd <projectFolder>

dotnet restore

dotnet publish <project>.csproj --configuration Release /p:Version=%1

This all works perfectly, and the deployed application assemblies are stamped with the correct version number.