asp.net Enterprise Library, All connections in use (closed) - asp.net

im using the asp.net Enterprise Library to insert and update data to an sql database.
c# code:
Database db = DatabaseFactory.CreateDatabase();
IDbConnection connection = db.GetConnection();
connection.Open();
IDbTransaction transaction = connection.BeginTransaction();
DBCommandWrapper command;
try
{
//insert part
command = db.GetStoredProcCommandWrapper("stored_procedure1");
command.CommandTimeout = 900;
command.AddInParameter("#parameter1", DbType.Int32, 3);
db.ExecuteNonQuery(command, transaction);
//update part
command = db.GetStoredProcCommandWrapper("stored_procedure2");
command.CommandTimeout = 900;
command.AddInParameter("#param1", DbType.Int32, 5);
db.ExecuteNonQuery(command, transaction);
transaction.Commit();
}
catch (SqlException e)
{
transaction.Rollback();
throw (new ApplicationException("sql error", e));
}
catch (Exception e)
{
transaction.Rollback();
throw (new ApplicationException("error", e));
}
finally
{
connection.Close();
}
the code is on a method.
The method is executed many times and sometimes im getting error:
"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached."
My questions are: Is it ok to have the insert and update part together as it is above?
Having the insert and update part together is causing this error?
Thanks.

First you do not roll back your transaction on error.
Secondly in order to guarantee that your finally block is called you need to add the catch block.
Try {
...
}
Catch {
}
finally {
close connection
}
Read the second paragraph of the link located below
http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.100).aspx

Related

SQL Error executing INSERT: [SQLITE_BUSY] The database file is locked

I am using sqlite as db in my Micronaut application getting the sqlite busy error in the below code:
#SneakyThrows
#TransactionalAdvice(value = EmpDao.DATASOURCE, propagation = TransactionDefinition.Propagation.REQUIRES_NEW)
public void storeEmp(EmpDto empDto) {
String id = empDto.getId();
try {
if (empDao.existsById(id)) {
log.debug("updating emp for id {}", empDto.getId());
empDao.update(EmpEntity.builder()
.id(id)
.data(getJson(empDto))
.entryCreatedAt(timeService.nowDateTime().toEpochSecond(ZoneOffset.UTC))
.build());
} else {
empDao.save(
EmpEntity.builder()
.id(id)
.data(getJson(empDto))
.entryCreatedAt(timeService.nowDateTime().toEpochSecond(ZoneOffset.UTC))
.build());
}
}catch(Exception e){
log.error("emp db save/update failed for id {} ",id, e);
}
}
#SneakyThrows
#TransactionalAdvice(value = EmpDao.DATASOURCE, propagation = TransactionDefinition.Propagation.REQUIRES_NEW)
public void storeEmployees(List<Emp> empDtos) {
try {
empDao.saveAll(empDto);
} catch (Exception ex) {
log.warn("saveAll failed", ex);
empDtos.forEach(this::storeEmp);
}
}
In stacktrace I can see first saveAll getting failed becuase of Primary keyconstraint Issue, that might be because of duplicate emp ids in the list
SQL error executing INSERT: [SQLITE_CONSTRAINT_PRIMARYKEY] A PRIMARY KEY constraint failed
and After that when It tried to save/update each emp object independently through storeEmp method in forEach, it's failing with the sqlite busy exception.
What I am not sure if saveAll is already failed, how there can be multiple connection to sqlite. Can anyone suggest what's wrong with the above code.
Thanks

sqlite jdbc setJournalMode

I running my first trials on SQLite (with JDBC) as pure memory database. As I need very fast inserts I tried to set the config accordingly. I could find out that the code below fails only at the setting for JournalMode. Please refer to the method shown below. The variables con and isConnected are defined as class vars and not shown here.
Thanks a lot
Rolf
public Boolean connect() {
try {
Class.forName("org.sqlite.JDBC"); // sqlitejdbc_3.7.2
// Set all pragmas
SQLiteConfig config = new SQLiteConfig();
// This statement (JournalMode setting) causes a fail
// Without that statement the connection can be established
// ==> java.sql.BatchUpdateException: batch entry 0: query returns results
config.setJournalMode(JournalMode.MEMORY);
config.setTempStore(TempStore.MEMORY);
config.setSynchronous(SynchronousMode.OFF);
config.enforceForeignKeys(false);
config.enableCountChanges(false);
con = DriverManager.getConnection("jdbc:sqlite::memory:", config.toProperties());
isConnected = true ;
return true ;
}
catch (Exception e) {
LogMessages.instance().print(0, LogMessages.MSG_SEVERITY.ERROR, e.getMessage() + "\n");
e.printStackTrace() ;
return false ;
}
}
I have the same issue, but there is an other way to disable it. After opening the connection you can execute this query :
PRAGMA journal_mode=MEMORY;

Reading from HttpContext.Current.Session fails on multi server environment

