Category Archives: Web Development

Breaking the Internet

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

Advertisements

Geography: one of the identified items was in an invalid format – Entity Framework

Hey everyone,

I’m currently working on a prototype using .net core, sql server, ef and NetTopologySuite to handle locations. While trying to save a location I ran into the following error:

Geography: one of the identified items was in an invalid format

My code was as follows:

using GeoAPI.Geometries;
using NetTopologySuite;
using NetTopologySuite.Geometries;

...
var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
...
Location = geometryFactory.CreatePoint(new Coordinate(request.Lat, request.Lng))
...

The solution ended up being pretty straight-forward. Simply swap the latitude and longitude values when creating a coordinate:

Location = geometryFactory.CreatePoint(new Coordinate(request.Lat, request.Lng))

// Use this instead
Location = geometryFactory.CreatePoint(new Coordinate(request.Lng, request.Lat))

This is mentioned pretty clearly when reading the documents but I somehow skipped over it. Hopefully this will be able to help out anyone else who does the same thing!

Official docs: https://docs.microsoft.com/sv-se/ef/core/modeling/spatial

Simple React-Leaflet Location Picker Setup

Hi everyone,

Just thought I’d share a very simple react-leaflet setup in case it’s able to help anyone.

screencast-localhost_3889-2019.08.24-14_01_41.gif

Add the css and javascript for leaflet to public > index.html:

  
https://unpkg.com/leaflet@1.5.1/dist/leaflet.js">https://unpkg.com/leaflet@1.5.1/dist/leaflet.js

Install react-leaflet via npm or yarn, also add the dependencies:

npm install react-leaflet # npm
npm install leaflet react react-dom # npm

yarn add react-leaflet # Yarn
yarn add leaflet react react-dom # Yarn

Create the map component:

import React, { useState } from 'react'
import { Map, TileLayer, Marker, Popup } from 'react-leaflet'


const MapSimple = () => {

    const [location, setLocation] = useState({
        lat: 51.505,
        lng: -0.09,
        zoom: 13,
    });
    const position = [location.lat, location.lng];
    
    const setMarkerPosition = e => {
        setLocation({ ...e.latlng, zoom: 19 });
        console.log(`My location is: ${JSON.stringify(e.latlng, null, 3)}`)
    };

    return (
        
            <TileLayer
                attribution='© OpenStreetMap contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            
                
                   A sample popup.
                
            
        
    )
}

export default MapSimple;

Request Denied – react-geocode

Hi everyone,

I’m currently testing react-geocode but hit a “request denied” error after providing my API key.

Error: Server returned status code REQUEST_DENIED

The solution was pretty simple thankfully – enable the Geocoding API for your project: https://developers.google.com/maps/documentation/geocoding/get-api-key

In my case I was re-using a Google maps key from another project where I’d enabled all of the map apis but not the GeoCoding one.

Module not found: Can’t resolve ‘leaflet’ in – react-leaflet error

Hey everyone,

I ran into the following error after installing react-leaflet and attempting to run an example:

Module not found: Can’t resolve ‘leaflet’ in ‘…\node_modules\react-leaflet\es’

It turned out I’d simply rushed things and skipped the second step in the documentation:

npm install leaflet react react-dom # npm
yarn add leaflet react react-dom # Yarn

Doco: https://react-leaflet.js.org/docs/en/installation.html

NetTopologySuite Circular Reference with .net core 2.2

Hey everyone,

Testing out a spatial project with .net core and I ran into the following error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : The best overloaded method match for ‘Xunit.Assert.Equal(string, string)’ has some invalid arguments

at CallSite.Target(Closure , CallSite , Type , Nullable`1 , Object )
at UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at DiscussionsControllerIntegrationTests.CreateTestDiscussion(HttpClient client, ApplicationDbContext db, DiscussionCreateWebRequest payload) in DiscussionsControllerIntegrationTests.cs line: 56
at DiscussionsControllerIntegrationTests.b__1_0(ApplicationDbContext db) in DiscussionsControllerIntegrationTests.cs line: 27
at IntegrationTestBase.RunTest(Func`2 testToExecute) in IntegrationTestBase.cs line: 54
at DiscussionsControllerIntegrationTests.CreateDiscussionIsSuccessful() in DiscussionsControllerIntegrationTests.cs line: 25
at — End of stack trace from previous location where exception was thrown —

Thankfully the solution is pretty straight forward. Install GeoJSON:

Install-Package NetTopologySuite.IO.GeoJSON

Then merge the following with your existing addMvc call in startup.cs:

services.AddMvc(options =>
            {
                // Prevent the following exception: 'This method does not support GeometryCollection arguments'
                // See: https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/585
                options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Point)));
                options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Coordinate)));
                options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(LineString)));
                options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(MultiLineString)));
            })
                .AddJsonOptions(options =>
                {
                    foreach (var converter in NetTopologySuite.IO.GeoJsonSerializer.Create(new GeometryFactory(new PrecisionModel(), 4326)).Converters)
                    {
                        options.SerializerSettings.Converters.Add(converter);
                    }
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);