I want to run my blazor app as a service using TopShelf but now that i have configured a service i lost all css. it does still use Startup as it is supposed to but it just doesnt load my css? is this just a problem with paths? or is it something else?
I havent made any changes to the Startup class.
my main:
public static void Main(string[] args)
{
var exitCode = HostFactory.Run(x =>
{
x.Service(() => new Service(args));
x.SetServiceName("Print");
x.SetDescription("service");
x.StartAutomaticallyDelayed();
});
Environment.ExitCode = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());
}
my Service:
public bool Start(HostControl hostControl)
{
Configuration.Settings settings = Program.initSettings();
new Task(() => CreateWebHostBuilder(args)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseStaticWebAssets()
.UseUrls(settings.BaseAddress)
.Build().Run()).Start();
return true;
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
});
//.UseStartup<Startup>();
}
So after a bit of trial and error i found it was a dumb mistake. I didn't change the properties of the css files to copy to output directory. Now my css is being loaded.
Related
My DbContext is in a separate class library project.
I want to generate migration using a worker service project.
is it possible?
Used this method and try again to generate migration. Maybe it will work well for you:
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureServices(
(hostContext, services) =>
{
var connectionString = hostContext.Configuration.GetConnectionString("DefaultConnection");
var migrationAssemblyName = typeof(Worker).Assembly.FullName;
services.AddDbContext<StockDbContext>(option =>
option.UseSqlServer(connectionString,
b => b.MigrationsAssembly(migrationAssemblyName)));
});
I am currently in a situation where I need to call a controller as part of the startup of an application?
The controller is being hosted by the application itself..
Is that somehow possible? It just needs to be triggered every time the application starts.
I ended implementing an interface and implement the required functionality within this interface.
IControllerService.cs
public interface IControllerService
{
void InsertIntoDB(string name);
}
Controller.cs
public InsertIntoDB(string name)
{
....
}
so I in my Startup.Configure could call
startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SchemaContext schemaContext, IControllerService controllerService)
{
....
controllerService.InsertIntoDB("InitData")
}
My API endpoint uses the same interface to call out
You could inject IHostApplicationLifetime on Startup.Configure() method , then write the callback for ApplicationStarted that would be triggered when the application host has fully started, and call your controller action within callback method.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
//register other services
}
private async Task<Action> OnApplicationStartedAsync(IHttpClientFactory httpClientFactory)
{
var client = httpClientFactory.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44326/api/values");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
//deal with the response
var result = await response.Content.ReadAsStringAsync();
}
return null;
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
{
IHttpClientFactory _clientFactory = app.ApplicationServices.GetService(typeof(IHttpClientFactory)) as IHttpClientFactory;
lifetime.ApplicationStarted.Register(OnApplicationStartedAsync(_clientFactory).Wait);
//other middlewares
}
In your Startup, you could call:
public void ConfigureServices(IServiceCollection services)
{
...
...
services.AddTransient<Interfaces.IService, Service.ServiceImplementator>();
...
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
...
Task.Run(() => {
app.ApplicationServices.GetRequiredService<Interfaces.IService>().DoWorkOnStartup();
});
...
...
}
Don't call a controller action, I think your controller should be invoking a service to do the work.
When I request a controller action that is [Authorize] decorated instead of being redirected to the login page I receive a 401 error.
This is a .net core mvc app using the identity template running on IIS express.
When i run the app from program.cs the redirect to login works fine.
I've added explicit directions to for the cookie authentication to use the /Account/Login redirect both for configuration and services section, as well as configuring Identity to perform this redirect.
I can't get it to work. Below is my StartUp class, what should I change to make it work in IIS express?:
public class Startup
{
private MapperConfiguration _mapperConfiguration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
_mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfileConfiguration());
});
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(
option => {
option.Cookies.ApplicationCookie.LoginPath = "/Account/Login";
option.Cookies.ApplicationCookie.AutomaticChallenge = true;
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddDataProtection();
services.AddMvc();
services.AddSignalR();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.Configure<IISOptions>(options => options.AutomaticAuthentication = true);
services.AddSingleton<IMapper>(sp => _mapperConfiguration.CreateMapper());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, RoleManager<IdentityRole> roleManager)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
//app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "MyCookies",
SlidingExpiration = true,
AutomaticAuthenticate = true,
AutomaticChallenge = true,
LoginPath = new PathString("/Account/Login")
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "index",
template: "{controller=Home}/{id?}",
defaults: new { action = "Index" });
});
app.UseSignalR();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
MyDbInit.Init(context, roleManager);
}
}
I had this same problem all night and could not find a solution to it. Running the site directly from Kestrel redirected fine, but through IIS or IIS Express it simply would not redirect - it would go to a white page.
After posting to the Identity Git about it, I realized that my template was set up to run under 1.0.1 of the framework, not 1.1.0. I updated it to use 1.1.0 and updated all the Nuget packages to 1.1.0 and now it is redirecting in IIS and IIS Express properly.
I'm not sure if the package updates "fixed" something that was screwy, or if this was simply a problem with 1.0.1 that was fixed in 1.1.0.
https://blogs.msdn.microsoft.com/webdev/2016/11/16/announcing-asp-net-core-1-1/
Identity adds cookie authentication automatically. You're adding it a second time in Configure.
When you add the second instance you're setting both the automatic properties, so now two middlewares are trying to do the redirection, and that behaviour is "undefined" (where undefined == "Going to seriously mess things up").
This line inside Configure method in Startup class, resolve me problem:
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseAuthentication(); // <= This line
app.UseMvc(routes =>
{
...
});
}
}
Composable.AddLocation doesn't works for me, even dll is loaded (i can see it in output window), but GetExport(s) return null always.
I used standard example from http://xsockets.net/docs/the-plugin-framework
So this works:
Composable.LoadAssembly(Path.Combine(Helper.PluginsDirectory, "testplugin.dll"));
But this doesn't:
Composable.AddLocation(Helper.PluginsDirectory, SearchOption.AllDirectories, false);
All other code is same.
P.S. Here is solution: Composable.AddLocation begins to work when I deleted XSockets Plug-in Framework dll and dll, which describes plugin interface from Plugins directory.
My guess is this:
You have files in "Helper.PluginsDirectory" that is already loaded by the plugin framework.
If you load one of them twice you will not be able to get the export.
A workaround...
class Program
{
static void Main(string[] args)
{
Composable.RegisterExport<IAnimal>();
//Helper that fix your issue...
Helpers.AddLocation(#"C:\Users\Uffe\Desktop\DynamicAssemblies\Implementation\bin\Debug", SearchOption.AllDirectories);
Composable.ReCompose();
var a = Composable.GetExports<IAnimal>();
foreach (var animal in a)
{
animal.Says();
}
Console.ReadLine();
}
}
public static class Helpers
{
public static void AddLocation(string location, System.IO.SearchOption searchOption)
{
foreach (var assembly in Directory.GetFiles(location, "*.dll", searchOption))
{
AssemblyName verifyName = AssemblyName.GetAssemblyName(assembly);
if(!Composable.LoadedAssemblies.Any(p => p.FullName == verifyName.FullName))
Composable.LoadAssembly(assembly);
}
}
}
We have an NServiceBus Windows service that takes a while to register modules when starting up. We would like to request additional time from the Service Manager to start up properly. For services not using NServiceBus, this would be done using ServiceBase.RequestAdditionalTime. How would this be done using NServiceBus.Host?
We ended up removing NServiceBus.Host and using Topshelf instead. Note additional config required on service startup.
public static void Main(string[] args)
{
HostFactory.Run(hf =>
{
hf.Service<MailboxListenerService>(svc =>
{
svc.ConstructUsing(mls => new MailboxListenerService());
svc.WhenStarted((mls, control) => mls.Start(control));
svc.WhenStopped(mls => mls.Stop());
});
});
}
public class MailboxListenerService
{
private RunWebApi _webApiRunner;
public MailboxListenerService()
{
}
public bool Start(HostControl hostControl)
{
hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(60));
var kernel = new StandardKernel(new MailboxListenerModule());
Configure.With()
.DefineEndpointName("my.endpoint.name")
.DefiningEventsAs(t => typeof(Messaging.Markers.IEvent).IsAssignableFrom(t))
.Log4Net<NlogAppenderForLog4Net>(a => { })
.NinjectBuilder(kernel)
.MsmqTransport()
.MsmqSubscriptionStorage("my.subscription.storage")
.DisableTimeoutManager()
.DisableSecondLevelRetries()
.UnicastBus()
.ImpersonateSender(false);
_webApiRunner = kernel.Get<RunWebApi>();
_webApiRunner.Run();
return true;
}
public void Stop()
{
_webApiRunner.Stop();
}
}
Unfortunately no, we have opened up an issue to support this in future versions
https://github.com/NServiceBus/NServiceBus/issues/1046
On workaround would be to increase the timeout for you service using the registry:
http://support.microsoft.com/kb/824344