Why am I getting this error when trying to implement UseNetTopologySuite in my ASP.Net Core 2.2 api? - ef-core-2.0

I am attempting to use the geometry functionality in Sql Server and EF Core.
I've installed the following packages
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite" Version="2.2.6" />
<PackageReference Include="NetTopologySuite" Version="2.0.0" />
In my Startup.cs, I have the following:
services.AddDbContextPool<CRFlowContext>(options =>
options.UseSqlServer("connection string", x => x.UseNetTopologySuite());
});
Everything builds fine, but when I attempt to run the app, I get the following error:
Application startup exception: System.MissingMethodException: Method not found: 'GeoAPI.IGeometryServices NetTopologySuite.NtsGeometryServices.get_Instance()'.
at Microsoft.Extensions.DependencyInjection.SqlServerNetTopologySuiteServiceCollectionExtensions.AddEntityFrameworkSqlServerNetTopologySuite(IServiceCollection serviceCollection)
at Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerNetTopologySuiteOptionsExtension.ApplyServices(IServiceCollection services)
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.ApplyServices(IDbContextOptions options, ServiceCollection services)
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.<GetOrAdd>b__2(Int64 k)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions options, Boolean providerRequired)
at Microsoft.EntityFrameworkCore.DbContext..ctor(DbContextOptions options)
at Entities.CRFlowContext..ctor(DbContextOptions`1 options) in C:\Src\myproj\myproj.Entities\MyProjContext.cs:line 11
at lambda_method(Closure )
at Microsoft.EntityFrameworkCore.Internal.DbContextPool`1.Rent()
at Microsoft.EntityFrameworkCore.Internal.DbContextPool`1.Lease..ctor(DbContextPool`1 contextPool)
I suspect this has to do with creating my entity in the Program.cs and injecting it into the rest of the app.
Any ideas on how to fix this?

You need to delete the NetTopologySuite library
And just use Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite.

For anyone looking at this, it turns out that you need to install the NetTopologySuite.Core, not NetTopologySuite.
Once I installed this, it worked fine.

Related

MissingMethodException with Suave & Fable.Remoting

