WorkerService configure a RabbitMq with MassTransit - dependency-injection

in a WorkerService .Net I am trying to configure a MassTransit host with RabbitMq but I am getting this Error
Reference to type 'IBusControl' claims it is defined in 'MassTransit', but it could not be found
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context,services) =>
{
services.AddHostedService<Worker>();
services.AddAutoMapper(typeof(Program));
//MassTransit-RabbitMQ Configuration
services.AddMassTransit(config => {
config.UsingRabbitMq((ctx, cfg) => {
cfg.Host(context.Configuration.GetValue<string>("EventBusSettings:HostAddress"));
});
});
services.AddMassTransitHostedService();
})
.Build();
await host.RunAsync();
What am I missing?

You are probably referencing an assembly that is not current. The latest version of MassTransit no longer requires the AddMassTransitHostedService configuration method. More details are available in the documentation.

Related

Visual Studio Docker debug failed. System.ArgumentException: The path must be absolute. (Parameter 'root')

I am working with a ASP dotnet 6 project and it working fine when build a docker container with external commands or debugging with IIS. But when debugging with docker support provided by visual studio it ended with below error inside the container.
Program.cs file content
using Microsoft.AspNetCore;
using Microsoft.Extensions.FileProviders;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// 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.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");
app.Run();
Here is the error inside the container
Unhandled exception. System.ArgumentException: The path must be absolute. (Parameter 'root')
at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root, ExclusionFilters filters)
at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.<>c.<UseStaticWebAssetsCore>b__1_0(String contentRoot)
at Microsoft.AspNetCore.StaticWebAssets.ManifestStaticWebAssetFileProvider..ctor(StaticWebAssetManifest manifest, Func`2 fileProviderFactory)
at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssetsCore(IWebHostEnvironment environment, Stream manifest)
at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssets(IWebHostEnvironment environment, IConfiguration configuration)
at Microsoft.AspNetCore.WebHost.<>c.<ConfigureWebDefaults>b__9_0(WebHostBuilderContext ctx, IConfigurationBuilder cb)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass9_0.<ConfigureAppConfiguration>b__0(HostBuilderContext context, IConfigurationBuilder builder)
at Microsoft.AspNetCore.Hosting.BootstrapHostBuilder.RunDefaultCallbacks(ConfigurationManager configuration, HostBuilder innerBuilder)
at Microsoft.AspNetCore.Builder.WebApplicationBuilder..ctor(WebApplicationOptions options, Action`1 configureDefaults)
at Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(String[] args)
at Program.<Main>$(String[] args) in D:\workspace\my\mdo\xx\src\xxx\Program.cs:line 1
Aborted

Identity Server 4 on docker Issue

