ASP.NET Core 2 with EventFlow configuration - asp.net

EventFlow have avery limited example on how to configure on dotnetcore which is based on dotnet core 1 and things changed a little but in dotnet core 2
Is there a way to use EventFlow configuration without Autofac?
There is discussion about here and the last comments are about the same thing I am asking here but no answers
https://github.com/eventflow/EventFlow/issues/158
basically I want to find a way to use the build in DI with doing some thing like
services.AddEventFlowOptions.New...
or
var resolver = EventFlowOptions.New.UseDotnetCoreServices(services)...
or ... anything else that you guys used?

I used this and it is working fine. What it looks like is that you pass in services into EventFlow's IoC AuotFac and it wraps around that.
As you can see you use the known ASP.NET Core API as usual, you Inject the same way without change in your Contollers, etc.
The only thing I changed was void ConfigureServices to IServiceProvider ConfigureServices - I am not sure if that actually impacts anything but it works.
You will need these packages
EventFlow.Aspnetcore.Middlewares;
EventFlow.AspNetCore.Extensions;
EventFlow.Autofac.Extensions;
In Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var containerBuilder = new ContainerBuilder();
var container = EventFlowOptions.New
.UseAutofacContainerBuilder(containerBuilder)
.AddDefaults(EventFlowTestHelpers.Assembly)
.AddAspNetCoreMetadataProviders();
containerBuilder.Populate(services);
return new AutofacServiceProvider(containerBuilder.Build());
}
and you need to use some MiddleWare provided by the package
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMiddleware<CommandPublishMiddleware>();
app.UseMvcWithDefaultRoute();//or whatever you are doing
}

Following on from the startup setup provided, i have created a simple web api solution that integrates with EventFlow with .net core 2.2. It uses the same commands/events from the source
Hope that helps!

Related

Good practices to analyze .NET Core effectively?

In short: how can I find efficiently the .NET-Core code (using VS2022), where a HTTP redirection is handled (the app was created using the console and makes use of a lot of extensions)
It know how to add some breakpoints in Startup.cs or Program.cs and to Watch items like configuration, services or app, endpoints. But how do they help me, after Program.cs has worked off an the App is running? In PHP, i can see each single file with code and add Debugging-Snippets everywhere. But in the example below, i can only see code which seems to "Build something". I can't see what happens when this Host has been built (CreateHostBuilder) and a simple HTTP-Request is received.
As i mentioned, i worked with PHP. I'm not yet familiar with VS2022 nor .NET-Core and this monolithic architecture. I'm happy for some advices how to search efficiency in a solution. Or maybe some useful links; I wasn't able to find useful resources.
Background and description of code below:
I followed this tutorial to create an Blazor App with ".NET Core 3.1" to authenticate on MS Azure AD and Read data from the corresponding O365 Account using the MS Graph API. So far so good, this works and, as soon as the Website loads, the visitor is redirected to the login page https://login.microsoftonline.com/ to authenticate.
Now, i'd like to avoid this redirect and reimplement the login process in a popup / modal. I've found some Tutorials attempting to do this, but always targeted another language / version / extensions. So i came up with the idea to analyse the existing code and find the names of the appropiate parts / extensions, so i can take a deeper look in the Documentation and the configuration values possible. The question is: Which part is responsible for what?
I tried to use the "Go to Definition" and always end up in a dead end. I've also detected an "Object Browser" but I'm not sure if this helps in my case. Unfortunately, I don't have the links to the original resources used to create this Code.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Blazor_Server_App
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Blazor_Server_App.Data;
using Microsoft.Graph;
namespace Blazor_Server_App
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
services.AddRazorPages();
services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
services.AddSingleton<WeatherForecastService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
Jet Brains has some good tooling for decompiling and looking at sources.
https://www.jetbrains.com/decompiler/
Even better Resharper coupled with Dot Peek will allow you to do all this inside of the IDE. It will even pull down the original sources for decompiled code that has debug symbols and a symbol server for. This should be the case for .NET 6 sources.
https://www.jetbrains.com/dotnet/
These are paid tools but well worth it for especially when you take into account the productivity gains Resharper provides in code annotations, syntax completion and refactoring. Although I will say the stock Visual Studio experience gets better every release and is not starting to rival Resharper.
Hope this helps.
Clarification:
DotPeek is free on its own. It only cost money if you want the full ide integration with Resharper. ILSpy is another free decompiler.
You will not be able to avoid having to redirect to https://login.microsoftonline.com/ to do a microsoft login. Microsoft(and any OAuth provider really) would not allow it to be embedded in your website as it would allow you to harvest user credentials as they enter them/clickjack the user.
It may be a better user experience to have a "Login with Microsoft" button that does the redirect when clicked rather than immediately redirect to the Microsoft login upon loading your webpage.

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

