Articles about C#

Azure DevOps - Get the capacity of your team in the current sprint programmatically

Microsoft Azure DevOps provides a solid way of tracking your team-progress while using the scrum principles.

Nuget Packages with WebApi Clients are provided for accessing your team information via code. For example you can access the queries of your team, the work items of your backlog and much more!

In this article we will focus on getting the capacity of the current sprint for each member of your team. This is the code snippet that does our job:

Read the complete article

The Reference vs. Value Types with an easy to understand example

In this article I would like to use a simple example for presenting you the difference between a Reference and a Value Type. Such an example shows us how careful we have to be when dealing with properties of different types. Consider the following class and list in C#:

Read the complete article

The complete guide to cast different types to and from enums in .NET Core

Enumerations are a great way to standardize your code and move away from using string literals or integers for if-comparisons in your code. For example using this Gender gender = Gender.Female instead of this string gender = Female is much cleaner and one change in the Enum affects the whole application. However, since you might dealing with legacy code, you will have to cast the strings or ints to your Enumerations when connecting new with old code. Lets see how this is done.

Read the complete article

How to validate your .NET Core WebAPI model and return a 400 (BadRequest) response from your controller and test it with Moq

I know, this is not a new question, however, if you search online you will mostly find articles writing about the older .NET Framework. Here is my way of dealing with 400 (BadRequest) and 404 (NotFound) errors with the latest .NET Core 3.0 WebAPI methods.

Read the complete article

How to disable a Nuget Feed in a .NET project

Most of us use private Feeds in Nuget for storing our Nuget Packages. However, since some projects might have other security restrictions that others, it is possible that we want to disable some Feeds in our project, so that we do not have them as references.

To do this “black-listing” of Feeds you can use the following configuration:

Read the complete article

See the details of every Exception thrown when debugging in Visual Studio

When debugging your .NET application with Visual Studio, you will come along Framework- or Application-Exceptions. In specific cases you see the line where the Exception was thrown (line 132 in the following screenshot) but you cannot see the content (message, stacktrace, etc.) of the Exception. To find this information simple type the following in the watch list area of Visual Studio:

Read the complete article

How to use Postman when testing .NET Core WebAPI actions with FromBody and FromForm attributes

Postman requires no introductions and plenty of resources about this tool can be found online. However, while testing I recently noticed, that the binding of JSON objects to C# primitive types or POCO classes is not documented in detail.

We are going to see different scenarios of binding while we test against a .NET WebAPI and try to answer the question “why my action is not getting called when everything is set up in Postman?”.

Read the complete article

Deserialize a JSON string into a C# object and set custom values into a property of that object

This week I had to deserialize a JSON string into a collection of C# objects. The class of these objects contained not only the properties that map directly to the JSON properties but also an extra property which I wanted to fill with values based on the values of other properties of the object.

Let us consider the following simple POCO class and its container, which is a simple array of Students:

Read the complete article

How to use the fileinputname parameter inside your template items in Visual Studio

A Visual Studio Item Template allows us to generate new files with code, so that we avoid having to manually create them. This automatization is very practical when we need to create similar classes more than one time. A template is being offered as option in the “Add new item” dialog of Visual Studio:

Add new item dialog in visual studio

Read the complete article

How to skip the mapping between properties of a source and a target object in AutoMapper

As I did in my previous article, I focus again on the AutoMapper framework.

When I map one object to another, I often deal with a destination object that contains LESS properties than the source object. If I take no action, an exception is going to be thrown. For that we will have to declare the skipped properties by using the DoNotValidate method when we define the mapping (CreateMap) between the two objects:

Read the complete article

Use a custom function when mapping one property to another with Automapper

Automapper is a handful tool for mapping the properties of two different type objects together. Such mappings are very common when you are dealing with a multi-tier architecture in your program. For example you want to map the entity object, which contains data from the database, with the UI-model object of your WebApi action.

For basic mapping examples refer to the Automapper documentation. In this article we will consider the following advanced example:

  • Your entity model contains a property with a non-serialized string that you store in a table of your database

  • Based on some condition checking, you want to or do not want to deserialize this string and store it into a property of different type of your UI-model object

For that you need a mapping between two properties of different type and also a function that runs every time to do this transformation:

Read the complete article

Clone a Git repository from Azure DevOps to your local machine by using the command line

In order to download and use a remote repository, which is stored in Azure DevOps, do the following two steps and you are good to go.

Read the complete article

A possible reason for the .NET MVC "The view XXXX or its master was not found" error

“The view XXXX or its master was not found” error looks like that:

"The view 'XXXX' or its master was not found or no view engine supports the searched locations. 
The following locations were searched:

