When is Connection object picked up and released in JdbcTemplate - spring-jdbc

I am assuming that a JdbcTemplate object while processing below method, performs:
-picks up Connection object from connection pool.
-create Statment object.
-execute sql query.
-release Connection object.
jdbcTemplateObject.queryForObject(..);
Could you please correct me.

If you check out JdbcTemplate's code
The execute() method :
-picks up Connection object from connection pool.
-create Statment object.
-execute sql query.
-release Connection object.
Method's like update, queryForObject internally call execute()

Related

How to create/simulate creation of deserialization exception when using schema registry ( in addition to brokers and zookeepers)

We are using spring-kafka-2.2.7.RELEASE to produce and consume avro messages and using schema registry for schema validation with 'FORWARD_TRANSITIVE' as the compatibility type. Now, I'm trying to use 'ErrorHandlingDeserializer2 ' from spring-kafka to handle the exception/error when a deserializer fails to deserialize a message. Now I'm trying to write a component test to test this configuration. My component test expected to have below steps.
Spin up a local kafka cluster using docker containers
Send an avro message (using KafkaTemplate) with invalid schema to re-create/simulate the deserialization exception onto a test topic
Now what's happening is, since we have schema registry in place, if i send a message with new schema (invalid schema) it's validating the schema as per the compatibility type setting we have and not letting me producer the message onto kafka by throwing an exception at the producer level itself.
Now my question is, In this scenario, how can I create/simulate the creation of deserialization exception to test my configuration. Please suggest.
Note:- I don't want to disable/stop schema registry because that wouldn't simulate our prod setup.

Entity Framework Core: How to get the Connection from the DbContext?

I am trying the new Entity Framework Core with MySQL Connector.
I can get a valid DbContext and write into the database so everything has been setup correctly.
I need to get the Connection from the DbContext because I have to test for it at application starting using a connection.Open() inside a try statement. If there is not a valid connection, the console app should try to start MySQL Server and retry.
How can I get the Connection from the DbContext?
Before EF6 by context.Connection. After EF6 by context.Database.Connection.
It seems the latest has been removed too from EFCore.
The Microsoft.EntityFrameworkCore.Relational (https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Relational/) package provides extension methods for this - you can use dbContext.Database.OpenConnection() or dbContext.Database.GetDbConnection() to get the DbConnection object.
Note: if you have Microsoft.EntityFrameworkCore.SqlServer installed then you don't have to explicitly install this package
You can do the following :
If you are using System.Data.SqlClient change it to Microsoft.Data.SqlCLient since the later library will accept excplicit casting from the object of the DBContext in both EntityFramework and EntityFrameWorkCore.
Create a command from the DBContext connection and Cast it to your SQLCommand by
using (SqlCommand cmd = (SqlCommand)database.GetDbConnection().CreateCommand())
Check the connection state and open it if necessary.
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
If there is a transaction in the DBContext add it to the command.
if (database.CurrentTransaction != null)
{
cmd.Transaction = database.CurrentTransaction.GetDbTransaction();
}
By doing this you will avoid any problems can appear when using comands outside the context.

Is restarting host instance mandatory while changing the stored procedures?

In BizTalk 2010, I am using the SQL Adapter for polling a table to create a message and to initiate the orchestration process.
I have modified the stored procedure without changing the schema. But i have started getting errors after modifying it and SQL polling is not happening. So i have restarted the Host instance and it started working.
So here my question is Is restarting host instance mandatory after changing the stored procedures?
Error is "The adapter "WCF-Custom" raised an error message. Details "Microsoft.ServiceModel.Channels.Common.AdapterException: The ResultSet returned as part of the Typed Stored Procedure or Typed Polling invocation did not match the metadata available. If this Stored Procedure or Polling Statement can return a variable number of result sets, consider using the un-typed Stored Procedure or un-typed Polling operation instead."
Can anyone please suggest what could be the root cause?
Thanks,
Sasikumar.S
Yes, you will need to restart the Host Instance of the Host configured for your WCF-SQL Handler.
Under the hood, the first time a particular Stored Proc is called, the WCF-SQL adapter first executes it with the SET FMTONLY ON; flag. This causes Sql Server to return just the datatypes of the expected data, but not execute the sproc itself. The adapter caches these datatypes for the lifetime of the host process.
If you change the data returned by the stored procedure, the next time it executes, it will be out of sync, and unable to coerce into the expected type. Hence, the need to restart the Host Instance(s).
TL;DR - If you change a stored procedure, you need to restart the WCF-SQL Host Instance.

