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.
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.
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.
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.
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.
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:
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.
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:
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.
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.
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#:
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 ints to your Enumerations when connecting new with old code. Lets see how this is done.
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.
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:
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:
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?”.
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:
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:
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:
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:
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.
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.
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.
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:
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.
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.
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.
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:
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?
How to fix the 'Could not load file or assembly Newtonsoft.Json, Version=220.127.116.11...' error when creating a REST API Client for Azure in Visual Studio
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:
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:
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.
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.
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: