Tag Archives: C#

Element does not match nay field or property of Class – MongoDb and .net core

Hey everyone,

I ran into the following error today while searching MongoDb for an object:

Element ‘Tags’ does not match any field or property of class X.

The issue was that there were extra fields on the returned document that were not specified on the mapping target object. A bit of Googling revealed that there is a provided attribute that allows you to ignore all extra fields.

Simply add [BsonIgnoreExtraElements] to any relevant model definitions.

Thanks to this stackoverflow post for the lead: https://stackoverflow.com/a/23448987/522859

OpenXml Validation Spreadsheet Value Between Two Numbers – C#

Hi everyone,

Just a quick post on how to validate a numeric cell to ensure that the value is between two numbers when using OpenXml:

// Restrict min and max values
var dataValidations = new DocumentFormat.OpenXml.Spreadsheet.DataValidations { Count = 0 };
DocumentFormat.OpenXml.Spreadsheet.DataValidation dataValidation;
dataValidation = new DocumentFormat.OpenXml.Spreadsheet.DataValidation {
Type = DataValidationValues.Decimal,
AllowBlank = false,
SequenceOfReferences = new ListValue() { InnerText = $”{columnName}2:{columnName}1048576″ },
Operator = DataValidationOperatorValues.Between,
Formula1 = new Formula1 { Text = “10 “},
Formula2 = new Formula2 { Text = “20 “},
};
dataValidations.Append(dataValidation);
dataValidations.Count++;
worksheetPart.Worksheet.Append(dataValidations);

The snippet above will ensure that any values are between 10 and 20. I didn’t come across any examples for this while searching, so hopefully this will be able to help someone else out!

Thanks,
Chris

Docker – Severity Code Description Project File Line Suppression State Error DT1001 Service service has neither an image nor a build context specified. At least one must be provided. docker-compose C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Sdks\Microsoft.Docker.Sdk\build\Microsoft.VisualStudio.Docker.Compose.targets 204

Hi everyone,

I ran into the following error while using docker compose and visual studio:

Severity Code Description Project File Line Suppression State
Error DT1001 Service has neither an image nor a build context specified. At least one must be provided. docker-compose C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Sdks\Microsoft.Docker.Sdk\build\Microsoft.VisualStudio.Docker.Compose.targets 204

It took a bit of poking around to find as the error seemed a bit ambiguous, but luckily this turned out to be a simple mistake on my part. I’d renamed my service from “servicename” to “service_name” in docker-compose.yml. Unfortunately, I hadn’t noticed the visual studio had automatically added an entry to docker-compose.override.yml. Because I hadn’t updated this entry it couldn’t find an image for the non-existent service.

A simple error on my part, but hopefully it’s able to save you a bit of time!

Cheers,
Chris

Automapper protobuf datetime to timestamp c#

Hi everyone,

I ran into the following error tonight while attempting to use automapper to map a datetime field to a protobuf timestamp property:

automapper missing type map “DateTime -> Timestamp”

To fix it, add the following to your mapping profile:

CreateMap().ConvertUsing(x => x.ToTimestamp());

UPDATE:
I later hit a similar error parsing a different entity:

Type Map configuration:
Entity-> EntityDto
EntityService.Models.Entity-> EntityService.EntityDto

Destination Member:
CreatedAt

—> System.ArgumentException: Conversion from DateTime to Timestamp requires the DateTime kind to be Utc (Parameter ‘dateTime’)

Implementing the following map appears to have resolved it:

CreateMap().ConvertUsing(x => Timestamp.FromDateTime(DateTime.SpecifyKind(x, DateTimeKind.Utc)));

If you’re planning to go the other way (timestamp -> datetime) you may also need the following:

CreateMap().ConvertUsing(x => x.ToDateTime());

I’m currently using the following base class in my library:

public class BaseMappingProfile : Profile
{
public BaseMappingProfile()
{
CreateMap().ConvertUsing(x => Timestamp.FromDateTime(DateTime.SpecifyKind(x, DateTimeKind.Utc)));
CreateMap().ConvertUsing(x => x.ToDateTime());
}
}

Google didn’t seem to turn up a lot so I thought I’d post it here in case it helps someone out!

‘DatabaseFacade’ does not contain a definition for ‘Migrate’ and no accessible extension method ‘Migrate’… – eShopOnContainers

Hi everyone,

I’ve been going through Microsoft’s eShopOnContainers repo and replicating it as a small test project to learn microservices. While adding the WebHost Customization project I ran into the following error: 

