Modelling an existing database in .NET Core 2.x - .net-core

I have an existing application. I am trying to port some pieces over from .NET 4.x over to .NET Core. I have created a context in my .NET Core app. I have create a db context via scaffold-dbcontext. I can run a basic query (hooray). Life is good. Now, I want to add in some async queries. I get the following error:
System.InvalidOperationException: 'The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations. For more details see http://go.microsoft.com/fwlink/?LinkId=287068.'
code:
var ctx = new GolfGameContext();
var userId = await (from u in ctx.AspNetUsers where u.Token == UserToken select u.Id).SingleAsync();
return userId;
This error seems strange. I have created some .NET Core 2.x apps from scratch and everything seems to work properly. I am able to do async queries with them just fine. When I look at the error link, I get taken to information about EF 6.x. I am guessing that there is something that the scaffold-dbcontext puts in the resulting models that cause this problem. I am also guessing that the code I have created in Core 2.x doesn't contain these same limitations. Am I on the right track? Do I need to change something in my context/models to get async to work properly? All thoughts are welcome.
TIA,
Wally

Related

How to add ApplicationInsights Logging Provider in Framework Console App Using Autofac

I am working on a .NET (full framework 4.7.1) console app that uses AutoFac for DI purposes.
We are in the process of migrating slowly to .NET Core, and have switched to using the ILogger abstractions provided by Microsoft.Extensions.Logging.Abstractions.
I have wired up ILogger<> and ILoggerFactory in AutoFac using the following
private static void RegisterLogging(ContainerBuilder builder)
{
builder.RegisterType<LoggerFactory>().As<ILoggerFactory>().SingleInstance();
builder.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>)).InstancePerDependency();
}
This depends on Microsoft.Extensions.Logging - and it seems to be working.
Now I want to wire up the Application Insights Logging provider, however all the documentation I can find only mentions how to add it to the .NET Core DI Container, and looking through the source code on various repos, I am a bit mystified on how to do it.
I figured that I might be able to do it like this:
builder.RegisterType<ApplicationInsightsLoggerProvider>().As<ILoggerProvider>();
But it depends on IOptions<TelemetryConfiguration> telemetryConfigurationOptions and IOptions<ApplicationInsightsLoggerOptions> applicationInsightsLoggerOptions neither of which I have.
Have anybody done this, or have suggestions on how to accomplish it?
I managed to get something going by doing it like this:
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging();
serviceCollection.AddApplicationInsightsTelemetryWorkerService();
builder.Populate(serviceCollection);
Not the very best solution, but I guess it does allow me to use the footwork of the ServiceCollection extensions methods, so I might have to live with that if nobdoy has a better answer

APIGatewayProxyRequest not getting populated after dotnet core upgrade from 1.0 to 2.1

I am currently working on to upgrade dotnet core framework version from 1.0 to 2.1 of an existing product.
The UI of the same is made in Angular which makes service calls to AWS Lambdas (made using dotnet core) for all the requirements. User data is stored in AWS Cognito and every time a service call is made it first gets verified by fetching data from Cognito. This part stopped working after the framework upgrade.
The following lines of code stopped fetching data:
if (!HttpContext.Items.Keys.Contains("APIGatewayRequest"))
{
//Log error
}
HttpContext.Items["APIGatewayRequest"] as APIGatewayProxyRequest;
Custom api gateway authorizer is used for Cognito and also HttpContext is used inside a controller.
The following image shows the Request.HttpContext structure for me:
Any information around this issue will be great.
Finally, after trying desperately for a couple of days, I got the resolution. In the newer version of DotNet Core the value of the HttpContext key got changed from "APIGatewayRequest" to "LambdaRequestObject" causing all the pain. And the code was using the value directly from a constant declared inside the project and was not using the constant "AbstractAspNetCoreFunction.LAMBDA_REQUEST_OBJECT" provided by the framework.

Get role of current user in Sharepoint Online site using Microsoft Graph