hi i am new to identity server 4. recently i made simple small project using identity server 4. solution has 3 projects of 1.identityserver4 2.api resource 3.client razor. every thing fine in localhost. but when i try the same project in docker i got problem with identityserver 4. this is the repository of the test project here
Problem
when web app client is started it should redirect to identity server 4 login page which happens with local host. but here i ran into the problem.
NOTE: until now according to searching i reach there may be certificate problem OR networking and DNS issue and i tried some suggested approaches but it wont work or maybe i doing it wrong
1st i tried set the authority address to the container name with port like http://identityserver4:9001 (also for client address which is port 5001) which throws the errors as
SocketException: Connection refused
System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.ThrowException(SocketError
error, CancellationToken cancellationToken)
HttpRequestException: Connection refused (identityserver4:9001)
System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(string host,
int port, HttpRequestMessage initialRequest, bool async,
CancellationToken cancellationToken)
IOException: IDX20804: Unable to retrieve document from:
'http://identityserver4:9001/.well-known/openid-configuration'.
Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string
address, CancellationToken cancel)
InvalidOperationException: IDX20803: Unable to obtain configuration
from: 'http://identityserver4:9001/.well-known/openid-configuration'.
Microsoft.IdentityModel.Protocols.ConfigurationManager.GetConfigurationAsync(CancellationToken
cancel)
In this case the error came from client app.
When i shutdown the identityserver4 service and try the client it throws the same error. so it seems totally it could not reach identity server.
i tried the defined bridge network in docker-compose as well and i got the same result
also i tried http request to http://identityserver4:9001/.well-known/openid-configuration from client (i removed the client authorization & authentication stuff for test this) which throws the Connection refused error in response.
2nd i tried set the authority address to http://identityserver4:80. in this case the client app redirect to identity server 4 identityserver4/connect/authorize but the browser throws
dial tcp: lookup identityserver4 on 127.0.0.11:53: no such host
in this case the client passed and redirect to identity server 4
http request to http://identityserver4:80/.well-known/openid-configuration from client (i removed the client authorization & authentication stuff for test this) gives the correct response.
i linked the github repository above but for ease i also added mu configuration as below.
i try some approaches but this is the BASE CODE from the first attempt.
docker-compose.override.yml
version: '3.4'
services:
identityserver4:
container_name: identityserver4
environment:
- ASPNETCORE_ENVIRONMENT=Development
ports:
- "9001:80"
networks:
- mynet
clientapp:
container_name: clientapp
environment:
- ASPNETCORE_ENVIRONMENT=Development
ports:
- "5001:80"
depends_on:
- identityserver4
networks:
- mynet
apiresource:
container_name: apiresource
environment:
- ASPNETCORE_ENVIRONMENT=Development
ports:
- "8001:80"
networks:
- mynet
networks:
mynet:
external: true
Identity Server
client configuration in Config.cs
new Client
{
ClientId = "razorClient",
ClientName = "RAZOR Client App",
AllowedGrantTypes= GrantTypes.Hybrid,
RequirePkce = false,
AllowRememberConsent = false,
RedirectUris = new List<string>()
{
"http://clientapp:80/signin-oidc"
},
PostLogoutRedirectUris = new List<string>()
{
"http://clientapp:80/signout-callback-oidc"
},
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
AllowedScopes = new List<string>()
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"MYAPI"
},
AllowAccessTokensViaBrowser = true,
}
program.cs
using IdentityServer;
var builder = WebApplication.CreateBuilder(args);
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
builder.Services.AddControllersWithViews();
builder.Services.AddIdentityServer(options =>
{
options.IssuerUri = "http://identityserver4:80";
})
.AddInMemoryClients(Config.Clients)
.AddInMemoryIdentityResources(Config.IdentityResources)
//.AddInMemoryApiResources(Config.ApiResources)
.AddInMemoryApiScopes(Config.ApiScopes)
.AddTestUsers(Config.TestUsers)
.AddDeveloperSigningCredential();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseHttpsRedirection();
}
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
app.Run();
Client APP
program.cs
using ClientApp.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc.Authorization;
var builder = WebApplication.CreateBuilder(args);
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
builder.Services.AddHttpClient();
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Authority = "http://identityserver4:80";
options.MetadataAddress = "http://identityserver4:80/.well-known/openid-configuration";
//options.BackchannelHttpHandler = new HttpClientHandler
//{
// ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
//};
options.RequireHttpsMetadata = false;
options.ClientId = "razorClient";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("MYAPI");
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
});
builder.Services.AddMvcCore(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHttpsRedirection();
// 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.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
i got the solution
Description
the problem is the container communication. when running the project on localhost (not on docker) every thing is set to localhost:port address including authority address of is4. the app is authorized or redirect to login page simply. but in docker env the authority have to addressed based on docker inter-communication address ( local host is unknown here which leads to connection refused ) which is known by docker containers network but not machine localhost. so in that case the authority of is4 works but when it comes to redirect to login page ( identity server 4 UI ) based on authority address that address is unknown by local machine so it throws DNS error. so according to #Dimitris Maragkos answer i set the base addresses to local machine Ip address like
options.Authority= "http://192.168.8.202:9001"
including the client and api relevant required addresses.

.NET 6 UseWindowsService() throws exception

Here's my "ENTIRE" code in program.cs.
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService();
// Add services to the container.
builder.Services.AddGrpc();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "error");
app.Run();
Packages:
Grpc.AspNetCore(2.47.0)
Microsoft.Extensions.Hosting.WindowsServices (6.0.0)
I deployed this a test server and tried to start the service...and I got this in the Event Log:
Application: PartReservationGrpc.exe CoreCLR Version: 6.0.622.26707
.NET Version: 6.0.6 Description: The process was terminated due to an
unhandled exception. Exception Info: System.NotSupportedException: The
content root changed from "C:\windows\system32" to
"D:\CMAP\iceman\partreservation". Changing the host configuration
using WebApplicationBuilder.Host is not supported. Use
WebApplication.CreateBuilder(WebApplicationOptions) instead. at
Microsoft.AspNetCore.Builder.ConfigureHostBuilder.ConfigureHostConfiguration(Action1 configureDelegate) at Microsoft.Extensions.Hosting.HostingHostBuilderExtensions.UseContentRoot(IHostBuilder hostBuilder, String contentRoot) at Microsoft.Extensions.Hosting.WindowsServiceLifetimeHostBuilderExtensions.UseWindowsService(IHostBuilder hostBuilder, Action1 configure) at
Microsoft.Extensions.Hosting.WindowsServiceLifetimeHostBuilderExtensions.UseWindowsService(IHostBuilder
hostBuilder) at Program.$(String[] args) in
C:\Users\WuJ22\source\Workspaces\C5CG2133PXF\gRPC\PartReservation\PartReservation\PartReservationGrpc\Program.cs:line
33
line 33: is exactly where the UseWindowsService() is made.
Has anyone run into this issue?
Answer can be found here:
The trick is calling the CreateBuilder() with the WebApplicationOptions to set the ContentRootPath.

