nancy selfhost, with dryioc and bootstrapper -> Method not found exception - nancy

At work we require a small application, and decided to test some things we are not really familiar with for this project as well.
I started with a console app, using topshelf to host nancy via the nancy selfhosting package.
All of this works.
Now I wanted to wire in the DryIoc container into the nancy bootstrapper and got the following error:
System.MissingMethodException
HResult=0x80131513
Message=Method not found: 'DryIoc.Rules DryIoc.Rules.With(DryIoc.FactoryMethodSelector, DryIoc.ParameterSelector, DryIoc.PropertiesAndFieldsSelector, Boolean)'.
Source=Nancy.Bootstrappers.DryIoc
StackTrace:
at Nancy.Bootstrappers.DryIoc.DryIocNancyBootstrapper.<GetApplicationContainer>b__0(Rules rules)
at DryIoc.Container..ctor(Func`2 configure, IScopeContext scopeContext)
at Nancy.Bootstrappers.DryIoc.DryIocNancyBootstrapper.GetApplicationContainer()
at Nancy.Bootstrapper.NancyBootstrapperBase`1.Initialise()
at Nancy.Hosting.Self.NancyHost..ctor(INancyBootstrapper bootstrapper, HostConfiguration configuration, Uri[] baseUris)
at Nancy.Hosting.Self.NancyHost..ctor(Uri baseUri, INancyBootstrapper bootstrapper, HostConfiguration configuration)
at Segrey.Licensing.Web.WebService.Start() in I:\git projects\Segrey.Licensing\Segrey.Licensing.Web\WebService.cs:line 21
at Segrey.Licensing.Service.Program.<>c.<CreateHost>b__1_2(WebService ls) in I:\git projects\Segrey.Licensing\Segrey.Licensing.Service\Program.cs:line 26
at Topshelf.ServiceConfiguratorExtensions.<>c__DisplayClass2_0`1.<WhenStarted>b__0(T service, HostControl control)
at Topshelf.Builders.DelegateServiceBuilder`1.DelegateServiceHandle.Start(HostControl hostControl)
at Topshelf.Hosts.ConsoleRunHost.Run()
My bootstrapper: empty, no registrations yet as I first wanted to test this out
before making it more complex
public class Bootstrapper : DryIocNancyBootstrapper
{
protected override void ApplicationStartup(IContainer container, IPipelines pipelines)
{
//No registrations should be performed in here, however you may
//resolve things that are needed during application startup.
base.ApplicationStartup(container, pipelines);
}
protected override void ConfigureApplicationContainer(IContainer container)
{
//Perform registation that should have an application lifetime
base.ConfigureApplicationContainer(container);
}
protected override void ConfigureRequestContainer(IContainer container, NancyContext context)
{
//Perform registrations that should have a request lifetime
base.ConfigureRequestContainer(container, context);
}
protected override void RequestStartup(IContainer container, IPipelines pipelines, NancyContext context)
{
// No registrations should be performed in here, however you may
// resolve things that are needed during request startup.
base.RequestStartup(container, pipelines, context);
}
}
And in my .Start method for the service via topshelf where the bootstrapper gets assigned
public void Start()
{
var hostConfig = new HostConfiguration() { UrlReservations = new
UrlReservations { CreateAutomatically = true } };
var uri = new Uri(_hostUrl);
_nancyHost = new NancyHost(uri, new Bootstrapper(), hostConfig);
_nancyHost.Start();
}
Error occurs on new NancyHost(uri, new Bootstrapper(), hostConfig); as soon as I add new Bootstrapper() into the arguments

Sounds like a versioning issue. Check your .config file for binding redirects for dryioc.
It appears DryIocNancyBootstrapper thinks it's using version X of DryIOC, but instead it's using version Y (due to a binding redirect), which doesn't have that method (either it was removed or it's an older version that doesn't yet have it).
Figure out what version DryIocNancyBootstrapper wants (i.e., version X in the example above) and reference that version.

Related

WPF and EntityFrameworkCore - Adding migration gives "No database provider has been configured for this DbContext"

Note I have read the large number of SO answers that appear to be similar, but I am already doing what they suggested, so I don't know if there is some difference with WPF (they all seem to relate to ASP.NET). Also, most answers relate to run-time errors, not ones when adding migrations.
I'm trying to set up a .NET Core 3 WPF project that uses EntityFrameWork Core, but am having problems adding a migration. I have set up my context as follows...
public class ApplicationDbContext : DbContext {
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) {
}
public ApplicationDbContext() {
}
public DbSet<Product> Products { get; set; }
}
The parameterless constructor is there, as without it I get an exception Unable to create an object of type 'ApplicationDbContext' when trying to add a migration.
My App.xaml.cs contains the following...
public partial class App {
public IServiceProvider ServiceProvider { get; private set; }
public IConfiguration Configuration { get; private set; }
protected override void OnStartup(StartupEventArgs e) {
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", optional: false, reloadOnChange: true);
Configuration = builder.Build();
ServiceCollection serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
ServiceProvider = serviceCollection.BuildServiceProvider();
MainWindow mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
mainWindow.Show();
}
private void ConfigureServices(IServiceCollection services) {
// Configuration
services.Configure<AppSettings>(Configuration.GetSection(nameof(AppSettings)));
// Database
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlConnection")));
// Windows
services.AddTransient(typeof(MainWindow));
}
}
I realise that some of this is irrelevant, but thought I'd show the whole class in case it reveals something I missed. The code is based on this blog post.
However, when I try to add a migration, I get an exception "No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext."
As far as I can see, I have configured the database provider. I put a breakpoint in the ConfigureServices method, and can see that services.AddDbContext is called with the correct connection string.
Anyone any ideas what I've missed?
UPDATE I tried connecting to an existing database, and it worked absolutely fine, so it looks like the database provider has been configured correctly. It's only when I try to add a migration that I get the exception.
UPDATE 2 It seems that the migration tool is using the parameterless constructor on the context, which is why it thinks the provider hasn't been configured. If I remove the lines that configure it from App.xaml.cs, and instead override the OnConfiguringmethod to call UseSqlServer then the migration works fine. However, apart from the fact that I've not seen anyone else doing this (which makes me wonder if it's really the right way to do it), I don't see how to get the connection string from the config file. I can't inject an IConfiguration parameter, as the whole issue is that migrations requires a parameterless constructor.
It's actually quite simple with .Net Core 3.1 and EF Core Version 5, Entity Framework will look at the entry point class for the static function CreateHostBuilder, in my case that would be the App class in app.xaml.cs.
Not entirely sure the convention required prior to .Net Core 3.1. From my experience it had something to do with having a Startup class with .Net Core 2.1 and ASP.Net.
https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli
My solution:
public partial class App : Application
{
/// <summary>
/// Necessary for EF core to be able to find and construct
/// the DB context.
/// </summary>
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
// Configure Application services
.ConfigureServices((context, services) =>
{
ConfigureServices(context, services);
});
}
/// <summary>
/// Not necessary but I prefer having a separate function for
/// configuring services.
/// </summary>
private static void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
...
}
/// <summary>
/// Hold the built Host for starting and stopping
/// </summary>
private readonly IHost AppHost;
/// <summary>
/// Constructor
/// </summary>
public App()
{
// Create Application host
AppHost = CreateHostBuilder(new string[] { }).Build();
}
/// <summary>
/// App Startup Event Handler
/// </summary>
private async void Application_Startup(object sender, StartupEventArgs e)
{
// Start the application host
await AppHost.StartAsync();
...
}
/// <summary>
/// App Exit Event Handler
/// </summary>
private async void Application_Exit(object sender, ExitEventArgs e)
{
// Kill the application host gracefully
await AppHost.StopAsync(TimeSpan.FromSeconds(5));
// Dispose of the host at the end of execution
AppHost.Dispose();
}
}
You need to implement IDesignTimeDbContextFactory. There is a lot of hidden plumbing in an ASP.NET Core app that deals with wiring up the apps service provider so it can be found by the dotnet ef tooling, but no such plumbing exists in WPF. In addition the ef tools know nothing about WPF events so your OnStartup method isn't going to even be called (an instance the class wont even get created) to create your DI setup so that the ef tools can find your DBContext.
Move the code that creates the ServiceProvider into the constructor, other than the bit that looks up the main window and displays it.
Implement IDesignTimeDbContextFactory<ApplicationDbContext>. In the implemented CreateDbContext method return ServiceProvider.GetRequiredService<ApplicationDbContext>()
The tooling will then create an instance of your class, which will setup DI, and call that method to get your (now configured) DB Context and it should work.
I'd also recommend moving to HostBuilder based config (that blog post was written before the final version of Core 3 was released). You will find an updated version of the same post here