I am building a .net core web app in which i use AzureAD auth and Microsoft Graph to get data from a sharepoint online site.
I need to get the groups of the current user.
I tried to use graphClient.Me.MemberOf.Request().GetAsync();
I think i'm getting the role of the user in the Azure directory.
But i want the role of the current user for a specific sharepoint online site.
Is that possible to get this information and how ?
I don't find a working way to get this using Microsoft Graph.
EDIT:
As Microsoft Graph doesn't allow to get that data.
I tried to call the following Sharepoint Online API endpoint :
https://{name}.sharepoint.com/sites/{name}/_api/web/currentUser?$select=Groups/Title&$expand=Groups
Using this api endpoint i can see all the roles of the current user in my browser.
But i don't find how to call it from my .net core web app.
Tried the following :
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-types", "application/json;odata=verbose");
var response = await client.GetAsync("https://{name}.sharepoint.com/sites/{name}/_api/web/currentUser?$select=Groups/Title&$expand=Groups");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
}
But that give me a 403 response.
EDIT 2 :
I am currently trying to use CSOM to get this informations(TCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200.)
But i don't find a way to get TokenHelper.cs.
var token = TokenHelper.GetAppOnlyAccessToken(SharePointPrincipalId, webUri.Authority, null).AccessToken;
var ctx = TokenHelper.GetClientContextWithAccessToken(webUri.ToString(), token);
I tried to add "AppForSharePointOnlineWebToolkit" and it did not add the needed files in the project.
How can i get the TokenHelper.cs file ?
Thanks for any help.
Tristan
To execute CSOM code in .net core, do below settings.
We can install the package as below.
Install-Package TTCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200 -Version 16.1.8029.1200
More information is here: TTCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200
Or use the following solution from GitHub: NetCore.CSOM
Or follow the steps below.
1.Create a .NET Core console app.
2.Add the references: Microsoft.SharePoint.Client.Portable.dll, Microsoft.SharePoint.Client.Runtime.Portable.dll, and Microsoft.SharePoint.Client.Runtime.Windows.dll.
Note: If the project has references to Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll, please remove them.
These references can be accessed by installing CSOM library into another project, and then navigating to installed nuget packages in the file directory: c:\Users\user.nuget\packages\microsoft.sharepointonline.csom(version)\lib\netcore45
3.Add the code below to the .NET Core 2.0 console application:
Get current user role:
To get the current user role, you can use Web.GetUserEffectivePermissions method.
Ex:
ClientResult<BasePermissions> permission= web.GetUserEffectivePermissions(name);
context.ExecuteQuery();
var res = permission.Value;
Refer below link to get clientcontext using access token: https://www.sharepointpals.com/post/how-to-get-the-client-context-using-app-access-token-by-passing-client-id-and-client-secret-id-using-csom-in-sharepoint-office-365/
No. Microsoft Graph doesn't expose an endpoint that allows you to get the information of SharePoint Group and its members.
If you has this requirement, you could vote this idea on Microsoft Graph UserVoice.

ASP .NET Boilerplate + MongoDb

I am using ASP.Net boilerplate framework + SQL Server 2016 in my project. Recently I have faced a challenge with migration from SQL Server to MongoDB. I have found that it is possible with ASP .NET boilerplate and installed required NuGet packages, however, due to the lack of documentation the only thing I have managed to do is to define respective RepositoryBase class:
public abstract class MyRepositoryBase<TEntity, TPrimaryKey> : MongoDbRepositoryBase<TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
protected MyRepositoryBase(IMongoDatabaseProvider databaseProvider)
: base(databaseProvider)
{
}
}
As far as I understand, first of all, I need to define connection string somewhere now. And then populate the database with required basic data(which previously had been done by EF Core migrations). Obviously, EF Core in the new approach is obsolete so does that mean for my DbContext class that it is obsolete as well?
Actually, there are plenty of questions in relation to ASP .NET boilerplate and MongoDB integration, therefore my current post is actually a request for provision of some kind of example of the existing integration. Thank you in advance.
You can register your module by depending on it on your web module.
[DependsOn(typeof(YourMongoDbModule))]
public class YourWebModule : AbpModule
{
}
I think you have to register the repository with:
IocManager.Register(typeof(IMongoRepository<>), typeof(MongoRepository<>), Abp.Dependency.DependencyLifeStyle.Singleton);
You can refer this sample.
Look at this comment also.
Here is a framework which maps EF Core to Mongo DB.

Entity Framework 5 Code-First dropping/recreating database when app is restarted

I'm experimenting with the latest EF 5 CF (in VS2010, not VS2012). I'm generally following the MSDN EF 5.0 Quickstart: Creating a Model with Code First...
Rather than using a console app, my DbContext is in a Windows Service, which will eventually expose various data service methods by hosting a WCF Service (the client will be WPF MVVM)
In the OnStart of the Windows Service, I invoke SetInitializer, and then do a simple query to trigger initialization:
// Start the Windows service.
protected override void OnStart(string[] args)
{
Database.SetInitializer<MediaLibraryContext>(new MediaLibraryContextInitializer());
using (var context = new MediaLibraryContext())
{
var firstMedia = (from m in context.Medias select m).FirstOrDefault();
}
...
And EF CF creates the database from the model and seeds it, as expected.
But when I stop/restart the Service, EF appears to delete the database and recreate it (or perhaps it's just dropping the tables and recreating them?). All post-initialization changes I've made to the database are gone, and only the "seed" data is present.
I've worked with EF 4.1 and 4.3, but I've never seen this behavior. Any ideas where to look???
DadCat
EDIT: I found the problem just after posting this... the Quick start code has the database initialization strategy set to DropCreateDatabaseAlways.
That's what I get for copy/pasting code without carefully looking at it!
DC
I found the problem just after posting this... the Quick start code has the database initialization strategy set to DropCreateDatabaseAlways.

Resources