Dapper Error: "System.InvalidOperationException: 'The ConnectionString property has not been initialized.'" - dapper

I'm following a course on how to use Dapper however I've come across an error I'm unable to find a solution for.
The error being "System.InvalidOperationException: 'The ConnectionString property has not been initialized.'"
I've done some debugging and have noticed that when my initialize function reads from the appsettings.json file, nothing seems to be available within the "config" variable that is returned.
This also seems to be the case for when the function CreateRepository is called after, a null string is being sent to the repository.
Would appreciate if someone can see what seems to be wrong?
Initialize - object of 0 options returned to config
private static void Initialize()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config = builder.Build();
}
Contact Repository - when setting a breakpoint in ContactRepository - the parameter passed is null
private static ContactRepository CreateRepository()
{
return new ContactRepository(config.GetConnectionString("DefaultConnection"));
}
App Settings
{
"ConnectionStrings": {
"DefaultConnection": "server=.\\SQLEXPRESS2014;database=ContactsDB;Trusted_Connection=Yes;"
}
}

The issue seemed to have been that the "AppSettings.json" file wasn't being added to the location where builder.SetBasePath was hence why it was returning null. A manual copy and paste of the file fixed the issue

Related

kotlin.KotlinNullPointerException while accessing Data from local Room Database?

I am new into Kotlin and trying to learn, how to fetch Data with retrofit and store this data into a Room DB. But as soon as i start the Activity where this process takes place i get a NullPointerException.
EDIT: As far as i could find out now, my "database" in the RoomViewmodel class is still NULL when i want to access it, even though i have an override oncreate function, where it is created
Here is also a link to the GitHub repository from the mini-project I'm working on: https://github.com/Engin92/Dog_Breeds/tree/RoomDatabase
here is my complete errorlist:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dogbreeds, PID: 14803
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dogbreeds/com.example.Breedlist.activity.DetailedViewActivity}: kotlin.KotlinNullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: kotlin.KotlinNullPointerException
at com.example.Breedlist.activity.DetailedViewActivityRepository.getBreeds(DetailedViewActivityRepository.kt:23)
at com.example.Breedlist.activity.DetailedViewActivityViewModel.getAllBreedList(DetailedViewActivityViewModel.kt:23)
at com.example.Breedlist.activity.DetailedViewActivity.onCreate(DetailedViewActivity.kt:42)
at android.app.Activity.performCreate(Activity.java:8086)
at android.app.Activity.performCreate(Activity.java:8074)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3755)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:213) 
at android.app.ActivityThread.main(ActivityThread.java:8178) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101) 
The important part of DetailedViewActivity
class DetailedViewActivity : AppCompatActivity() {
lateinit var breedRecyclerView: RecyclerView
lateinit var detailedViewActivityViewModel: DetailedViewActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detailed_view)
breedRecyclerView = findViewById(R.id.breedRecyclerView)
detailedViewActivityViewModel = ViewModelProviders.of(this).get(
DetailedViewActivityViewModel::class.java)
if(isOnline(this))
{
detailedViewActivityViewModel.getBreedsFromAPIAndStore()
}
else
{
Toast.makeText(this,"No internet connection. Showing cached list!",Toast.LENGTH_LONG).show()
}
detailedViewActivityViewModel.getAllBreedList().observe(this, Observer<List<CurrentBreedResponseItem>> { breedList ->
Log.e(MainActivity::class.java.simpleName,breedList.toString())
setUpBreedRecyclerView(breedList!!)
})
} ....
the class RoomViewModel, where i build the DB (where i Think the error is, the var database is still NULL, after trying to access (write/read) it)
class RoomViewModel : Application() {
companion object {
var database: BreedDatabase? = null
}
override fun onCreate() {
super.onCreate()
database = Room.databaseBuilder(applicationContext, BreedDatabase::class.java, "breed_db").fallbackToDestructiveMigration().build()
}
}
getBreeds function in DetailedViewActivityRepository:
fun getBreeds() : LiveData<List<CurrentBreedResponseItem>>
{
return RoomViewModel.database!!.currentBreedDao().getAllBreeds()
}
getAllBreedList function in DetailedViewActivityViewModel
fun getAllBreedList(): LiveData<List<CurrentBreedResponseItem>>
{
return detailedViewActivityRepository.getBreeds()
}
There are two problem in your code. The first one is very clear you are trying to access a null object and you are getting NullPointerException. So be careful when you use !! operator.
The reason you are getting it is, inside your RoomViewModel your database instance is null.
class RoomViewModel : Application() {
companion object {
var database: BreedDatabase? = null
}
override fun onCreate() {
super.onCreate()
database = Room.databaseBuilder(applicationContext, BreedDatabase::class.java, "breed_db")
.fallbackToDestructiveMigration().build()
}
}
You may think you are initializing the database instance in onCreate() but the onCreate() is not getting called. The reason is to make the application class work you need to add it to your AndroidManifest.xml file.
Solution:
Add this RoomViewModel class to your AndroidManifest.xml file like this.
<application
android:name=".view.RoomViewModel"
android:allowBackup="true"
We do it as application tag's name attribute as you can see above.
This will fix your null pointer exception. But your program will again crash, because you are using Kotlin and do make room work with kotlin this thing needs to be added in your app level build.gradle file.
kapt "android.arch.persistence.room:compiler:1.1.1"
After adding it to your app level build.gradle inside dependencies block. Sync your project and run it should work.
If you want to learn more about Room Database in Android, you can check this Room Database Tutorial.
Hope this will help you.