and I recently had to deal with it, although I was 100% sure that my view was in the right place inside my MVC project.

Read the complete article

Run your Load Tests against multiple server environments, like localhost, development or integration

Load Tests help us identify bottlenecks in our application and can answer with high precision how many users our infrastructure can support in a given time. In a previous article I gave you some tips for using the Load Tests from Visual Studio in a more efficient way.

Today I would like to show you how you can run the same load tests against different server environments, for example on your localhost machine and on the integration server, before deploying a change into the production.

Read the complete article

How to find the connection string of your LocalDB database in Visual Studio

Today while I was developing a .NET Core example for testing Dapper against my LocalDB tables, I had to define the connection string so that I can run queries in my code against the database. If I was to use Entity Framework, then the connection string would be scaffolded for me, but now I have to find it on my own.

Read the complete article

6 tips and tricks for better unit-testing while using the Moq framework

Moq is probably the most known framework for mocking functionality which is then used in your unit-tests. In this article you can find some of my notes about Moq that I wanted to share with you.

Read the complete article

Create a real-life example (Function, Service Bus Queue, Storage Table) of an Azure Logic App. A step to step example.

Some time ago I wrote an article with an example of an Azure Function which I used in my applications. With the current article I want to present you another real-life example of using different Azure Services and combining them together in a Logic App.

A Logic App represents a workflow of steps that are defined to be done in a sequential or in a parallel manner.

Our scenario contains a company which owns an eshop. We are going to build a workflow for getting customer orders, pushing them into a queue for almost-real-time process (A queue is a good way to balance load of large number of requests in your servers), retrieving them back, storing them in a storage table and informing the user about her order with an email. The most important thing, we are going to develop all the steps inside the Azure Portal; the use of Visual Studio is optional.

After we finish with the creation of our Logic App, we are going to have the following workflow:

Read the complete article

The reason behind the identifier could not be resolved error in your CosmosDB queries

When writing SQL queries to test them against your CosmosDB collections, chances are that your deal with the following error message:

Identifier XXX could not be resolved.

where XXX is the name of a property inside your collection. You could have for example the following query:

SELECT * FROM students WHERE firstname = 'Christos'

The reason for the error is that you forgot something in your query.

Read the complete article

Manage configuration in your .NET Core web projects by using the IOptions interface

Every application out there needs to read some configuration written from the programmers in order to perform critical tasks and function correctly. Examples of configuration can be the connection string to your SQL database or a boolean flag which decides if a feature will be available to your customers or not.

.NET Core gives us a way to store our configuration in a json file and access its properties programmatically.

This way of coding gives us the advantage of not having to redeploy our application, every time we update a value in our configuration (in our case the json file). We simply have to recycle the application pool that hosts our application and we are set.

Read the complete article

How to solve the "project.assets.json not found. Run a NuGet package restore to generate this file" problem in .NET Core applications when using MSBuild

While I was developing a .NET Core web application and wanted to automate the build process in VSTS, I got the following error, when I was triggering the build:

Error: Assets file ...\project.assets.json not found. Run a NuGet package restore to generate this file. Process 'msbuild.exe' exited with code 1.

The issue here is that needed .NET Core files are missing, when we start build our application. I solved this problem by defined an extra initial step in my build process.

Read the complete article

Write a custom .NET attribute to mark searchable columns of a HTML table and match them with their equivalent DB columns

Consider you have to implement the following requirement:

  • We have a MVC .NET web application and a view with a HTML table and multiple columns. We want to mark some of these columns as searchable, so that we can search their values when we use the search field.

  • We host our data in a relational database, we get the structure of the DB table as it is. We use Entity Framework and we need to “map” the DB columns to their equivalent UI columns, so that the search works correctly.

Here a simple mockup of our UI:

Read the complete article

The It.Is and It.IsAny methods of the Moq unit-testing framework and why your "partial mocking" might do not work

Unit-testing of existing code can sometimes be a challenge, since you have to deal with classes that contain too much of functionality. In that case the “Single Responsibility” principle was not in focus, however, refactoring the code can be an issue, so you will have to unit-test the class as it is. Apart from that we do not want to “mock” the Interface of a class, which would mock all its method, but the class it self.

Such classes are calling methods of the same class, so the task is to mock only few of the methods, but not all of them, since we also want to unit-test some of them. The feature of partially mocking the methods of a class is called partial mocking. The methods that we want to mock, have to be defined as virtual, so that Moq can ovveride them. This feature can be a sign of code smell, when overused.

There are some great examples in StackOverflow on how to achieve that, however, in this article I would like to focus on an issue that caused my partial mocks not to work and show you how I fixed it.

Read the complete article

Define a custom HTML prefix for your .NET MVC models

