How to configure Program.cs without startup.cs? .NET 6.0 - electron

The instructions at Electron.NET instruct to add the following snippets to my .NET 6 project for Electron to run.
Add to Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseElectron(args);
webBuilder.UseStartup<Startup>();
});
Add to Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
// Open the Electron-Window here
Task.Run(async () => await Electron.WindowManager.CreateWindowAsync());
}
Since there is no longer a Startup.cs file, how do I convert this code to a usable state for a modern Program.cs file?
Obviously it's not as simple as putting all the code into a modern Program.cs file. I scoured google for an answer to this issue and didn't find anything. I also poured through the documentation in the github repository and Electron website. I don't have the experience to figure this out on my own and would love some help.

This works for me:
Program.cs
using ElectronNET.API;
using ElectronNET.API.Entities;
namespace tests;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddElectron();
builder.WebHost.UseElectron(args);
if (HybridSupport.IsElectronActive)
{
var window = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions
{
Width = 500,
Height = 250
});
window.OnClosed += () =>
{
Electron.App.Quit();
};
}
}
}
Pre-requisites
.NET 6
.NET 5 framework installed (at least runtime)
Node installed (for npm)
VS running as admin (I am running 2022 at time of writing)
Electron-API nuget package installed
Electron-CLI installed (dotnettool)
Result

Related

create sub domains "sub.example.com" with .net core 5

i'm trying to create a sub domain for my website, something like "sub.example.com", i've been following a tutorial on youtube but it is not working, this is what i have done.
my startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<SubdomainRouteTransformer>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapDynamicControllerRoute<SubdomainRouteTransformer>(
"{controller=Home}/{action=Index}/{id?}");
});
public class SubdomainRouteTransformer: DynamicRouteValueTransformer
{
public override async ValueTask<RouteValueDictionary> TransformAsync(
HttpContext httpContext,RouteValueDictionary values)
{
var host =httpContext.Request.Host.Value;
var subdomain = httpContext.Request.Host.Value.Split(".")[0];
if(!string.IsNullOrEmpty(subdomain)){
values["controller"]= subdomain;
}
return values;
}
}
program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls("https://*.localhost:5001");
});
i have also registred new subdomains on my machine hosts file
127.0.0.1 admin.localhost
127.0.0.1 bugreport.localhost
i tried to create a break point on the TransformAsync method, it is getting hit by the compiler whenever i enter the normal URL address "https://localhost:5001".
when i enter sub domain address "https://admin.localhost:5001" TransformAsync method is never getting hit .
any help is appreciated
i've figured out this by myself, it seams like the solution above is working perfectly, the issue was with Safari, somehow the solution above did not work on it but it worked perfectly on chrome.
also another small detail is that you can skip the last step of setting the host file on your machine, the solution works without it.

gRPC and MVC in same ASP.NET Core 3.0 Application

I am building out small, single purpose micro-services that require access via gRPC and Rest. We are implementing on ASP.NET Core 3.0. I realize this is pretty fresh stuff and have been looking for some reasonably complete reference implementations that demonstrate how to get this done.
I have a small .NET Service (Business Logic) call it IOrders. Now I want to wire up both gRPC and MVC (HTTP) against this back end service.
Any examples, github repos, blogs to follow or look around in would be greatly appreciated.
I had exactly same issue. I am runing.NET Core 3.0 and Grpc.AspNetCore Version 2.23.1. The biggest problem was to start it without SSL (not recommended for prod environments). Using certificate i found this github Secure_gRpc to be nice example.
Running without ssl for dev environments could be achieved in this way.
Program.cs file. Key aspects is to set HttpProtocols.Http1AndHttp2. I also removed certificate just to get it running. Uncomment next line to use SSL and certificate
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>()
.ConfigureKestrel(options =>
{
options.Limits.MinRequestBodyDataRate = null;
options.ListenLocalhost(8008, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
listenOptions.UseHttps(adapterOptions =>
{
adapterOptions.ClientCertificateMode = ClientCertificateMode.NoCertificate;
adapterOptions.ServerCertificate = null;
});
//listenOptions.UseHttps("<path to .pfx file>", "<certificate password>");
});
});
});
}
Startup.cs is pretty straightforward. It is very important to remember if you modify Startup.cs file order of added services is very important. If it doesnt work try other order and/or find official documentation.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc((options => { options.EnableDetailedErrors = true; }));
services.AddMvc(options => options.EnableEndpointRouting = false);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseMvcWithDefaultRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
});
}
}

NSwag: 404 Not Found /swagger/v1/swagger.json on IIS