Hystrix Javanica : Call always returning result from fallback method.(java web app without spring)

I am trying to integrate Hystrix javanica into my existing java EJB web application and facing 2 issues with running it.
When I try to invoke following service it always returns response from fallback method and I see that the Throwable object in fallback method has "com.netflix.hystrix.exception.HystrixTimeoutException" exception.
Each time this service is triggered, HystrixCommad and fallback methods are called multiple times around 50 times.
Can anyone suggest me with any inputs? Am I missing any configuration?
I am including following libraries in my project.
project libraries
I have setup my aspect file as follows:
<aspectj>
<weaver options="-verbose -showWeaveInfo"></weaver>
<aspects>
<aspect name="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
</aspects>
</aspectj>
Here is my config.properties file in META-INF/config.properties
hystrix.command.default.execution.timeout.enabled=false
Here is my rest service file
#Path("/hystrix")
public class HystrixService {
#GET
#Path("clusterName")
#Produces({ MediaType.APPLICATION_JSON })
public Response getClusterName(#QueryParam("id") int id) {
ClusterCmdBean clusterCmdBean = new ClusterCmdBean();
String result = clusterCmdBean.getClusterNameForId(id);
return Response.ok(result).build();
}
}
Here is my bean class
public class ClusterCmdBean {
#HystrixCommand(groupKey = "ClusterCmdBeanGroup", commandKey = "getClusterNameForId", fallbackMethod = "defaultClusterName")
public String getClusterNameForId(int id) {
if (id > 0) {
return "cluster"+id;
} else {
throw new RuntimeException("command failed");
}
}
public String defaultClusterName(int id, Throwable e) {
return "No cluster - returned from fallback:" + e.getMessage();
}
}
Thanks for the help.
If you want to ensure you are setting the property, you can do that explicitly in the circuit annotation itself:
#HystrixCommand(commandProperties = {
#HystrixProperty(name = "execution.timeout.enabled", value = "false")
})
I would only recommend this for debugging purposes though.
Something that jumps out to me is that Javanica uses AspectJ AOP, which I have never seen work with new MyBean() before. I've always have to use #Autowired with Spring or similar to allow proxying. This could well just be something that is new to me though.
If you set a breakpoint inside the getClusterNameForId can you see in the stack trace that its being called via reflection (which it should be AFAIK)?
Note you can remove commandKey as this will default to the method name. Personally I would also remove groupKey and let it default to the class name.

Can't connect to SQL 2008 database using .NET Core 2.0

