Using Linq to sql and server explorer, I mapped to a loginvalidation stored proc. So I write the following code:
ClientReportingDataContext db = new ClientReportingDataContext();
var data = db.ADMIN_LoginValidation(login, password);
It throws up an exception on the following line:
public ClientReportingDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["FeedsConnectionString"].ConnectionString, mappingSource)
Exception thrown:
Object reference not set to an instance of an object.
I'm calling this function from a unit test class. I cann feedsconnectionstring in web.config.
I put the web.config in the unit tests folder, and also under debug and debug/bin. Not sure what I'm missing.
Thanks in advance for any advise.
For a unit test,
ConnectionStrings["FeedsConnectionString"].ConnectionString
won't be reading from your web.config file; it will be reading from the application configuration file for the test runner. Therefore, unless you've put FeedsConnectionString in the application configuration file for your test runner,
ConnectionStrings["FeedsConnectionString"]
is null and so
ConnectionStrings["FeedsConnectionString"].ConnectionString
is going to throw a NullReferenceException.
This is why testing and application configuration files don't get along well.
You should consider the following:
public ClientReportingDataContext(string connectionString) :
base(connectionString, mappingSource)
Then inject your connection string in your test.
Related
I have a small query regarding the Spring boot logic of calling the sql files. I know that the schema sql files are called automatically if they are kept inside the resource directory of the spring boot app project.
But i would like to call them from a different directory. I have written the below code to try and achieve that but fails with below error message.
Code :
public void executeSqlScript()throws SQLException{
Connection connection = dataSource.getConnection();
connection.setAutoCommit(false);
ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("C:\\react-file-upload-master\\createConfigurationTableAndData.sql")));
connection.commit();
}
Error Message : java.io.FileNotFoundException: class path resource [C:/react-file-upload-master/createConfigurationTableAndData.sql] cannot be opened because it does not exist.
Its is not reading my directory. Would be greatfull if you could educate me on the same. Thank you.
try using FileSystemResource instead of ClassPathResource and give absolute path.
public void executeSqlScript()throws SQLException{
Connection connection = dataSource.getConnection();
connection.setAutoCommit(false);
ScriptUtils.executeSqlScript(connection, new FileSystemResource("C:\\react-file-upload-master\\createConfigurationTableAndData.sql"));
connection.commit();
}
because ClassPathResource will point to class path only. assuming your file is not in classpath.
I have a running Spring Boot project. I want to read some environment specific properties from an external properties file.
I mentioned config files names and locations while starting the server as follows:
java -jar AllergiesConditions.jar --spring.config.name=application,metadata --spring.config.location=classpath:/,/APPS/SpringBoot/
The property files loads successfully(because i tried to log one of the external key values inside datasource bean and It printed successfully) But when i try to access a value using #Value annotation - It returns null.
My test Class is as follows:
#Component
public class testclass {
private Logger logger = LogManager.getLogger(testcla.class);
#Value("${sso.server}")
public String sso;
public void test(){
logger.info("sso url is: "+sso); //This sso is logged as null
otherStuff();
}
}
This test() function is called when a particular API is hit after server is running.
The external config file - metadata.properties contains this variable:
sso.server=1234test
Edit: As suggested in this apparently duplicate question I also tried adding #PropertySource(name = "general-properties", value = { "classpath:path to your app.properties"}) in main Application configuration class and It loaded the files, but still I get null value itself.
Can someone please help in what's going wrong here?? Does the testclass need some specific annotation OR it needs to be a bean or something??
Thanks in Advance :)
Thanks to M.Deinum for great input and saving my time
Just posting his comment as answer
Factually ${sso.server} cannot be null. If ${sso.server} couldn't be resolved, my application will break at startup itself.
So the obvious problem was that I was creating a new instance of testclass in my controller using
testclass obj = new testclass(); obj.test();
Rather I should be using spring managed instance by autowiring testclass in my controller.
Is it possible to create a code-first Entity Framework model that connects to an existing database using ODP.Net without having any settings in the app.config file?
I have tried many different things.
Currently I am setting DbConfiguration:
sealed class EntityFrameworkConfiguration : DbConfiguration
{
public static readonly DbConfiguration Instance = new EntityFrameworkConfiguration();
EntityFrameworkConfiguration()
{
this.SetDefaultConnectionFactory(new OracleConnectionFactory());
this.SetProviderServices("Oracle.ManagedDataAccess.Client", EFOracleProviderServices.Instance);
}
}
DbConfiguration.SetConfiguration(EntityFrameworkConfiguration.Instance);
I am passing an OracleConnection directly into the EF context.
However, I either have problems with the SQL being generated in SQL Server format (using double-quotes around table aliases), or I get the following error:
An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.dll
Additional information: Unable to determine the provider name for provider factory of type 'Oracle.ManagedDataAccess.Client.OracleClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
Has anyone any experience of getting this to work without polluting app.config with crud?
Yes. To complete the switch from machine.config/app.config to code-based configuration, I had to also include a call to SetProviderFactory().
public sealed class EntityFrameworkConfiguration : DbConfiguration
{
public static readonly DbConfiguration Instance = new EntityFrameworkConfiguration();
public EntityFrameworkConfiguration()
{
SetDefaultConnectionFactory(new OracleConnectionFactory());
SetProviderServices("Oracle.ManagedDataAccess.Client", EFOracleProviderServices.Instance);
SetProviderFactory("Oracle.ManagedDataAccess.Client", new OracleClientFactory());
}
}
I also called DbConfiguration.SetConfiguration(EntityFrameworkConfiguration.Instance); in the startup of my application because I had DbContext's in multiple assemblies that all needed to share this configuration.
On a side note, I have also found this to be effective in allowing your application to work around the ConfigurationErrorsException: The 'DbProviderFactories' section can only appear once per config file for cases where you may not have access to repair the user's machine.config.
Uff. Found the problem.
Because I was registering column mapping using lower case the query didn't work. The column and table names must be in upper-case.
How silly.
Any unit test the includes a call to SELECT (using LINQ) data from my DBContext throws the following error:
The model backing the 'MyDBContext' context has changed since the
database was created. Either manually delete/update the database, or
call Database.SetInitializer with an IDatabaseInitializer instance.
For example, the DropCreateDatabaseIfModelChanges strategy will
automatically delete and recreate the database, and optionally seed it
with new data.
Doing a search for that specific error leads me to believe that I need to include the following line in my Global.asax Application_Start method:
System.Data.Entity.Database.SetInitializer<MyDBContext>( null );
This is suppose to fix a similar error when running the application itself. Unfortunately, I don't get this error when I run my application and there doesn't seem to be an Application_Start method for my unit test project. Is there any way to to the unit test project that I'm using a custom database back-end and to ignore any changes that have occurred in it?
I added the unit test project after working on my main project for a while so it's possible I messed it up somehow, but I can't figure out for the life of me what to do. I'm using the built in unit testing in Visual Studio 2010.
There are 2 methods that you could use with the VS unit testing framework allowing you to run some code before and after each test and before and after all the tests contained in the file
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
}
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
}
or:
// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
}
// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup()
{
}
Why in NUnit when i write :
Assert.AreEqual(ConfigurationManager.ConnectionStrings["FertigungRead"].ConnectionString , "Data Source=server511;Initial Catalog=FERTIGUNG;Persist Security Info=True");
it does not run the test and raises an error : Object reference not set to an instance of an object.
But ConfigurationManager is static class. So how can i run this test?
It is running the test - but the test is failing, because ConfigurationManager.ConnectionStrings["FertigungRead"] is returning null.
See this post about app.config files an NUnit, as that's where it'll be getting the configuration from.
However, I don't really see a test for a config file value as a valuable unit test... is this part of a more reasonable test?