There might be the case when you develop with .NET MVC, that you have to render a complex view which contains a hierarchy of partial views.

In such times you might want to render more than one instances of a ViewModel inside the view or you just want to use different ViewModels, like one from your framework and one from your partial view, that have the same name.

In order to avoid collisions of names of the properties between the models, you can use the HTMLFieldPrefix property which adds a prefix to the CSS id and name attributes.

Let us consider the ViewModel class in the following example:

Read the complete article

A very possible reason as to why your ASP.NET MVC ViewModel's IEnumerable Validate method is not firing

If you are dealing with an ASP.NET MVC project chances are that your ViewModels or POCO classes are implementing the Validate method of the IValidatableObject interface to validate on the server side the incoming data from the UI of your application. Chances are also that you are decorating the properties of these classes with validation attributes like [Required].

As stated here when you use both validation attributes and the Validate method, the property attributes are going to be applied first, if they pass the object attributes are checked and if they also pass the Validate method of the current class will run and validate the input.

However, what happens when you use no attributes in the property or object level and you only implement the Validate method? Why is the method not firing?

Read the complete article

How to fix the 'Could not load file or assembly Newtonsoft.Json, Version=' error when creating a REST API Client for Azure in Visual Studio

The last few days I have been experimenting with the different types of App Services that the Azure platform provides. One very interesting combination of app services is a ASP.NET MVC client (Azure Web app) or a WebAPI (Azure API app) which acts as the middleware between a JavaScript client and an internal “business” WebAPI (Azure API app). The architecture looks like this:

Read the complete article

A real world Azure Function example that logs client errors in a Storage Table

Today I invested some time into getting deeper to the topic of Azure Functions. Together with the new microservices architecture, new ways of doing business logic arise. Azure Functions are small chunks of code that run in a “serverless” (you do not care about allocating new hardware resources, even when the requests to the function raise) environment and each of them is meant to do one specific job.

Apart from the great examples and templates with Functions that you can find inside the Azure Portal, I tried to think of some use cases that I would use an Azure Function for a web application and I came up with the following one:

Read the complete article

Store .NET objects inside an Azure Table Storage and then retrieve them back in their original type

Non-relational databases are becoming more and more popular as a solution for storing your data. Cloud solutions like Microsoft Azure also get more popular with every day.

Currently Azure supports two types of “NoSQL” databases in the Azure portal. The one is DocumentDB (the NoSQL option in the main menu of the portal) and the other is the Table Storage (from the Storage accounts option in main menu). Do not confuse this Table with the tables of a relational database, they are not the same! A detailed analysis of the differences and similarities of the two technologies is beyond the purpose of this article, but we can summarize them to the following points:

Read the complete article

The subscription is not registered for the resource type components in the location Central US error when creating a new Azure Web App in Visual Studio

With the Azure cloud solution from Microsoft we can create a new web application with Visual Studio, deploy it as a Azure Web App and “go live” in only few minutes.

I recently was faced with the “The subscription is not registered for the resource type ‘components’ in the location ‘Central US’” error when I was trying to publish my new web application to a Website (or a Web App) in Azure. Either starting from scratch with a web project and doing the mapping or by using the Publish option of an already created project, I was getting the same error. Visual Studio tried to publish the application to Windows Azure with no success.

Read the complete article

How to create a .gitignore file for Visual Studio projects in Mac

If you want to store your source code in a repository that uses Git, you often have to create a .gitignore file which contains a black list of files that should not be committed to the repository. If now you are using Visual Studio for your projects the need for such a file is even bigger since this IDE creates a number of files (.exe, build, bin folders, etc.) that are only needed on your local machine.

With the release of Visual Studio for Mac we need to create a .gitignore file for our Visual Studio projects by using our Mac.

Read the complete article

The System.BadImageFormatException error when unit-testing in Visual Studio and its solution

The BadImageFormatException was unhandled – An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) exception is being thrown when you try to load a .dll of your application which was compiled with 32 bits (X86) or 64 bits (X64) and the process that runs this file runs in a different bit-environment than the file.

If you see this exception when you run your C# unit tests in Visual Studio, then the reason for this error is that the test environment of Visual Studio has a different bit setting than the compiled code which is under test. To fix that you have to do the following change in your Visual Studio test settings:

Read the complete article

Six practical features of C# 6.0 to use in your everyday coding

With this article I would like to present you six useful features of the 6.0 version of C#.

null conditional operator

Removes the need for checking for null values and thus we avoid the tedious if(... != null && ... != null ...) if conditions.

  if (myDog?.Mouth?.TeethsInMouth[0]?.ScientificName == "default tooth name") ...
Read the complete article