Severity Code Description Project File Line Suppression State
Error CS1061 ‘DatabaseFacade’ does not contain a definition for ‘Migrate’ and no accessible extension method ‘Migrate’ accepting a first argument of type ‘DatabaseFacade’ could be found (are you missing a using directive or an assembly reference?) WebHost.Customization … N/A

This turned out to be a fairly simple fix. All that’s required is the following package (I installed via Nuget):

Microsoft.EntityFrameworkCore.SqlServer

Thanks to the following stackoverflow post for the info: https://stackoverflow.com/a/57606203/522859

‘add-migration’ is not recognized as the name of a cmdlet – .net core 3.0

Hey everyone,

I recently upgraded my .net core 2.2 project to .net core 3.0. When trying to add a migration I hit the following error:

add-migration : The term ‘add-migration’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:1
+ add-migration events
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (add-migration:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

It turns out that there have been a few changes to how this all works. You’ll need to go to package manager console and run the following:

1) Install-Package Microsoft.EntityFrameworkCore.Tools
2) Update-Package Microsoft.EntityFrameworkCore.Tools
3) Get-Help about_EntityFrameworkCore

After running step three you should get something that looks like the following:

PM> Get-Help about_EntityFrameworkCore
ef-core

Covered in full here: https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell

View Raw SQL in EF Core – Simple Option

Hi everyone,

I’ve been looking for a simple way of viewing the raw output of sql in my local environment without having to make code changes and came across the following config setup:

{
“Logging”: {
“LogLevel”: {
“Default”: “Debug”,
“System”: “Information”,
“Microsoft”: “Information”
}
}

This will show the sql statements in your output window without requiring any additional code:
sql-output

Thanks to this stackoverflow post for the answer: https://stackoverflow.com/a/54704006/522859

Unable to Migrate after Adding Config to Startup

Hi everyone,

Just a quick post on fixing up a migration error after I added new config to startup.cs via DI. The error after running add-migration was pretty unintuitive:

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

To find out a bit more I ran the following:

add-migration -verbose

This revealed the fact that there was an issue with adding my config line. The error stated that I had to have an empty constructor which led me on a bit of a wild goose chase.

The solution was simply a missed entry in application.json. In my case it was an omitted “assembly” section. Having said that, I did come across a few instances where people had the same problem when omitting commas etc.

Hopefully that’s able to get you on the right track!

Thanks,
Chris

Dynamic Robots.txt with Web Api 2

Hi everyone,

For a project I’m currently working on I needed a dynamic robots.txt. Because our test environment is public facing we want to keep it from being indexed by Google etc. It took a bit of Googling to find a solution that worked, but in the end it was actually pretty simple.

Here’s the action in one of the API Controllers:

    public class UtilitiesController : CustomBaseApiController
    {
        [Route("Robots.txt")]
        [HttpGet]
        public HttpResponseMessage GetRobotsFile()
        {
            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            var stringBuilder = new StringBuilder();

            if (Helpers.IsProduction())
            {
                // Allow bots in production
                stringBuilder.AppendLine("user-agent: *");
                stringBuilder.AppendLine("disallow: ");
            }
            else
            {
                // Don't allow bots in non-production environments
                stringBuilder.AppendLine("user-agent: *");
                stringBuilder.AppendLine("disallow: *");
            }

            resp.Content = new StringContent(stringBuilder.ToString());

            return resp;
        }
    }

Also need to add the following to your web.config so that the robots.txt file can processed by the routing handler. Without this IIS will attempt to serve it as a static file and will return a 404 when it’s not found:


    
    
        
        
        
    
    

In production you’ll end up with the following:

user-agent: *
disallow:

And any other environments:

user-agent: *
disallow: *

Thanks to these answers on stackoverflow for the info:
https://stackoverflow.com/a/52270877/522859
https://stackoverflow.com/a/17037935/522859

Error Number:8152,State:10,Class:16 String or binary data would be truncated. The statement has been terminated. – Entity Framework

Hi everyone,

I ran into the following error after adding model validation attributes to a database with existing values:

Error Number:8152,State:10,Class:16
String or binary data would be truncated.
The statement has been terminated.

The solution is pretty straightforward if you’re happy to truncate the values. Simply run the query below, swapping Title for your column name, Products for your table name and 25 for your new column length:

UPDATE Products
SET Title = LEFT(Title, 25)
WHERE LEN(Title) > 25

You should then be able to run update-database without any issues:

PM> update-database
Specify the ‘-Verbose’ flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201806240741543_product_validation].
Applying explicit migration: 201806240741543_product_validation.
Running Seed method.
PM>

Thanks to David in for his answer on Stackoverflow: https://stackoverflow.com/a/24931522/522859