Here is a minimal sample that will reproduce the issue.
Trying to hit that endpoint, either with a Fable client or just navigating to http://127.0.0.1:8080/ITestAPI/Test causes the server to throw a Method not found:
[ERR] request failed
System.MissingMethodException: Method not found: 'Microsoft.FSharp.Collections.FSharpMap`2<System.String,System.Object> HttpContext.get_userState()'.
at Fable.Remoting.Suave.SuaveUtil.setBinaryResponseBody#26-1.Invoke(Unit unitVar)
at Microsoft.FSharp.Control.AsyncPrimitives.CallThenInvoke[T,TResult](AsyncActivation`1 ctxt, TResult result1, FSharpFunc`2 part2) in F:\workspace\_work\1\s\src\fsharp\FSharp.Core\async.fs:line 386
at Fable.Remoting.Server.Proxy.makeEndpointProxy#80-10.Invoke(AsyncActivation`1 ctxt)
at Microsoft.FSharp.Control.AsyncPrimitives.unitAsync#577.Invoke(AsyncActivation`1 ctxt) in F:\workspace\_work\1\s\src\fsharp\FSharp.Core\async.fs:line 577
at Program.greetFun#12-1.Invoke(AsyncActivation`1 ctxt) in C:\Users\username\code\test\suavetest\Program.fs:line 12
at Microsoft.FSharp.Control.AsyncPrimitives.unitAsync#577.Invoke(AsyncActivation`1 ctxt) in F:\workspace\_work\1\s\src\fsharp\FSharp.Core\async.fs:line 577
at Microsoft.FSharp.Control.Trampoline.Execute(FSharpFunc`2 firstAction) in F:\workspace\_work\1\s\src\fsharp\FSharp.Core\async.fs:line 105
I've hit my head against this for a couple of days now, with no progress. Same error occurs using both .Net Core 3.1 and .Net 5.
Anyone have any insight into what might be causing this? I'm not seeing any open issues with Fable.Remoting or Suave about this, so I have to imagine it's something I'm doing wrong?
This looks like an FSharp.Core mismatch issue. Are you depending on a specific FSharp.Core package that is less than 4.7.2?
In general, unless you are writing a library intended for distribution on NuGet, you should not pin your dependency on FSharp.Core at all. For applications, always use whatever the .NET SDK provides and you'll virtually never run into these issues.
Explicitly FSharp.Core package references are an additional issue for library authors who need to worry about which F# versions their package is compatible with. If that is not a requirement for you, then it's best to never opt into that additional bit of complexity.
Using your sample code in a brand-new .NET 5 console app works for me:
Test.fsproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="fable.remoting.suave" Version="4.13.0" />
</ItemGroup>
</Project>
Program.fs
open System
open Suave
open Fable.Remoting.Server
open Fable.Remoting.Suave
type ITestAPI = {
Test : Async<string>
}
let greetFun =
async {
return "It works!"
}
let testAPI = {
Test = greetFun
}
let webApp =
Remoting.createApi()
|>Remoting.fromValue testAPI
|> Remoting.withDiagnosticsLogger (printfn "%s")
|>Remoting.buildWebPart
[<EntryPoint>]
let main argv =
startWebServer defaultConfig webApp
0 // return an integer exit code
Under the covers, this uses the FSharp.Core in the SDK that is version 4.7.0 or higher, which makes it compatible with the library you're using and results in no exception at runtime.
I ran into the same issue. Phillip is correct, but is missing an important piece. The problem is that the current version of Fable.Remoting.Suave is built against Suave 2.5.6. If you reference this specific version of Suave, you can have both dependencies in your .fsproj file:
<ItemGroup>
<PackageReference Include="Fable.Remoting.Suave" Version="4.29.0" />
<PackageReference Include="Suave" Version="2.5.6" />
</ItemGroup>

error in running transformation:indexoutofrangeexception - petapeco

as per suggestion for by #CreativeManix I started investigating petaPeco
Retrieving large number of rows (more than 10 mil) in asp.net mvc application
After adding exact system.data.oracleclient + putting web.config in the bin where mvc is getting compiled in .dll I got following error:
Error 3
Running transformation: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices)
at System.Array.GetValue(Int32 index)
at Microsoft.VisualStudio.TextTemplating5F4490FB7AE018243DBB4DF6250E7211.GeneratedTextTransformation.GetCurrentProject()
at Microsoft.VisualStudio.TextTemplating5F4490FB7AE018243DBB4DF6250E7211.GeneratedTextTransformation.GetConnectionString(String& connectionStringName, String& providerName)
at Microsoft.VisualStudio.TextTemplating5F4490FB7AE018243DBB4DF6250E7211.GeneratedTextTransformation.InitConnectionString()
at Microsoft.VisualStudio.TextTemplating5F4490FB7AE018243DBB4DF6250E7211.GeneratedTextTransformation.LoadTables()
at Microsoft.VisualStudio.TextTemplating5F4490FB7AE018243DBB4DF6250E7211.GeneratedTextTransformation.TransformText()
at Microsoft.VisualStudio.TextTemplating.TransformationRunner.RunTransformation(TemplateProcessingSession session, String source, ITextTemplatingEngineHost host, String& result)
This error shows up when i run the transformation after installation of petaPoco.
One thing I do know the error is coming from "GetCurrentProject" - and probably - "(Array)dte.ActiveSolutionProjects"
I think something is wrong in the way petaPoco is set up with my project! somehow it can't find the activesolution project. I am not too sure how to fix it.
I investigated this.
In my question section I asked few questions:
I was not sure about how to fire transformation/or process of generating Database.CS. So initially I was installing petapoco from the command prompt- I
To do that you just click "Run Custom Tool" by right clicking on the "Database.tt". If your connection string is correct + you are referencing correct Oracle/SQL server data provider + that provider is available in GAC + (if it is oracle and you have the password for the default schema user of the database you are trying to access)- then that should generate the Database.cs
To enable Oracle data client to read the schema out of oracle database I needed to take out following entry:
cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null);
And everything worked.
Connection string can look like:
connectionString="Data Source=PXWREG;Persist Security Info=True;User ID=XWREG_ACDS_T;password=isacdst"

SignalR Requests Throwing "Hub could not be resolved."

I've been using SignalR since an early version and upgraded along the way however I have deployed my application to my Windows Server 2008 R2 production server and now the app crashes out with the " Hub could not be resolved." exception.
edit: StackTrace Added:
[InvalidOperationException: 'stockitems' Hub could not be resolved.]
Microsoft.AspNet.SignalR.Hubs.HubManagerExtensions.EnsureHub(IHubManager hubManager, String hubName, IPerformanceCounter[] counters) +426
Microsoft.AspNet.SignalR.Hubs.HubDispatcher.Initialize(IDependencyResolver resolver, HostContext context) +716
Microsoft.AspNet.SignalR.Owin.CallHandler.Invoke(IDictionary`2 environment) +1075
Microsoft.AspNet.SignalR.Owin.Handlers.HubDispatcherHandler.Invoke(IDictionary`2 environment) +363
Microsoft.Owin.Host.SystemWeb.OwinCallContext.Execute() +68
Microsoft.Owin.Host.SystemWeb.OwinHttpHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object extraData) +414
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
Microsoft.Owin.Host.SystemWeb.CallContextAsyncResult.End(IAsyncResult result) +146
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
On my dev machine and local test server I am getting no issues.
The hub in question is really simple:
[HubName("StockItems")]
public class StockItemHub : Hub
{
}
Originally I thought it was an issue with the HubName so removed it but it still bombs out.
Originally I thought it was due to dependency injection so I then changed my Global.asax to look as follows:
var signalRResolver = new SignalRDependencyResolver();
GlobalHost.DependencyResolver = signalRResolver;
var configuration = new HubConfiguration { Resolver = signalRResolver };
RouteTable.Routes.MapHubs(configuration);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, config.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
edit: what is SignalRDependencyResolver?
SignalRDependencyResolver didn't exist until I tried to solve this issue. As I believe its a dependency injection issue I wrapped DefaultDependencyResolver overrode GetService and GetServices to first check my Ninject kernel for the type and if not fall back to the DefaultDependencyResolver
Any ideas?
The server is running IIS7, Windows Server 2008 with .Net 4.5
The application is an MVC 4 .Net 4.5
I had this same error due to my Hub class being internal, therefore SignalR couldn't find it within my assembly.
Setting the hub to public solved the issue.
I suffer from this problem just now, and I dig in a little deeper, and have just found out a possible solution.
My hub class are not in assembly of the web project, they are in some referenced assemblies. This is a very common scenario in a multi-layer application.
When starting up, signalR will try to find hub class by an IAssemblyLocator instance. When deployed within an IIS site, this IAssemblyLocator instance find through all referenced assemblies. But at this point of time, the application is just during the startup, which means many (referenced but not loaded yet) assemblies may had NOT been gathered by owin host environment.
So the lookup for hub classes fails.
So, just add your assembly into system.web/compilation/assemblies section of Web.Config:
<system.web>
<compilation targetFramework="4.5">
<assemblies>
<add assembly="HubAssembly, Version=1.0.0.0, Culture=neutral"/>
</assemblies>
</compilation>
</system.web>
Or if you like, you can also solved this problem by implementing a custom IAssemblyLocator class, register it into the dependency resolver as soon as app.MapSignalR is invoked.
using Microsoft.AspNet.SignalR.Hubs;
public class AssemblyLocator : IAssemblyLocator {
public IList<System.Reflection.Assembly> GetAssemblies()
{
// list your hubclass assemblies here
return new List<System.Reflection.Assembly>(new []{typeof(HubAssembly.HubClass).Assembly});
}
}
// add following code to OwinStartup class's Configuration method
app.MapSignalR();
GlobalHost.DependencyResolver.Register(typeof(Microsoft.AspNet.SignalR.Hubs.IAssemblyLocator), () => new AssemblyLocator());
This is now an old question but it reared its ugly head again this weekend. After spending alot of time investigating I have found that SignalR wasn't the only thing broken in the deployment, my WebAPI was also throwing could not find controller exceptions.
Turns out this is caused by the internals of SignalR and WebApi reflecting over all the types in the Sites assembly. A TypeLoadException was being thrown , in my case due to having a class derive RoleEntryPoint which is an Azure type but as the site was being deployed in a non Azure Environment things fell apart. Simply excluding this type from non Azure builds resolved the issue.
It would be nice if these TypeLoadExceptions were more visible but there it is.
Similar to #Jijie Chen, when I hit this issue I found that it was not able to load my assembly containing my hub. The fix for me was more straightforward though. In my case I had three projects. All the logic, including the hub was in a project of its own and I had two projects intended to host using owin. One was a console project that was working fine. I then adapted that to a windows service to host it. Well, somehow I managed to forget to include a reference to the project containing my hub. This still compiled fine because the host code relies on the signalr/owin mapping functions which load the hub(s) at runtime not compile time. So when I would start up the service and try to connect I got the hub no defined error described here because it couldn't find the assembly with my hub.

How to use Entity Framework + PostgreSQL from connection?

I have already seen threads discussing the use of Entity Framework and PostgreSQL with official instructions. Those instructions need to run gacutil for every install which is not so handy for deployment purposes.
What I want to do here is passing PostgreSQL connection directly to the DbContext constructor. This is enough for me because I am going to use CodeFirst without designer. This is what I do:
public class Context : DbContext
{
Context(System.Data.Common.DbConnection connection)
: base(connection, true)
{
}
public static Context CreateContext()
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=********;Database=xxx;");
conn.Open();
return new Context(conn);
}
}
But using this method I get a NotSupportedException with message:
Unable to determine the provider name for connection of type
'Npgsql.NpgsqlConnection'.
What should I do?
You'll need to register the Npgsql provider in the app/web.config. See section 3.4 Using Npgsql with ProviderFactory of the Npgsql manual.
When you install an ADO.NET provider for databases (MySQL, PostgreSQL, etc.) the installers will usually register the provider assembly in the GAC and add an entry to the machine.config. If you want to deploy without having to install the provider you'll need to include a copy of the provider assembly (set Npgsql assembly reference as Copy Local for your project) and add an entry to your application's app/web.config as follows:
<configuration>
...
<system.data>
<DbProviderFactories>
<clear />
<add name="Npgsql Data Provider" invariant="Npgsql" support="FF" description=".Net Framework Data Provider for Postgresql Server" type="Npgsql.NpgsqlFactory, Npgsql, Version=2.0.1.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7" />
</DbProviderFactories>
</system.data>
...
</configuraiton>
Make sure the version matches exactly the version of the Npgsql assembly you deploy with (or just omit the Version/Culture/PublicKeyToken). The <Clear /> is there to avoid conflicts if running on a machine that already has entry for Npgsql in its machine.config. Without the clear you would get an exception. However, that's also assuming you're not relying on any other providers specified in the machine.config for your application.

Why is EF4 trying to re-create my database even though the model hasn't changed?

I have an ASP.NET MVC 3 Beta website using SQL Server CE 4.0. With both ScottGu's NerdDinner example and my own code, I will sometimes get the following exception as soon as I try to access the database:
File already exists. Try using a different database name.
[ File name = D:\Sourcecode\NerdDinner\NerdDinner\App_Data\NerdDinners.sdf ]
Line 17: public ActionResult Index()
Line 18: {
Line 19: var dinners = from d in nerdDinners.Dinners
Line 20: where d.EventDate > DateTime.Now
Line 21: select d;
[SqlCeException (0x80004005): File already exists. Try using a different database name. [ File name = D:\Sourcecode\NerdDinner\NerdDinner\App_Data\NerdDinners.sdf ]]
System.Data.SqlServerCe.SqlCeEngine.ProcessResults(IntPtr pError, Int32 hr) +92
System.Data.SqlServerCe.SqlCeEngine.CreateDatabase() +1584
System.Data.SqlServerCe.SqlCeProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 timeOut, StoreItemCollection storeItemCollection) +287
System.Data.Objects.ObjectContext.CreateDatabase() +84
System.Data.Entity.Internal.DatabaseOperations.Create(ObjectContext objectContext) +35
System.Data.Entity.Infrastructure.Database.Create() +70
System.Data.Entity.Infrastructure.CreateDatabaseOnlyIfNotExists`1.InitializeDatabase(TContext context) +360
System.Data.Entity.Infrastructure.Database.Initialize() +272
System.Data.Entity.Internal.InternalContext.Initialize() +90
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +34
System.Data.Entity.Internal.Linq.EfInternalQuery`1.Initialize() +140
System.Data.Entity.Internal.Linq.EfInternalQuery`1.get_Provider() +29
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +34
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
NerdDinner.Controllers.HomeController.Index() in D:\Sourcecode\NerdDinner\NerdDinner\Controllers\HomeController.cs:19
I cannot figure out why this works sometimes with an existing .dbf file and other times it complains. I have even tried explicitly setting the default behaviour with
Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<...>());
Has anyone else experienced this?
Restarting Cassini doesn't seem to make a difference.
Hitting refresh in IE after receiving this error will make the exact same page load properly.
Sorry to resurrect such an old question, but I was experiencing this today and have found a workaround which does not involve installing an older version of the CTP.
From The correct url for the blogpost is http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx (about half-way through the blog post)
*Go into your AppStart_SQLCEEntityFramework.cs file and the DefaultConnectionFactory line to this:*
Database.DefaultConnectionFactory = new SqlCeConnectionFactory(
"System.Data.SqlServerCe.4.0",
HostingEnvironment.MapPath("~/App_Data/"),"");
My particular database is placed in the App_Data folder but I'm assuming that if yours is not you should be able to change the path to suit and it will work.
Hope this helps!
It looks like this is a recently discovered bug.
MSDN Forum
The workaround is to re-install SQL Server CE 4.0 CTP 1 download
Install and use SQL Server CE CTP1, which is still downloadable on Microsoft sites. This solved my problem with that.
I had the same problem today with released MVC3 and SQL Server CE 4.0 downloaded with NuGet and it was resolved by uncommenting the line:
DbDatabase.SetInitializer(new CreateCeDatabaseIfNotExists<MyContext>());
And replacing MyContext with the context class that was inheriting from DBContext in the models folder.
The final SQL Compact Edition 4.0 is out and after installing it the issue is not happening anymore. Here is the announcement from the team blog:
Microsoft SQL Server Compact 4.0 is available for download

Resources