ASP.NET retrieving data from nowhere

I am going through ASP.NET MVC 3 tutorial. Got to the point where EnityFramework was used for model classes. I ran the the application without having connection strings in the web.config specified and it worked.
I could add, edit, delete records. And the weirdest thing is that they are sill there even after I stop development server and start debugging application again as if table was created somewhere in memory and stayed alive for some reason. Can anybody explain what was going on?
Here's a link to an image:
oi48.tinypic.com/fnbeba.jpg
Was it supposed to use the the connection string for which name matches the name of the class derived from DbContext?
EDIT1:
Because I had no connection string in web.config it was generated by Enity Framework using namespace and the name of the class derived from DBContext. By default EF uses SQL Express, hence database file was created in database server's DATA direcotry C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA.
The last thing I don't understand why it wouldn't create the database file in App_Data dir if DBContext derived class is
public class MoviesDBContex : DbContext
{
public DbSet<Movie> Movies { get; set; }
// Passing name of the connections string shouldn't be even necessary
public MoviesDBContex()
: base("MoviesDBContex")
{ }
}
and web.config contains
<connectionStrings>
<add name="MoviesDBContext"
connectionString="Data Source=|DataDirectory|Movies.sdf"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Thist what the Microsoft guide about ER connections and models (msdn.microsoft.com/en-us/data/jj592674.aspx) says:
If the name of the connection string matches the name of your context (either with or without namespace qualification) then it will be found by DbContext when the parameterless constructor is used. If the connection string name is different from the name of your context then you can tell DbContext to use this connection in Code First mode by passing the connection string name to the DbContext constructor.
Any idea why database file isn't created in App_Data?
EDIT2:
There was a missing 't' in the class name and hence it didn't match the name of the connection string.
I does work as expected when provider is SQL Server Compact providerName="System.Data.SqlServerCe.4.0", but if I change it to providerName="System.Data.SqlClient" I get an exception added below. Shouldn't regular SQL Server be able to create a database file also?
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Do you have SQL Express installed on your machine? Which version of Entity Framework are you using? As long as I know the Entity Framework targets the local SQL Express as its default connection string if no string connection is provided.
I believe it is using SQL Server express, writing the DB files to the app_data directory within your application.
This is called "Convention over configuration", and Entity Framework and MVC use this principle a lot. Basically, it says that unless you give it specific instructions otherwise, they will assume various conventions.
If you don't supply a connection string to EF, then it will use a default connection string, generated from the namespeace and name of the class. If that doesn't exist in your web.config, then it will use the DefaultConnection that is defined in the machine.config located in the folder tree at C:\Windows\Microsoft.NET

How to avoid DTC when using PersistenceIOParticipant in WF4.0?

I am using PersistenceIOParticipant in WF4.0 to save something into database together with the persistence of the workflow instance. I have no idea that how to use the same connection object with the workflow persistence and I am forced to use the distributed transaction. Are there any ways to avoid using DTC?
I found the WF4 Sample project "WorkflowApplication ReadLine Host" useful
to see an example of persistenceIOParticipant in action.
I toggled the booleans in the constructor to verify that a transaction was being used and that
MSDTC was required.
See http://msdn.microsoft.com/en-us/library/dd764467.aspx
If using SQL Server 2008+, then it shouldn't matter if multiple connections are required. After using reflector on the SqlWorkflowInstanceStore, I discovered it was setting some additional properties on the connection string. Here is the code it uses to create a connection string:
SqlConnectionStringBuilder builder2 = new SqlConnectionStringBuilder(connectionString);
builder2.AsynchronousProcessing = true;
builder2.ConnectTimeout = (int)TimeSpan.FromSeconds(15.0).TotalSeconds;
builder2.ApplicationName = "DefaultPool";
SqlConnectionStringBuilder builder = builder2;
return builder.ToString();
I verified with profiler that MSDTC is not involved when using a custom IO participant and this connection string code. Don't forget to pass true to the base PersistenceIOParticipant constructor and flow Transaction.Current appropriately. Obviously, Microsoft could change that at anytime so use at your own discretion.

Resources