Environment: IIS 7.5, .Net 4.0
I have a problem reading from HttpContext.Current.Session on a multi server environment.
First in my code I store an object in HttpContext.Current.Session an later try to read it again. The read (performed a number of times) fails randomly and I suspect it has something to do with what server the call hits. The storing and reading of the object is done through ajax calls and a colleague told me to store the object in Page_Load. I was fairly skeptic and as it turns out the problem has not been solved using this approach.
Storing:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Stream GetHierarchy(string invId, string zoomLevel)
{
Hierarchy hierarchy = new Hierarchy();
try
{
hierarchy = businessLogic.GetHierarchy(invId);
HttpContext.Current.Session["hierarchy"] = hierarchy;
}
catch (Exception ex)
{
throw ex;
}
return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(hierarchy)));
}
Reading:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Stream GetCustomer(string invId, string includeDetails, string zoomLevel)
{
Hierarchy hierarchy = (Hierarchy)HttpContext.Current.Session["hierarchy"];
Customers customers = null;
Customer customer = null;
if (hierarchy != null) {
customers = hierarchy.Customers;
if (customers != null)
{
try
{
customer = (from e in customers.DiagramCustomers where e.InvId == invId select e).ToList()[0];
}
catch (Exception ex)
{
}
}
}
return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(customer)));
}
Everything is working just fine in a single server environment...
Can anyone shed some light over what kind of problem it is I'm facing here? And preferably how to solve it :-)
./CJ
Use Sql Server to Store Asp.NET Session State
http://support.microsoft.com/kb/317604

Error at login in Asp .Net and MySQL

I am trying to connect to a database on an sql server in asp .net.
Here is a part of the code:
try
{
connection = new SqlConnection();
if(connection != null)
try
{
connection.ConnectionString = "Data Source=127.0.0.1,3306;Initial Catalog=MyPlace;User ID=root;Password=student";
connection.Open();
cmd = new SqlCommand(sqlQuery, connection);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
String s1 = (String)rdr["id"];
Response.Redirect(s1);
// Operate on fetched data
}
}
catch (Exception exc) { Response.Output.Write(exc.Message); }
}
catch(Exception ex)
{
Response.Output.Write(ex.Message);
}
finally
{
if (cmd != null)
cmd.Dispose();
if (connection != null)
connection.Close();
if (rdr != null)
rdr.Dispose();
}
The error I receive is :
A connection was successfully established with the server, but then an error occurred during the login process. (provider:TCP Provider, error:0 - An existing connection was forcibly closed by the remote host)
Any ideas why this might happen? I've already gone through the basic troubleshooting steps, but nothing seems to help...
Could be a number of things but start with the simplest which would be to verify that your MySql database is allowing connections. yes it seems silly, but we recently ran in to a case where an application wasn't behaving and part of the problem was the way the MySql users were configured which limited where they could connect from and what they could do once connected.
Assuming you can connect locally through the sql tools, and since you are running on the default port try this connect string instead of the one you are using
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Also make sure there aren't any conflicts with the MySql connectors on your box.

ajax with WCF work. but few miniute after, doesn't work

I am a new to WCF. I have written ajax to use a web service before, but on this project I am trying to use ajax to WCF.
After I build the project and wcf using ajax, I receive the return successfully. But, 10 or more minutes later I don't get a return, the ajax calls the error function, and the fiddler returns nothing.
If I rebuild the project without any source modifying, I receive the return successfully again.
Is their anybody who has experienced this or knows why this might be?
Thank You.
Most likely you're not closing the connections. You should wrap all your calls in Try/Catch/Finally blocks.
In C#:
ServiceClient service = GetService();
try
{
SomeRequest request = new SomeRequest();
SomeResponse response = service.GetSome(request);
return response.Result;
}
catch (Exception ex)
{
// do some error handling
}
finally
{
try
{
if (service.State != CommunicationState.Faulted)
{
service.Close();
}
}
catch (Exception ex)
{
service.Abort();
}
}
or VB
Dim service As ServiceClient = GetService()
Try
Dim request As New SomeRequest()
Dim response As SomeResponse = service.GetSome(request)
Return response.Result
Catch ex As Exception
' do some error handling
Finally
Try
If service.State <> CommunicationState.Faulted Then
service.Close()
End If
Catch ex As Exception
service.Abort()
End Try
End Try
Here is the best practice for calling WCF services:
public static void CallService<T>(Action<T> action) where T
: class, ICommunicationObject, new()
{
var client = new T();
try
{
action(client);
client.Close();
}
finally
{
if (client.State == CommunicationState.Opened)
{
try
{
client.Close();
}
catch (CommunicationObjectFaultedException)
{
client.Abort();
}
catch (TimeoutException)
{
client.Abort();
}
}
if (client.State != CommunicationState.Closed)
{
client.Abort();
}
}
}
Each WCF call should create a new instance of your service class. This code allows you to enforce that and just call the services like this:
CallService<MyService>( t => t.CallMyService());

Resources