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.
Related
I created a .NET 5, Visual Studio project using the Worker Service template, which creates a Program.cs file containing the Program class with the following method:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
Since I want to specify a Startup class to implement health checks for this application (since it will be deployed to Kubernetes (I’m following this tutorial)), I read there’s the ConfigureWebHostDefaults extension method. However, I get the following error trying to use it:
The code that gives me the error is the following (the one hidden by the error in the above screenshot):
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
This answer seemed to show my situation, but the Microsoft.Extensions.Hosting.Abstractions package doesn’t resolve the issue. I also tried to import the Microsoft.AspNetCore.Hosting and Microsoft.AspNetCore.Hosting packages, without success. I’m already using the Microsoft.Extensions.Hosting package.
I think it's still in the Microsoft.Extensions.Hosting namespace, but it's now in the Microsoft.AspNetCore assembly.
(The class containing the method is GenericHostBuilderExtensions).
I want to log errors for a console application using Elmah.I've found ElmahCore and elmah.io.core but I don't know how to setup any of them on a console app.I'm using .net core.
ELMAH (the open source project) doesn't work with .NET Core. ElmahCore has a lot of dependencies to ASP.NET Core, but if you really wanted to, you could do something like this:
class Program
{
static void Main(string[] args)
{
var log = new MemoryErrorLog();
log.Log(new Error(new Exception()));
var errors = new List<ErrorLogEntry>();
var result = log.GetErrors(0, 10, errors);
Console.WriteLine(result);
Console.WriteLine(errors);
Console.ReadLine();
}
}
You can replace MemoryErrorLog with a target logger of your choice.
The package named elmah.io.core is a deprecated package from elmah.io. elmah.io is (among other things) a commercial cloud version of ELMAH, where you store all of your errors in the cloud (list of differences between ELMAH and elmah.io). elmah.io works with .NET core through either the Elmah.Io.Client NuGet package or using one of the integrations for popular logging frameworks like Serilog and NLog.
I wouldn't recommend you to use ElmahCore for logging in a console application. It is created for ASP.NET Core. There are much better options for logging from a console application, like the mentioned logging frameworks.
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!
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
I Have a spring boot application with following config.
#Configuration
#EnableWebMvc
#ComponentScan({ "com.xxx.mypackages" })
public class MyWebAppConfiguration extends WebMvcConfigurerAdapter {
}
In my project I have some web services and spring controllers. I want swagger to be enabled only in my web service classes. Currently, it generates documentation for both rest and controller classes. How can I customize that?
I'm using following dependency in gradle.
compile "com.mangofactory:swagger-springmvc:1.0.2"
If you look at the 1.0.2 documentation you'll find that SwaggerSpringMvcPlugin has a includePatterns method. This method takes a regular expression of the paths to include. For e.g. if you had an path prefix for the rest endpoints like this /rest/some-resource.... you could include a pattern, something like the snippet shown below
#Bean
public SwaggerSpringMvcPlugin customImplementation(){
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
//... more config goes here
//regex to identify your rest services path
.includePatterns(".*rest.*");
}
Also it would be useful to know that we're going to be releasing 2.0 shortly with support for swagger spec 2.0. That might be something to consider as well.