My articles about C#

How to create a Nuget Package of your .NET code and host it in a private Azure DevOps Feed

In this tutorial we are going to see how to set up your .NET code as a Nuget Package and host this package on an private Azure DevOps Feed. You can then use the Package on other .NET projects.

Read the complete article

How to map a property of a parent object to a property inside a list of objects with AutoMapper

Mapping objects with AutoMapper can save you a lot of time and repeated code. However, some mappings are more tricky than others. Consider the example where we want to map two lists of objects and moreover, a specific property of each of these list-objects should contain the value of a property from a parent object.

Let us see this scenario with a concrete example:

Read the complete article

Map one C# Record to another with AutoMapper

Records were introduced in C# 9.0 and are a handy way of holding data, instead of using properties of classes. I recently came along the task of mapping one record of one type to one of another type by using AutoMapper. At first I thought I will map them exactly as I would map the properties of two different classes. However, it was trickier than that :)

Read the complete article

Parse your XML with XPATH and find a value of an element based on the value of another element

When parsing and reading XML files in your C# code, you can use the XDocument or XElement objects to access it with LINQ and the Descendants or Elements properties. However, there is another option; you can use XPATH for traversing the XML. In this example we are going to see how you access a value of an XML-element, by matching the value of another element with a value given from the user.

Read the complete article

How to create an empty or with one element IReadOnlyCollection for your unit-tests

When using the Moq framework for mocking your C# classes, you will have do define what dummy value or values a method of the mocked classes returns. For that we use the Setup method and in the Returns method we define the returned value. The question now is, which dummy value to return when your methods return a IReadOnlyCollection collection.

Read the complete article

How to pass parameters to an AutoMapper Profile constructor aka Dependency Injection for AutoMapper

While using AutoMapper for mapping different objects in your application, you might come into a situation where you need business logic from other services while you are mapping. For that we will have to inject these services into our Profile class.

Read the complete article

How to fix the "Unable to find assembly Microsoft.VisualStudio.QualityTools.LoadTest ..." error when running your unit-tests

For an older MVC project I wrote unit-tests with the MSTest framework. Visual Studio requires a .testsettings file in your project, which contains the configuration for the unit-tests.

When running or debugging unit-tests there might be the case that the “Unable to find assembly Microsoft.VisualStudio.QualityTools.LoadTest …” error is logged and the test is getting skipped. In order to correct this issue you have to check inside the .testsettings file for the WebTestRunConfiguration section.

Read the complete article

How to define and use Application Settings in your Azure Functions

As it is stated in the Azure Portal Application settings are encrypted at rest and transmitted over an encrypted channel. You can choose to display them in plain text in your browser by using the controls below. Application Settings are exposed as environment variables for access by your application at runtime.

Storing sensitive data as application settings is preferred over having them in plain text in your code. In this article we are going to see how to define them in your Azure Portal, how to integrate them in your Function-code and how to give them values when you are debugging your Functions locally.

Read the complete article

How to register and inject multiple implementations of one interface in .NET

There are times when you want to register multiple classes which all implement a common interface. One example could be a IValidationRule interface which is implemented by different validation rules, lets say NameNotEmptyValidationRule and the NameRangeValidationRule. We want these rules to run in order and validate user input. Let’s see this example in form of code:

Read the complete article

How to migrate your code for uploading files from .NET Framework to .NET Core

I recently had to migrate code, for uploading Excel, files from an older .NET Framework application to a new one which is based on .NET Core. I would like to share my learnings with you in a “before and after” form.

Read the complete article

Use the JsonConverter attribute to parse complex JSON object into a C# class

I was working lately with some complex JSON objects coming from the alphavantage, an API for getting meta information about stocks, currencies and the world economy in general, and had to overcome major issues before being able to deserialize the strings into my C# POCO classes.

Read the complete article

The reason behind the "Cannot implicitly convert type System.Threading.Tasks.Task to XXX"

A quick article this time about an error message in C# when dealing with asynchronous code calls.

Read the complete article

Why is my HiddenFor property having an empty value in the MVC4 view

When dealing with ASP.NET MVC you might use hidden fields to pass values of model properties from the view to an action of a controller. So you will find yourself writing something like that in your view:

Read the complete article

How to prevent Model Binding of UI properties to the MVC Model in your .NET Core application

We are dealing here with a security risk for your .NET Core application. Suppose you are having the following MVC model in your .NET application and the user can edit in a UI-form her Firstname and Lastname. The property Age cannot be edited on the form. The business logic tells us that it will be filled later. However, the user, with the help of simple tools such as Postman or Google console debugger can edit the Age property. Let us see how we can block such actions.

Read the complete article

How to copy data-files to the TestResults folder of your MSTest unit-tests

When running unit-tets you will often want to read data from .txt or .xml files. On the runtime, these files have to be copied to the TestResults folder. By choosing Copy to Output Directory: Copy always or Build Action: embedded Resource for these files will not help and the file is not found when the unit-test runs.

Read the complete article

Enable warnings about possible null references in your Visual Studio project

All .NET programmers had dealt at least once on their career with a null reference exception on a code line they wrote. Most of the times a parameter of a method is null, the code is not aware of it and the parameter is being used inside the method, for example we are accessing a property of an object. Because the value of the object is null we are getting an exception on the runtime.

Visual Studio provides a way to inform / warn us about possible null references. Let us see how we can enable this feature on our C# project.

Read the complete article

The implicit operator in C# and when it can be useful

A cool feature of C# that I lately used is the implicit operator keywords and with them we can define the way for converting one type into another one implicitly. A good scenario when you can use that is presented in this example.

Read the complete article

A list of my favorite C# examples using Reflection

This article contains a list of code lines, that use reflection to access data in classes. Reflection can be combined with Generics and even though some might think it can be hacky, I find that Reflection offers a tremendous advantage when dealing with monolithic application and you want to write reusable code, and you can not use object oriented concepts such as inheritance. Let’s start without further delay.

Read the complete article

How to update your Azure Functions from version 2 (V2) to version 3 (V3)

Here is a small and quick article about how to perform the update in your C# project that contains the Azure Functions of your application

Read the complete article

How to fix the When passing parameters by position, each parameter can only be referenced once Dapper error

I lately had to write some queries using Dapper which use a date, defined from the user, and check this date against two other from-to dates. In other words the query tries to find if a given date is inside the range of two other dates. When I tried to use the same date-parameter to Dapper, I was getting the following exception: When passing parameters by position, each parameter can only be referenced once.

Read the complete article

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-conditions. For example using this Gender gender = Gender.Female instead of this string gender = "Female" is much cleaner and you get a single point of change in the Enum. However, since you might dealing with legacy code, you will have to cast the strings or integers 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