UPDATE
I could never make this work with a "Windows Authentication" (domain) user. But with a "SQL Server Authentication" user everything is working like it's supposed to.
ORIGINAL QUESTION
My connectionString: Server=ip;Database=dbname;User Id=xxx\user;Password=pass;
The connection string is located in appsettings.json like this:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"ConnectionString": "Server=ip;Database=dbname;User Id=xxx\user;Password=pass;"
}
}
Then i pass it to a static class from the "Startup.cs" file, like this:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
Orm.DatabaseConnection.ConnectionString = Configuration["ConnectionStrings:ConnectionString"];
}
This is where I initiate the connection:
using System.Data.SqlClient;
namespace MyProject.Orm
{
public static class DatabaseConnection
{
public static string ConnectionString { get; set; }
public static SqlConnection ConnectionFactory()
{
return new SqlConnection(ConnectionString);
}
}
}
And this is my controller:
public string Get()
{
using (var databaseConnection = Orm.DatabaseConnection.ConnectionFactory())
{
var sections = databaseConnection.Query("SELECT * FROM myTable").ToList();
return sections.ToString();
}
}
Where this line:
var databaseConnection = Orm.DatabaseConnection.ConnectionFactory();
returns:
ServerVersion: "'databaseConnection.ServerVersion' threw an exception of type 'System.InvalidOperationException'"
Message: "Invalid operation. The connection is closed."
Source: "System.Data.SqlClient"
StackTrace: "at
System.Data.SqlClient.SqlConnection.GetOpenTdsConnection()\n
at
System.Data.SqlClient.SqlConnection.get_ServerVersion()"
And i get this error on new SqlConnection: "error CS0119: 'SqlConnection' is a type, which is not valid in the given context".
But the program execution doesn't stop because of these errors.
The application then hangs on the following line:
var sections = databaseConnection.Query("SELECT * FROM myTable").ToList();
I'm using Dapper as my ORM (not EntityFramework). In "myTable" sql table are only 17 rows and 5 columns so it should load fast.
I tried all kinds of different connectionStrings but it always fails. If i try the same with .NET Framework 4.5, everything works fine. The problem is .NET Core 2.0.
Any idea about fixing it is welcome. Because i spent too many hours on this already.
Try to add databaseConnection.Open().
public string Get()
{
using (var databaseConnection = new SqlConnection(#"Server=ip;Database=dbname;User Id=xxx\user;Password=pass;Pooling=false;"))
{
databaseConnection.Open();
var sections = databaseConnection.Query("SELECT * FROM myTable").ToList();
return sections.ToString();
}
}
To avoid problems with connection pool that described in comments you add Pooling=false; to connection string:
Server=ip;Database=dbname;User Id=xxx\user;Password=pass;Pooling=false;
Edit:
I hardcoded connection string and removed factory to make example smaller
Try creating a self-contained deployment, this should eliminate and strange dependency stuff. If it works then at least you know that it's due to some assembly binding type stuff.
The exception "error CS0119: 'SqlConnection' is a type, which is not valid in the given context" smells like it is.

java.lang.NullPointerException: null value in entry: url=null Selenium Webdriver

I am trying the following simple code, which works as per expectation on my localmachine
public class NewTest
{
#Test
public void f() throws IOException
{
Properties obj = new Properties();
FileInputStream fileobj = new FileInputStream("C:\\selenium_Automation\\data_links.properties");
obj.load(fileobj);
System.setProperty("webdriver.chrome.driver", "c:\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(obj.getProperty("crm_url"));
System.out.println("Complete");
}
}
but when i try the same code on a different machine i get the following
FAILED: f
java.lang.NullPointerException: null value in entry: url=null
at com.google.common.collect.CollectPreconditions.checkEntryNotNull(CollectPreconditions.java:33)
at com.google.common.collect.SingletonImmutableBiMap.<init>(SingletonImmutableBiMap.java:39)
at com.google.common.collect.ImmutableBiMap.of(ImmutableBiMap.java:57)
at com.google.common.collect.ImmutableMap.of(ImmutableMap.java:80)
at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:306)
The code works fine if i replace (obj.getProperty("crm_url")) with the actual URL, but i have several different links stored in the properties file and i need them to be read from that place. What i am doing wrong can some please tell me the reason behind the NUll pointer expection for the URL
This is the error you get when you try to add a null object to an immutable map in the google common library. My guess would be that the org.openqa.selenium.remote.RemoteWebDriver.get is attempting to find do that and your file path is null or something similar. I would check the url but that is only a guess.
If I had to guess, I would say that the location of your properties file is different on the other machine.
The issue here I can assume is that the url you are using in the properties file must be wrong or it might have the inverted commas. If it has the inverted commas i.e
url="https://www.google.com" then remove it.
Even I had faced this issue. I deleted the target folder before running the code and my issue was resolved.

Bootstrapping NancyFX with RavenDB

I am trying to add bootstrap NancyFX with RavenDB and I am running into the following error trying to run the application...
"Unable to resolve type: Nancy.IResponseFormatter"
Environment:
ASP.Net
Nancy
Nancy.Hosting.Aspnet
RavenDB
VS2010 DevelopmentServer
In lieu of pasting all of the code, here is a link to the site that I used as an example. By example, I mean I copied it verbatim to see if I could get it to work.
http://stuff-for-geeks.com/category/NancyFx.aspx
I have actually seen this code run in a demo before, but I for some reason can not get it to run at all. It fails at start up. It is almost as if Nancy is not using my BootStrapper.
More of the Stack Trace:
[TypeInitializationException: The type initializer for 'Nancy.Hosting.Aspnet.NancyHttpRequestHandler' threw an exception.]
Nancy.Hosting.Aspnet.NancyHttpRequestHandler..ctor() +0
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
Any help would be really appreciated.
That code is based on an older version of Nancy. You should be looking at using the IResponseFormatterFactory instead. The custom module builder, that is defined in the blog post, is based on an old copy of the DefaultNancyModuleBuilder and if you have a look at the current version https://github.com/NancyFx/Nancy/blob/master/src/Nancy/Routing/DefaultNancyModuleBuilder.cs you should be able to make the necessary adjustments
Here is the code for the RavenAwareModuleBuilder class under discussion:
Edit 1
The code below has been updated for Nancy Release 0.12. Note the new NegotiationContext lines in BuildModule method.
public class RavenAwareModuleBuilder : INancyModuleBuilder
{
private readonly IViewFactory viewFactory;
private readonly IResponseFormatterFactory responseFormatterFactory;
private readonly IModelBinderLocator modelBinderLocator;
private readonly IModelValidatorLocator validatorLocator;
private readonly IRavenSessionProvider ravenSessionProvider;
public RavenAwareModuleBuilder(IViewFactory viewFactory, IResponseFormatterFactory responseFormatterFactory, IModelBinderLocator modelBinderLocator, IModelValidatorLocator validatorLocator, IRavenSessionProvider ravenSessionProvider)
{
this.viewFactory = viewFactory;
this.responseFormatterFactory = responseFormatterFactory;
this.modelBinderLocator = modelBinderLocator;
this.validatorLocator = validatorLocator;
this.ravenSessionProvider = ravenSessionProvider;
}
public NancyModule BuildModule(NancyModule module, NancyContext context)
{
context.NegotiationContext = new NegotiationContext
{
ModuleName = module.GetModuleName(),
ModulePath = module.ModulePath,
};
module.Context = context;
module.Response = this.responseFormatterFactory.Create(context);
module.ViewFactory = this.viewFactory;
module.ModelBinderLocator = this.modelBinderLocator;
module.ValidatorLocator = this.validatorLocator;
context.Items.Add(
"IDocumentSession",
ravenSessionProvider.GetSession()
);
module.After.AddItemToStartOfPipeline(ctx =>
{
var session = ctx.Items["IDocumentSession"] as IDocumentSession;
if (session != null) session.Dispose();
});
return module;
}
}

Resources