Exception (cause) is always null in Hystrix feign fallback

I have an issue finding the exception cause in FallBackFactory, mine is a old application, so i can not use spring cloud approach (with annotations etc..)
I found the below solution, but still not working for me:
Issue in getting cause in HystrixFeign client fallback
Here is the code i have:
public static class ProfileFallbackFactory implements ProfileProxy, FallbackFactory<ProfileFallbackFactory> {
final Throwable cause;
public ProfileFallbackFactory() {
this(null);
}
ProfileFallbackFactory(Throwable cause) {
this.cause = cause;
}
#Override
public ProfileFallbackFactory create(Throwable cause) {
LOG.info("Profile fallback create "+cause);
return new ProfileFallbackFactory(cause);
}
public Profile getProfile(String id) {
}
instance creation:
profileProxy = new HystrixFeign.Builder().setterFactory(new CustomSetterFactory())
.decode404()
.decoder(new GsonDecoder(gsonWithDateFormat))
.encoder(new GsonEncoder(gsonWithDateFormat))
.errorDecoder(new profileProxyErrorDecoder())
.target(ProfileProxy.class,profileServiceUrl, (FallbackFactory<ProfileFallbackFactory>)new ProfileFallbackFactory());
There is a logger added in ProfileProxyErrorDecoder class, but this logger is not found in logs. I can see com.netflix.hystrix.exception.HystrixRuntimeException in server logs
Can someone please point me where i am going wrong?

(Android Studio) Connecting an app to Google Endpoints Module

I'm having trouble following the second step here.
I really don't understand how this sample does anything other than return a simple toast message. How does it utilize the API to display that message?
class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
#Override
protected String doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
I'm afraid my this sample is too complex for my limited knowledge. How exactly do I "talk" to the Google Endpoints Module when running an app? Specifically, What is EndpointsAsyncTask();?
Are there any resources listing all the methods available to me? Is there a simpler example of an app communicating with a Google Cloud Endpoint?
The service methods available to you are defined by the backend source in section 1.
In the example you posted, this line: myApiService.sayHi(name).execute()
is an actual invocation call to the backend that you defined by annotating #ApiMethod("sayHi") on the method in the MyEndpoint.java class of your backend module.
The reason your Android app defines an EndpointsAsyncTask is because slow operations such as calls that hit the network need to happen off of the UI thread to avoid locking the UI. The demo simply puts the returned value into a Toast but you could modify onPostExecute() to do whatever you'd like with the result.
For more info on Google Endpoints check out:
https://cloud.google.com/appengine/docs/java/endpoints/
And for info about using an Android AsyncTask look here:
http://developer.android.com/reference/android/os/AsyncTask.html

Registering Startup Class In Nancy Using AutoFac Bootstrapper

I've been reading through a lot of the Jabbr code to learn Nancy and trying to implement many of the same patterns in my own application. One of the things I can't seem to get working is the concept of an on application start class. The Jabbr code base has an App_Start folder with a Startup.cs file (here) in it with the following implementation.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
...
SetupNancy(kernel, app);
...
}
}
private static void SetupNancy(IKernel kernel, IAppBuilder app)
{
var bootstrapper = new JabbRNinjectNancyBootstrapper(kernel);
app.UseNancy(bootstrapper);
}
When I tried to do something similar to that in my project the Startup.cs file was just ignored. I searched the Jabbr code base to see if it was used anywhere but I wasn't able to find anything and the only differences I could see is Jabbr uses Ninject while I wanted to use AutoFac
Is there a way to register a startup class in nancy?
Take a look at my project over on GitHub, you'll be interested in the Spike branch and may have to unload the ChainLink.Web project to run I can't remember.
I had some trouble finding a way to configure the ILifetimeScope even after reading the accepted answer here by TheCodeJunkie. Here's how you do the actual configuration:
In the bootstrapper class derived from the AutofacNancyBootstrapper, to actually configure the request container, you update the ILifetimeScope's component registry.
protected override void ConfigureRequestContainer(
ILifetimeScope container, NancyContext context)
{
var builder = new ContainerBuilder();
builder.RegisterType<MyDependency>();
builder.Update(container.ComponentRegistry);
}
The application container can be updated similarly in the ConfigureApplicationContainer override.
You should install the Nancy.Bootstrappers.Autofac nuget, inherit from the AutofacNancyBootstrapper type and override the appropriate method (depending on your lifetime scope requirements: application or request). For more info check the readme file https://github.com/nancyfx/nancy.bootstrappers.autofac
HTH
After following the advice from TheCodeJunkie you can use the Update method on the ILifetimeScope container parameter which gives you a ContainerBuilder through an Action:
protected override void ConfigureRequestContainer(ILifetimeScope container, NancyContext context)
{
container.Update(builder =>
{
builder.RegisterType<MyType>();
});
}