scdf 1.7.3 docker k8s #Bean no running, no logs

As a user, writing a processor as a cloud function,
scdf 1.7.3, spring boot 1.5.9, spring-cloud-function-dependencies 1.0.2,
public class MyFunctionBootApp {
public static void main(String[] args) {
SpringApplication.run(MyFunctionBootApp.class,
"--spring.cloud.stream.function.definition=toUpperCase");
}
#Bean
public Function<String, String> toUpperCase() {
return s -> {
log.info("received:=" + s);
return ( (s+"jsa").toUpperCase());
};
}
}
i've create a simple stream => time | function-runner | log
function-runner-0.0.6.jar at nexus is ok
docker created ok,
Container entrypoint set to [java, -cp, /app/resources:/app/classes:/app/libs/*, function.runner.MyFunctionBootApp]
No time message from time pod arrived to function-runner processor executing toUpperCase function
No logs
I am checking deploying using , app.function-runner.spring.cloud.stream.function.definition=toUpperCase, #FunctionalScan
any clues?
We discussed function-runner being deprecated in favor of native support of Spring Cloud Function in Spring Cloud Stream. See: scdf-1-7-3-docker-k8s-function-runner-not-start. Please don't duplicate post it.
Also, you're on a very old Spring Boot version (v1.5.9 - at least 1.5yrs old). More importantly, Spring Boot 1.x is in maintenance-only mode, and it will be EOL by August 2019. See: spring-boot-1-x-eol-aug-1st-2019. It'd be good that you upgrade to 2.1.x latest.

SignalR + Redis in cluster not working

Background
When running the website with single application instance (container) - SignalR is working perfectly.
When scaling out to more instances (>1), it throws errors and is just not working. I looked for an explanation on the internet and found that I need to configure my Signalr to work in cluster. I choose Redis as my backplane.
I worked through many tutorials on how to do it right and it's just not working for me.
Environment
I working asp.net core v2.1 hosted in Google cloud. The application is deployed as Docker container, using Kestrel + nginx. The docker container runs in a Kubernetes cluster behind a load balancer.
My Configuration
Startup.cs:
public class Startup
{
public Startup(IConfiguration configuration,
IHostingEnvironment hostingEnvironment)
{
Configuration = configuration;
HostingEnvironment = hostingEnvironment;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSignalR().AddRedis(options =>
{
options.Configuration = new ConfigurationOptions
{
EndPoints =
{
{ ConfigurationManager.Configuration["settings:signalR:redis:host"], int.Parse(ConfigurationManager.Configuration["settings:signalR:redis:port"])}
},
KeepAlive = 180,
DefaultVersion = new Version(2, 8, 8),
Password = ConfigurationManager.Configuration["settings:signalR:redis:password"]
};
});
// ...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/errors/general");
app.UseHsts();
}
// nginx forward
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseSignalR(routes =>
{
routes.MapHub<StatisticsHub>("/hubs/myhub");
});
}
}
In order to verify that the connection to Redis server succeeded, I checking the output window of the Kastrel:
Same behaviour (connected) found also on servers (2 replicas, not on development enviroment).
In order to verify that the Signalr is "really" using the Redis (not just connecting), I used redis-cli to connect the Redis server and found that:
From this I can understand that there are some "talks" on Redis.
I removed the website LoadBalancer (GCP) and deployed it agian. Now with Sticky-Session: ClientIP. This loadbalancer is routing requests to the different containers.
The only place that I didnt changed is the nginx configuration. I'm wrong?
The result
SignalR not working on the browser. These errors are from the browser console:
scripts.min.js:1 WebSocket connection to 'wss://site.com/hubs/myhub?id=VNxKLazEKr9FKM4GPZRDhA' failed: Error during WebSocket handshake: Unexpected response code: 404
scripts.min.js:1 Error: Failed to start the transport 'WebSockets': undefined
Error: Connection disconnected with error 'Error: Server returned handshake error: Handshake was canceled.'.
scripts.min.js:1 Error: Connection disconnected with error 'Error: Server returned handshake error: Handshake was canceled.'.
files.min.js:1 Uncaught (in promise) Error: Error connecting to signalR. Error= Error
...
Question
What I missed? What to check?

Resources