I would like to know the recommended approach to getting a connection string from a config file for my xUnit .net core test project.
I have set up a test project using the new Visual Studio 2017 xUnit Test project template for .net core. This project will run my integration tests that reference 2 different .net core class library projects - one of which will talk to the database using EF Core.
I understand that normally the connection string should not be set or accessed in a class library project - it should be the application that consumes the class library that should set the connection string.
However, in this case it appears that the xUnit test project is treated somewhat like a class library project. I have not seen any examples of how to set up some sort of config file and access that from the test project. How do I access the connection string from a config file so that my test project can consume my Datalayer class library project and pass in the appropriate connection string?
I was able to access the connection string from my xUnit test project by creating a DbOptionsFactory class that returns a DbContextOptions object initialized with a connection string that it reads from an appsettings.json configuration file.
This requires a dependency on Microsoft.Extensions.Configuration
public static class DbOptionsFactory
{
static DbOptionsFactory()
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var connectionString = config["Data:DefaultConnection:ConnectionString"];
DbContextOptions = new DbContextOptionsBuilder<MyDbContext>()
.UseSqlServer(connectionString)
.Options;
}
public static DbContextOptions<MyDbContext> DbContextOptions { get; }
}
appsettings.json
{
"Data": {
"DefaultConnection": {
"Name": "MyDbContext",
"ConnectionString": "connection string goes here"
}
}
}
When instantiating my DbContext I pass in the optionsBuilder object that has the connection string from the configuration file like so:
using (var context = new MyDbContext(DbOptionsFactory.DbContextOptions))
{
// access db here
}
Hope this helps anyone else that runs into the same issue.
Related
I am trying to create a selenium framework using spring boot. What I am trying to accomplish it spring-boot should manage selenium driver creation, even when we run the test in parallel and if possible I want to avoid passing driver object in page class constructor.
So I created a bean class like below
#Bean
public WebDriver getDriver(){
return new ChromeDriver();
}
it worked fine for the Single test. But for multiple tests in parallel, I changed the scope of the above method to the prototype, and when I ran the test it started multiple tests but it didn't work as I expected and commands started firing in the wrong browser. I know I am missing something related to Thread/parallel stuff. It would be really helpful if someone can guide me or someone can share git repo where spring-boot and selenium are used.
You could try changing the scope to thread with:
#Bean
#Scope(value = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS)
public WebDriver getDriver(){
return new ChromeDriver();
}
#Bean
public static CustomScopeConfigurer customScopeConfigurer()
{
CustomScopeConfigurer scopeConfigurer = new CustomScopeConfigurer();
Map<String, Object> scopes = new HashMap<>();
scopes.put("thread", SimpleThreadScope.class);
scopeConfigurer.setScopes(scopes);
return scopeConfigurer;
}
I have a back-end which is build on spring-boot and then some custom code from my school built upon that.
The front-end is pure angular application which I serve from a different server trough a gulp serve.
They're only connected by REST calls.
There's already an authentication module running on the backend and to now I need to serve this angular application from the same tomcat server the back-end is running on so it can also use this authentication module.
I've found this about multiple connectors so I copied it as following class to set up multiple connectors:
#ConfigurationProperties
public class TomcatConfiguration {
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
//tomcat.addAdditionalTomcatConnectors(createSslConnector());
return tomcat;
}
private Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = new ClassPathResource("keystore").getFile();
File truststore = new ClassPathResource("keystore").getFile();
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(8443);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass("changeit");
protocol.setKeyAlias("apitester");
return connector;
} catch (IOException ex) {
throw new IllegalStateException("can't access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}
}
Problem is that I don't see or find how I should setup these connectors so they serve from my angularJS build folder.
Upon searching I came upon Spring-Boot : How can I add tomcat connectors to bind to controller but I'm not sure if in that solution I should change my current application or make a parent application for both applications.
My current application main looks like this:
#Configuration
#ComponentScan({"be.ugent.lca","be.ugent.sherpa.configuration"})
#EnableAutoConfiguration
#EnableSpringDataWebSupport
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
If possible I'd like some more info about what connectors are in the spring-boot context.
If this is not the way to go I'd like someone to be able to conform this second solution or suggest a change in my code.
I'm really not sure enough about these solution that I want to go breaking my application over it. (though it's backed up with github)
Just place your AngularJS + other front-end assets into src/main/resources/static folder, Spring Boot will serve them automatically.
Kindly help me with this. I am using blob store for saving images and it is working perfectly fine on my local environment. But when I deploy the same code the cloud it is throwing me the exception : java.lang.NoClassDefFoundError: com/google/appengine/api/blobstore/BlobstoreServiceFactory
I am using GAE 1.8.4
Most likely, appengine-api.jar is missing from your war/WEB-INF/lib/ folder.
If you use Eclipse, click on the Problems tab. You may see a warning saying that this jar is not available on a server. Right click on this warning, select QuickFix, select "Copy..." option. Or copy this jar to this directory manually.
In my case the required jar was inside the WEB-INF/lib folder but the error was still occuring... I found that this error was occuring because Jetty 9 was not done yet with class loading startup process while one of my initialization class was requiring BlobstoreService:
public class InitializeAppContextListener implements ServletContextListener {
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
So I had to postpone instance variable initialization once context is fully loaded as follow:
public class InitializeAppContextListener implements ServletContextListener {
private BlobstoreService blobstoreService;
public void contextInitialized(ServletContextEvent event) {
blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Then the webapp was able to start normally again. This new behavior appeared after we had upgraded from servlet-api 2.5 to 3.1 with JDK 1.8...
I have a WAR with some JAX-RS services, deployed into TomEE Plus. Given a service annotated with #Path("myservice"), TomEE+ publishes it to localhost:8080/mywebapp/myservice.
However, that also makes accessing a JSP at localhost:8080/mywebapp/index.jsp impossible - JAXRSInInterceptor complains that No root resource matching request path has been found, Relative Path: /index.jsp.
So I would like to configure a path prefix api to all services, which changes the myservice URL to localhost:8080/mywebapp/api/myservice. Doing so would be trivial if I had configured CXF on my own (with or without Spring), because I could simply change the URL pattern of the CXF Servlet - but I am relying on the default settings where I don't configure anything besides the annotations. So how do I do that in this case?
Note that I don't want to alter the #Path annotations to include the prefix, because that does not fix the issue with the JSP.
Create an extension of javax.ws.rs.core.Application and annotate it with #ApplicationPath where value would be api in your case:
#ApplicationPath("/api")
public class MyApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
// register root resource
classes.add(MyServiceResource.class);
return classes;
}
}
This way a Servlet 3 container would find your application and map your resource to /mywebapp/api/myservice while making your web resources (.jsp) available at /mywebapp.
TomEE trunk supports these configurations: cxf.jaxrs.staticSubresourceResolution & cxf.jaxrs.static-resources-list
but the #ApplicationPath is the more relevant solution IMO
Using -Dopenejb.webservice.old-deployment=true can help too in some cases
I tried some stuff to host a little nancy test api under IIS 6:
https://github.com/NancyFx/Nancy/wiki/Hosting-nancy-with-asp.net
http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx
But it dont work. Here are my steps:
Create Empty Nancy Web Application
Add Reference with nuget - Nancy.Hosting.Aspnet Version 0.15.1
new Web.config is modifyed automatically
as described in the wiki
Add new class in solution root - HelloModule.cs
insert test code "HelloWorld"
Publish the web site local
on Windows 2003
with a virtual Directory in the IIS manager
Browsing the url 'localhost/nancyTest' brings an HTTP 403 ERROR.
A little ASP.NET WebApplication runs with the same configuration.
The nancyTest application does not have a start site like default.aspx. I want to get the request response from .../nancyTest/ coded as:
public class HelloModule : NancyModule
{
public HelloModule()
{
Get["/"] = parameters => "Hello World";
}
}
Perhaps the call .../nancyTest/ is not a GET Request? Are there other things to go in more detail?
I know not so many people user IIS6 nowadays, but there is the following solution, i wish it can help some people that still use this old one,
Config aspnet_isapi to handle a new ext files and like , .start
Set default page for this application is index.start
In nancy module add the redirect method, like the follwing:
Get["index.start"] = _ => {
return Response.AsRedirect("~/", Nancy.Responses.RedirectResponse.RedirectType.Permanent);
};
wish it helps