I have a basic asp.net core 2.1 web API. I installed NSwag.ASPNetCore nuget package.
here is my startup.cs. When I run this on IIS Express, swagger is working fine.
Once I deploy this to IIS, I am getting 404 not found.
Do I need to add a Path somewhere?
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddMvc();
// Add framework services.
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//Add Application Services
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSwaggerDocument();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUi3();
app.UseMvc();
}
}
As mentioned by Rico below: upgrading to nswag v13 should fix the issue (for me it worked).
For versions of nswag before v13:
I had the same problem and I found a solution here: NSwag Issue #1914
What you need to do is configure a 'transform to external path':
app.UseSwaggerUi3(config =>
{
config.TransformToExternalPath = (s, r) =>
{
string path = s.EndsWith("swagger.json") && !string.IsNullOrEmpty(r.PathBase)
? $"{r.PathBase}{s}"
: s;
return path;
};
});
This worked for me on my iisexpress and on iis.
Check if you do not use Virtual Path for the application. Swagger by default checks absolute path instead of
localhost:port/MyVirtualPath/swagger/v1/swagger.json
It may happen when you use IIS server with virtual path delimiter.

SignalR for .NET Core 2.1 in docker not working after moving project to new PC

UPDATE: SOLVED (read below)
I created this project on PC1. I've been working on it for a while when I found SignalR. After implementing, and making SignalR work, I had to move to a new PC, so I saved the project folder and moved it to the new PC. I installed Docker for Windows, the .NET Core 2.1 SDK and VS. I put the project in the same folder (C:\users\xxx\source\repos). Now when I run it it works as expected, but the client (browser) doesn't react on SignalR calls from the server. Because I don't have functions being called from the client I'm not using a custom Hub.
My issue is this: As soon as I try to set up the SignalR connection to the server from the JS, it tells me in the JS-Console it couldn't find a matching constructor. When looking at the hub object using a breakpoint in AddMessage(), it is not null, so some kind of constructer is working.
I have no idea what to do.
Error message:
Connection disconnected with error 'Error: Server returned an error on close: Connection closed with an error. InvalidOperationException: A suitable constructor for type 'Microsoft.AspNetCore.SignalR.Hub' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.'.
My Code:
in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddSignalR(o =>
{
o.EnableDetailedErrors = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseSignalR(routes =>
{
routes.MapHub<Hub>("/shoutboxHub");
});
//...
}
in HomeController.cs
public class HomeController : Controller
{
private readonly ShoutboxDbContext context;
private readonly IHubContext<Hub> hub;
public HomeController(ShoutboxDbContext context, IHubContext<Hub> hub)
{
this.hub = hub;
this.context = context;
}
//...
[HttpPost]
public IActionResult AddMessage([FromBody]Message input)
{
//...
hub.Clients.All.SendAsync("Refresh");
return Json((Object)true);
}
}
in Index.js
var connection = new signalR.HubConnectionBuilder().withUrl("/shoutboxHub").build();
connection.on("Refresh", function () {
updateMessageBox();
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
UPDATE:
Okay, I got it working again. The issue apparently was that Microsoft.AspNetCore.SignalR.Hub apparently isn't a concrete type. How exactly that is defined and in what sense Hub is not concrete, I don't know. I only know that this rediculous fix solved my problem:
I made my own Hub called ShoutboxHub:
using Microsoft.AspNetCore.SignalR;
namespace Shoutbox.Hubs
{
public class ShoutboxHub : Hub
{
}
}
... and changed the three lines containing Hub to ShoutboxHub (and added using Shoutbox.Hubs;, but that goes without saying). That's it.

SignalR without OWIN

I'm participating in the ASP MVC project.
I want to use SignalR in the project but I don't want to use OWIN lib.
As I understand, SignalR is registered in the application using this piece of code:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
How can I modify this to remove the dependency to OWIN?
I would like to use approach similar to RouteConfig.RegisterRoutes(RouteTable.Routes);
If you don't want the owin lib you can use SignalR 1.x.
protected void Application_Start()
{
RouteTable.Routes.MapHubs();
}
First be sure to Get-Package within the Package Manager Console and remove all previous installments Uninstall-Package [Id] -RemoveDependencies as this should give you a clean slate.
What worked for me without assembly nor dependency issues was using NuGet to install Microsoft.AspNet.SignalR Version 1.1.4 into your App and DataAccess. Then add the following to your Global.asax file:
// Add this Library for MapHubs extension
using System.Web.Routing;
protected void Application_Start()
{
// This registers the default hubs route: ~signalr
// Simply add the line below WITHIN this function
RouteTable.Routes.MapHubs();
}
[Did this using Visual Studios 2015 Enterprise on 10/29/2015]
I was able to do it following this Microsoft documentation: https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.1
Their sample startup class is located here: https://github.com/aspnet/AspNetCore.Docs/blob/master/aspnetcore/signalr/hubs/sample/Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// other configure code
// ...
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// other configure code
// ...
app.UseSignalR(route =>
{
route.MapHub<ChatHub>("/chathub");
});
}

Resources