Example of testing a RPC call using GWT-TestCase with GAE

How is that for a lot of acronyms!
I am having trouble testing GWT's RPC mechanism using GWT's GWTTestCase. I created a class for testing using the junitCreator tool included with GWT. I am attempting to test using the built in Google App Engine using the created "hosted mode" testing profile created by junitCreator. When I run the test, I keep getting errors saying things like
Starting HTTP on port 0
HTTP listening on port 49569
The development shell servlet received a request for 'greet' in module 'com.google.gwt.sample.stockwatcher.StockWatcher.JUnit.gwt.xml'
[WARN] Resource not found: greet; (could a file be missing from the public path or a <servlet> tag misconfigured in module com.google.gwt.sample.stockwatcher.StockWatcher.JUnit.gwt.xml ?)
com.google.gwt.user.client.rpc.StatusCodeException: Cannot find resource 'greet' in the public path of module 'com.google.gwt.sample.stockwatcher.StockWatcher.JUnit'
I hope that someone somewhere has successfully run junit test (using GWTTestCase or just plain TestCase) that will allow for the testing of gwt RPC. If this is the case, could you please mention the steps you took, or better yet, just post code that works. Thanks.
SyncProxy allows you to make GWT RPC call from Java. So you can test your GWT RPC with regular Testcase (and faster than GwtTestcase)
See
http://www.gdevelop.com/w/blog/2010/01/10/testing-gwt-rpc-services/
http://www.gdevelop.com/w/blog/2010/03/13/invoke-gwt-rpc-services-deployed-on-google-app-engine/
I got this working. This answer assume's you're using Gradle, but this could easily be adopted to run from ant. First, you'll have to make sure that you separate your GWT tests from your regular JUnit tests. I created 'tests/standalone' for the regular tests, and 'tests/gwt' for my GWT tests. I still get 1 single HTML report in the end that has all of the info.
Next, you need to make sure JUnit is part of your ant classpath, as described here:
http://gradle.1045684.n5.nabble.com/Calling-ant-test-target-fails-with-junit-classpath-issue-newbie-td4385167.html
Then, use something similar to this to compile your GWT tests and run them:
task gwtTestCompile(dependsOn: [compileJava]) << {
ant.echo("Copy the test sources in so they're part of the source...");
copy {
from "tests/gwt"
into "$buildDir/src"
}
gwtTestBuildDir = "$buildDir/classes/test-gwt";
(new File(gwtTestBuildDir)).mkdirs()
(new File("$buildDir/test-results")).mkdirs()
ant.echo("Compile the tests...");
ant.javac(srcdir: "tests/gwt", destdir: gwtTestBuildDir) {
classpath {
pathElement(location: "$buildDir/src")
pathElement(location: "$buildDir/classes/main")
pathElement(path: configurations.runtime.asPath)
pathElement(path: configurations.testCompile.asPath)
pathElement(path: configurations.gwt.asPath)
pathElement(path: configurations.gwtSources.asPath)
}
}
ant.echo("Run the tests...");
ant.junit(haltonfailure: "true", fork: "true") {
classpath {
pathElement(location: "$buildDir/src")
pathElement(location: "$buildDir/classes/main")
pathElement(location: gwtTestBuildDir)
pathElement(path: configurations.runtime.asPath)
pathElement(path: configurations.testCompile.asPath)
pathElement(path: configurations.gwt.asPath)
pathElement(path: configurations.gwtSources.asPath)
}
jvmarg(value: "-Xmx512m")
jvmarg(line: "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005")
test(name: "com.onlyinsight.client.LoginTest", todir: "$buildDir/test-results")
formatter(type: "xml")
}
}
test.dependsOn(gwtTestCompile);
Finally, here's a simple GWT test:
public class LoginTest extends GWTTestCase
{
public String getModuleName()
{
return "com.onlyinsight.ConfModule";
}
public void testRealUserLogin()
{
UserServiceAsync userService = UserService.App.getInstance();
userService.login("a", "a", new AsyncCallback<User>()
{
public void onFailure(Throwable caught)
{
throw new RuntimeException("Unexpected Exception occurred.", caught);
}
public void onSuccess(User user)
{
assertEquals("a", user.getUserName());
assertEquals("a", user.getPassword());
assertEquals(UserRole.Administrator, user.getRole());
assertEquals("Test", user.getFirstName());
assertEquals("User", user.getLastName());
assertEquals("canada#onlyinsight.com", user.getEmail());
// Okay, now this test case can finish.
finishTest();
}
});
// Tell JUnit not to quit the test, so it allows the asynchronous method above to run.
delayTestFinish(10 * 1000);
}
}
If your RPC instance doesn't have a handy getInstance() method, then add one:
public interface UserService extends RemoteService {
public User login(String username, String password) throws NotLoggedInException;
public String getLoginURL(OAuthProviderEnum provider) throws NotLoggedInException;
public User loginWithOAuth(OAuthProviderEnum provider, String email, String authToken) throws NotLoggedInException;
/**
* Utility/Convenience class.
* Use UserService.App.getInstance() to access static instance of UserServiceAsync
*/
public static class App {
private static final UserServiceAsync ourInstance = (UserServiceAsync) GWT.create(UserService.class);
public static UserServiceAsync getInstance()
{
return ourInstance;
}
}
}
I hope that helps.

Resources