How to run Update Database using Code first in Entity Framework Core?

I run the Update-Database from visual studio to create a database, it works fine. I have published the app on a production server. But I cannot run Update-Database there. So how it can be done on the server where there is no visual studio?
I thought to create it when the application starts the first time. But I didn't get any reference or sample code.
I'm using .net core 2.0.
First I want to warn you that I do not know what consequences the following code may have, since I do not know enough about the Abp architecture.
In the ProjectName.Web.Mvc project, in the ConfigureServices method, add the following code:
public IServiceProvider ConfigureServices(IServiceCollection services) {
// other stuff
string connectionString = _appConfiguration
.GetConnectionString("Default");
services.AddDbContext<YouDbContextTypeName>(opt =>
opt.UseSqlServer(connectionString)
);
// other stuff
}
In the same file in the Configure method, add the following code:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
YouDbContextTypeName context) {
context.Database.Migrate();
// other stuff
}
You can run the change scripts made against your development Db in your say 'Test' Db. To generate the scripts you can run this which creates a file to run as say part of your deployment phase.
dotnet ef migrations script -i -o "C:\<your-path>\<your-filename>.sql"
The script generated is essentially a cumulation of all the 'Up' migrations. The script is 'idempotent' in that it only applies migrations if they haven't already been applied to the database.
REF: dotnet CLI

What built-in framework objects are available to controller's constructor in the Asp.Net Core MVC?

When I run my Asp.Net Core 1.1 MVC project, I can do things like this in my controller's constructor:
public MyController(
Microsoft.Extensions.Options.IOptions<AppSettings> appSettings,
IHostingEnvironment environment,
ILogger<MyController> logger)
{
....
It works, but how is it getting there? I know where I populated it in Startup.cs and put it in the DI/IoC, but I do not know what's going on here. Why/How is it working the way it does?
This did not help,
asp.net mvc what is the life of a controller?
There are 2 parts at play here:
After the routes have defined which controller should be used. The IControllerActivator creates the controller. Aspnet Core contains a ServiceBasedControllerActivator which uses the HttpContext.RequestServices which is the IServiceProvider created in the startup class.
The IServiceProvider is created from the IServiceColection:
var services = new ServiceCollection();
services.AddTransient<IMyInterface, MyClass>();
var serviceProvider = services.BuildServiceProvider(); //ioc container
serviceProvider.GetService<IMyInterface>(); //will create an instance of: MyClass
The same way this ServiceBasedControllerActivator works: it checks which properties the constructor has and injects them from the ServiceProvider.

ASP.NET MVC 6 AspNet.Session Errors - Unable to resolve injected dependency?

I've been having a problem using the new Microsoft.AspNet.Session features in ASP.NET MVC 6 (vNext).
The error occurs when accessing all pages, including those that don't use the session features themselves. I'm using the beta4 version for everything, including all of my packages and my dnvm environment. The project is running on Visual Studio 2015 RC.
Here are some resources that might be important (if there's anything else anybody needs just comment):
Project.json: http://pastebin.com/qCA2AjGd
DNVM List: http://puu.sh/ja8us/4f912c0a9a.png
Global.json: http://pastebin.com/CFZp75KE
I think it's a problem with the dependency injection for the session package (see first two lines of the stack trace) but after that I'm not sure what to do about it.
Are you sure you've correctly registered the appropriate services in ConfigureServices?
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.AddOptions();
services.AddSession();
}
public void Configure(IApplicationBuilder app) {
app.UseSession();
}
}
Note: you need to explicitly register the options services as you're using beta4 packages.
This issue was fixed recently: https://github.com/aspnet/Session/commit/dab08ba7e90027a3bf1ef69f740427e93a310f09#diff-2990206dea5be4b3850cad8d4759d577R14

Resources