Understanding and investigating CommitFailedException on MySQL - mysql

I have an Entity Framework-based application running in production.
Since a couple of days some customers are calling for random Internal Server Errors. Log files show that a simple transaction, with a single INSERT statement, is failing to commit, and that transaction is related to logging.
Let me explain better....
I have inherited a database logging feature that thanks to a controller method attribute will log every HTTP request to database to make a navigation log. Last year I have refactored the whole application from plain old multi-dialect SQL/ADO (because app runs on both MySQL and SQL Server) to Entity Framework. The application went in production and only little maintenance was required, up to major release 3.0 which is in prod for more than a month.
From yesterday, we received multiple complaints that I found related to the following exception
System.Data.Entity.Infrastructure.CommitFailedException: [non-English description] http://go.microsoft.com/fwlink/?LinkId=313468. ---> MySql.Data.MySqlClient.MySqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.TimeoutException: Timeout in IO operation
in MySql.Data.MySqlClient.TimedStream.StopTimer()
in MySql.Data.MySqlClient.TimedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
in System.IO.BufferedStream.Read(Byte[] array, Int32 offset, Int32 count)
in MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, Byte[] buffer, Int32 offset, Int32 count)
in MySql.Data.MySqlClient.MySqlStream.LoadPacket()
in MySql.Data.MySqlClient.MySqlStream.ReadPacket()
in MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
in MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
in MySql.Data.MySqlClient.MySqlDataReader.NextResult()
in MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
--- Fine della traccia dello stack dell'eccezione interna ---
in MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
in MySql.Data.MySqlClient.MySqlConnection.HandleTimeoutOrThreadAbort(Exception ex)
in MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
in MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
in MySql.Data.MySqlClient.MySqlTransaction.Commit()
in System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
--- Fine della traccia dello stack dell'eccezione interna ---
in System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
in System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.Commit(DbTransaction transaction, DbInterceptionContext interceptionContext)
in System.Data.Entity.Core.EntityClient.EntityTransaction.Commit()
in System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
in System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
in System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
in System.Data.Entity.Internal.InternalContext.SaveChanges()
in DiagnosticoSite.Data.Managers.Spring.NavigationLogManagerImpl.Insert(String aUserId, DateTime aRequestDate, String aPath, String aQuery, String aHost, String aBrowser, String aExecutionTime)
The code
Code that runs the query is extremely simple
public void Insert(string aUserId, DateTime aRequestDate, string aPath, string aQuery, string aHost, string aBrowser, string aExecutionTime)
{
using (MyContext dataContext = GetDataContext())
{
LogNavigation log = new LogNavigation
{
LN_RequestDate = aRequestDate,
LN_Path = aPath,
LN_Query = aQuery,
LN_Host = aHost,
LN_Browser = aBrowser,
LN_ExecutionTime = aExecutionTime,
LN_FK_Utenti = aUserId
};
dataContext.log_navigation.Add(log);
dataContext.SaveChanges();
}
}
GetDataContext() is a Spring lookup method that returns new MyDataContext() as a Spring prototype object.
The application is DB-heavy, in the sense that it normally runs queries that take up to minutes to complete, but those readonly queries and the log navigation queries reasonably run on different connections/transactions.
What I have tried
Currently DB timeout is very high. Following is Spring XML configuration
<object id="DataContext" singleton="false" type="MyPackage.MyDataContext, MyAssembly" >
<property name="Database.CommandTimeout" value="3600" />
<property name="Configuration.UseDatabaseNullSemantics" value="true" />
</object>
I have also tried to investigate slow-query-log without finding any INSERT
Workaround
Currently the workaround to this issue was to try-catch the logging facility and log possible exception to log4net's system log. But that is a workaround. Like when you take a painkiller instead of properly treating an inflammation I mean.
The question is
How do I investigate the root cause of such timeouts during the execution of a single-statement transaction?

Related

Mysql.Data and Azure Mysql error 'Table 'mysql.proc' doesn't exist'

When I try to execute the stored procedure against Azure MySQL version 8.0.15 server using following code I get the error saying 'Table 'mysql.proc' doesn't exist'. This error does not happen with older versions. some search says to use MySQL_upgrade but I don't get that to work against azure MySQL. How do I overcome this error? Everything works fine when I connect to local MySQL version which is same as azure hosted.
Sample code
static async Task Main(string[] args)
{
var builder = new MySqlConnectionStringBuilder
{
Server = "myserver.mysql.database.azure.com",
Database = "mydb",
UserID = "myserver#myserver",
Password = "password",
SslMode = MySqlSslMode.Prefered,
};
using (var conn = new MySqlConnection(builder.ConnectionString))
{
Console.WriteLine("Opening connection");
await conn.OpenAsync();
using (var command = conn.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "prc_myprocedure";
var reader = await command.ExecuteReaderAsync(CommandBehavior.Default);
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
}
Console.WriteLine("Closing connection");
}
Console.WriteLine("Press RETURN to exit");
Console.ReadLine();
}
}
Complete error:
Unhandled exception. MySql.Data.MySqlClient.MySqlException (0x80004005): Table 'mysql.proc' doesn't exist
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.SchemaProvider.GetProcedures(String[] restrictions)
at MySql.Data.MySqlClient.ISSchemaProvider.GetProcedures(String[] restrictions)
at MySql.Data.MySqlClient.ISSchemaProvider.GetSchemaInternal(String collection, String[] restrictions)
at MySql.Data.MySqlClient.SchemaProvider.GetSchema(String collection, String[] restrictions)
at MySql.Data.MySqlClient.MySqlConnection.GetSchemaCollection(String collectionName, String[] restrictionValues)
at MySql.Data.MySqlClient.ProcedureCache.GetProcData(MySqlConnection connection, String spName)
at MySql.Data.MySqlClient.ProcedureCache.AddNew(MySqlConnection connection, String spName)
at MySql.Data.MySqlClient.ProcedureCache.GetProcedure(MySqlConnection conn, String spName, String cacheKey)
at MySql.Data.MySqlClient.StoredProcedure.GetParameters(String procName)
at MySql.Data.MySqlClient.StoredProcedure.CheckParameters(String spName)
at MySql.Data.MySqlClient.StoredProcedure.Resolve(Boolean preparing)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at AzureMySqlExample.MySqlUpdate.Main(String[] args) in C:\Users\sammo\source\repos\ConsoleApp1\Program.cs:line 31
at AzureMySqlExample.MySqlUpdate.<Main>(String[] args)
ISSUE: You are getting the below error because when you start a connection to Azure MySQL, the gateway of Azure MySQL will first send back a greeting package with a default server version "5.6.42.0 MySQL Community Server (GPL)". This make the MySQL.Data driver treat the server version as 5.6. But actually it is 8.0 and in MySQL 8.0, the table mysql.proc not exists anymore.
Workaround: You can use ProxySQL to fix the version issue:
Set up ProxySQL for Azure MySQL
https://techcommunity.microsoft.com/t5/Azure-Database-for-MySQL/Load-balance-read-replicas-using-ProxySQL-in-Azure-Database-for/ba-p/880042
Update the server version in ProxySQL
Connecting to ProxySQL with admin account, run the following commands.
a. mysql –u admin –padmin -h 127.0.0.1 -P 6032
b. UPDATE global_variables SET variable_value='' WHERE variable_name='mysql-server_version';
c. load mysql variables to runtime;
d. save mysql variable to disk;
To complement Mike Ubezzi's answer (credit to this post to point me in the right direction), the solution was to simply change the port from 3306 to 3309 in the database connection string. More information here.
In my case, I was running an ASP.NET app linked to a MySQL database version 8.0. After editing the connection string in the web app's configuration settings and restarting the web app, my stored procedures executed as expected.

Entity Framework execute RawSql on MySQL Database

I am using EntityFramework to connect to a MySql server.
I have a method which inserts many objects in the database. For this, i am generating an SQL script, which i execute it using dbContext.Database.ExecuteSqlCommand(script) method.
This workflow works ok when the EntityFramework was connected to MS SQL Server.
Now, after i moved it to MySql, it throws error when executing the script.
Incorrect syntax near '`'.
Important
The script had been generated to match MySql syntax. If i run that script in MySQL Workbench, the query is executed successfully.
I think that EntityFramework is trying to parse the script i am sending, but in the MS SQL language.
Here is the exception Stack Trace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__58()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__57()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommand(TransactionalBehavior transactionalBehavior, String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
at AppFormApp.Domain.EntityFramework.AppFormAppDatabaseService.<InsertAllObjectsAsync>d__1.MoveNext() in F:\GitRoot\AppFormApp\AppFormApp\AppFormApp.Domain\EntityFramework\AppFormAppDatabaseService.cs:line 120
UPDATE
This is the MySQL query generated
INSERT INTO `appformapp`.`appformdata`(`Id`, `ApplicationIdentifier`, `ApplicationName`, `LastSavedDate`, `LastActivity`)
VALUES (N'59bbf577-d601-4857-aabf-84b69b2d7b75', N'APP-TMH3EI', N'Test ABV', N'2016-10-17 05:56:16', N'2016-10-17 05:56:16');
The Entity Framework is already working with MySql. The error is only triggered when using dbContext.Database.ExecuteSqlCommand(script)

Why do we get "An unexpected error occurred in Report Processing" in SSRS 2008?

We often see this kind of errors in SSRS log file. This seems like internal error happening inside SSRS engine. How can we debug this ? We are not getting any other relevant information when report fails.
library!ReportServer_0-1!2864!09/09/2016-00:28:15:: w WARN:
Microsoft.ReportingServices.ReportProcessing.ReportProcessingException:
An unexpected error occurred in Report Processing. --->
System.Threading.ThreadAbortException: Thread was being aborted. at
Microsoft.Win32.Win32Native.SetFilePointerWin32(SafeFileHandle handle,
Int32 lo, Int32* hi, Int32 origin) at
Microsoft.Win32.Win32Native.SetFilePointer(SafeFileHandle handle,
Int64 offset, SeekOrigin origin, Int32& hr) at
System.IO.FileStream.SeekCore(Int64 offset, SeekOrigin origin) at
System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin) at
Microsoft.ReportingServices.Library.PartitionFileStream.Seek(Int64
offset, SeekOrigin origin) at
Microsoft.ReportingServices.Library.MemoryUntilThresholdStream.Seek(Int64
offset, SeekOrigin origin) at
Microsoft.ReportingServices.Library.RSStream.Seek(Int64 offset,
SeekOrigin origin) at System.IO.BufferedStream.Seek(Int64 offset,
SeekOrigin origin) at
Microsoft.ReportingServices.Rendering.RPLProcessing.RPLReader.ReadElementProps(Int64
startOffset, RPLContext context, Byte& elementType) at
Microsoft.ReportingServices.Rendering.ExcelRenderer.Layout.LayoutEngine.RenderNewItem(IRowItemStruct
item, Int32 top, Int32 topRow, IExcelGenerator excel, String
pageContentKey, Dictionary2 sharedBorderCache, Dictionary2
sharedImageCache, Boolean& autosizableGrow, Boolean&
autosizableShrink) at
Microsoft.ReportingServices.Rendering.ExcelRenderer.Layout.LayoutEngine.RenderPageToExcel(IExcelGenerator
excel, String key, Dictionary2 sharedBorderCache, Dictionary2
sharedImageCache) at
Microsoft.ReportingServices.Rendering.ExcelRenderer.MainEngine.RenderRPLPage(RPLReport
report, Boolean headerInBody, Boolean suppressOutlines) at
Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer.Render(Report
report, NameValueCollection reportServerParameters,
NameValueCollection deviceInfo, NameValueCollection
clientCapabilities, Hashtable& renderProperties,
CreateAndRegisterStream createAndRegisterStream) at
Microsoft.ReportingServices.ReportProcessing.Execution.RenderReport.InvokeRenderer(IRenderingExtension
renderer, Report report, NameValueCollection reportServerParameters,
NameValueCollection deviceInfo, NameValueCollection
clientCapabilities, Hashtable& renderProperties,
CreateAndRegisterStream createAndRegisterStream) at
Microsoft.ReportingServices.ReportProcessing.Execution.RenderReport.Execute(IRenderingExtension
newRenderer) --- End of inner exception stack trace --- at
Microsoft.ReportingServices.ReportProcessing.Execution.RenderReport.Execute(IRenderingExtension
newRenderer) at
Microsoft.ReportingServices.ReportProcessing.ReportProcessing.RenderReport(DateTime
executionTimeStamp, ProcessingContext pc, RenderingContext rc,
IChunkFactory yukonCompiledDefinition) at
Microsoft.ReportingServices.Library.RenderLive.CallProcessingAndRendering(ProcessingContext
pc, RenderingContext rc, OnDemandProcessingResult& result) at
Microsoft.ReportingService
webserver!ReportServer_0-1!2864!09/09/2016-00:28:16:: e ERROR:
Throwing
Microsoft.ReportingServices.Diagnostics.Utilities.UnhandledHttpApplicationException:
,
Microsoft.ReportingServices.Diagnostics.Utilities.UnhandledHttpApplicationException:
The report server encountered an unhandled exception in
HttpApplication. ---> System.Web.HttpException: Request timed out.
--- End of inner exception stack trace ---;
--------- UPDATE ----------
I see new error in log as
library!WindowsService_0!e88!09/09/2016-17:09:45:: e ERROR: Throwing
Microsoft.ReportingServices.Diagnostics.Utilities.ReportServerStorageException:
, An error occurred within the report server database. This may be
due to a connection failure, timeout or low disk condition within the
database.; dbcleanup!WindowsService_0!e88!09/09/2016-17:09:45:: e
ERROR: Error in CleanOrphanedSnapshots:
Microsoft.ReportingServices.Diagnostics.Utilities.ReportServerStorageException:
An error occurred within the report server database. This may be due
to a connection failure, timeout or low disk condition within the
database. ---> System.Data.SqlClient.SqlException: Timeout expired.
The timeout period elapsed prior to completion of the operation or the
server is not responding.
library!WindowsService_0!e88!09/09/2016-17:09:45:: i INFO: Cleaned 0
batch records, 0 policies, 0 sessions, 0 cache entries, 0 snapshots, 0
chunks, 4 running jobs, 0 persisted streams, 0 segments, 0 segment
mappings, 0 edit sessions.
--------- UPDATE ----------
After updating all the timeout to 12hr and Put DO NOT TIMEOUT setting on SSRS site setting, we see diff error now.
So far we have checked execution log and it shows no error. Below error is found inside ssrs log file. Server has 32gb memory and we run on 64bit OS. This report sometimes is generated fine and its 200MB in size.
httpruntime!ReportServer_0-2!58dc!09/12/2016-23:26:45:: e ERROR:
Failed in BaseWorkerRequest::SendHttpResponse(bool),
exception=System.Runtime.InteropServices.COMException (0x800703E3):
The I/O operation has been aborted because of either a thread exit or
an application request. (Exception from HRESULT: 0x800703E3) at
Microsoft.ReportingServices.HostingInterfaces.IRsHttpPipeline.SendResponse(Void*
response, Boolean finalWrite, Boolean closeConn) at
ReportingServicesHttpRuntime.BaseWorkerRequest.SendHttpResponse(Boolean
finalFlush) library!ReportServer_0-2!58dc!09/12/2016-23:26:45:: e
ERROR: Throwing
Microsoft.ReportingServices.Diagnostics.Utilities.ReportServerHttpRuntimeInternalException:
RsWorkerRequest::FlushResponse.,
Microsoft.ReportingServices.Diagnostics.Utilities.ReportServerHttpRuntimeInternalException:
An internal or system error occurred in the HTTP Runtime object for
application domain ReportServer_REPCENTER_0-2-131182052998828671.
---> System.Runtime.InteropServices.COMException (0x800703E3): The I/O operation has been aborted because of either a thread exit or an
application request. (Exception from HRESULT: 0x800703E3) at
ReportingServicesHttpRuntime.BaseWorkerRequest.SendHttpResponse(Boolean
finalFlush) at
ReportingServicesHttpRuntime.RsWorkerRequest.FlushResponse(Boolean
finalFlush) --- End of inner exception stack trace ---;
Finally we have answer to this. Its the recyletime element inside "rsreportserver.config" file. By default this element value is set to 720 min (12 hr). This means from the time you start the SSRS service, it will recycle every 12 hr. Our service was started during mid night release this means it kept recycling everyday at noon. We have since update this value to 24 hr.
<RecycleTime>1440</RecycleTime>
<MaxAppDomainUnloadTime>60</MaxAppDomainUnloadTime>

Fatal error encountered during data read

I am doing a regular update table scan
Using connect1 As New MySqlConnection(ConnectLocalhost.serverString)
connect1.Open()
Dim cmd = New MySqlCommand("set net_write_timeout=99999; set net_read_timeout=99999", connect1) ' // Setting tiimeout on mysqlServer
cmd.ExecuteNonQuery()
Dim BusinessReader = selectSomeQuery("Select * from tablebusiness limit 800,10000000", connect1)
Do While BusinessReader.Read 'random exception here
Sometimes I got this error
MySql.Data.MySqlClient.MySqlException was unhandled
ErrorCode=-2147467259
Message=Fatal error encountered during data read.
Number=0
Source=MySql.Data
StackTrace:
at MySql.Data.MySqlClient.MySqlDataReader.Read()
at dreamhost.Business.InsertLocalhost() in \\work\c\business\fromwork\currentprojects\program\library\vb.net\badger.vb:line 1849
at dreamhost.Business.surFoursquare() in \\work\c\business\fromwork\currentprojects\program\library\vb.net\badger.vb:line 1939
at dreamhost.traverseweb._Lambda$__92() in \\work\c\business\fromwork\currentprojects\program\library\vb.net\traverseweb.vb:line 77
at dreamhost.buttonClicking.startAndStopClickingButton(Object sender, Action SomeSub) in \\work\c\business\fromwork\currentprojects\program\library\vb.net\buttonclicking.vb:line 45
at dreamhost.traverseweb.foursquare_Click(Object sender, EventArgs e) in \\work\c\business\fromwork\currentprojects\program\library\vb.net\traverseweb.vb:line 77
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at dreamhost.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: MySql.Data.MySqlClient.MySqlException
ErrorCode=-2147467259
Message=Reading from the stream has failed.
Number=0
Source=MySql.Data
StackTrace:
at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.FetchDataRow(Int32 statementId, Int32 columns)
at MySql.Data.MySqlClient.Driver.FetchDataRow(Int32 statementId, Int32 columns)
at MySql.Data.MySqlClient.ResultSet.GetNextRow()
at MySql.Data.MySqlClient.ResultSet.NextRow(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlDataReader.Read()
InnerException: System.IO.IOException
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=MySql.Data
StackTrace:
at MyNetworkStream.HandleOrRethrowException(Exception e)
at MyNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at MySql.Data.MySqlClient.TimedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.BufferedStream.Read(Byte[] array, Int32 offset, Int32 count)
at MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, Byte[] buffer, Int32 offset, Int32 count)
at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
InnerException: System.Net.Sockets.SocketException
ErrorCode=10054
Message=An existing connection was forcibly closed by the remote host
NativeErrorCode=10054
Source=System
StackTrace:
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
InnerException:
All I want is for the program to just "continue" when this thing happen. But that seems to be impossible. So I guess I need a way to make sure this bug doesn't happen. It happens randomly eery 800 entries or so.
Looks to me the connection is forcibly closed by remote host. In that case, I simply want to go where things left on and restart again.
There may be a lot of reasons why the connection drops (server load, network problem, etc). That your program is crashing suggests that your database code is not protected by a try statement. If you do something like this :
try
Using connect1 As New MySqlConnection(ConnectLocalhost.serverString)
connect1.Open()
Dim cmd = New MySqlCommand("set net_write_timeout=99999; _
set net_read_timeout=99999", connect1)
cmd.ExecuteNonQuery()
Dim BusinessReader = selectSomeQuery("Select *...", connect1)
Do While BusinessReader.Read
'random exception here'
'...more code'
Loop
End Using
Catch ex As Exception
' code breaks here on exception - recover from this point '
End Try
I won't go into a protracted dissertation on exception handling but there are a lot of resources out there if you have a look. How you deal with it will depend on your specific situation - whether to log the exception, record what the last successful operation was, whether to try to resume from where you were or whether to try to do the whole thing over again, notify the user, etc.
MSDN - Try/Catch/Finally

Devart "Error on executing DbCommand."

Hi i've this kind of exception using Devart. I'm calling a store procedure in MySql. The Store procedure function if i call it by DB.
using (dc = conn.GetContext())
{
result = dc.StoreProcedure(pId).FirstOrDefault();
}
return result;
[MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(7003172) t1 LIMIT 1' at line 2]
Devart.Data.MySql.bk.s() +270
Devart.Data.MySql.bk.d() +200
Devart.Data.MySql.v.a(ah[]& A_0, Int32& A_1) +134
Devart.Data.MySql.v.a(Byte[] A_0, Int32 A_1, Boolean A_2) +106
Devart.Data.MySql.a3.e() +169
Devart.Data.MySql.a3.o() +89
Devart.Data.MySql.MySqlCommand.InternalExecute(CommandBehavior behavior, IDisposable stmt, Int32 startRecord, Int32 maxRecords) +1472
Devart.Common.DbCommandBase.InternalExecute(CommandBehavior behavior, IDisposable stmt, Int32 startRecord, Int32 maxRecords, Boolean nonQuery) +48
Devart.Common.DbCommandBase.ExecuteDbDataReader(CommandBehavior behavior, Boolean nonQuery) +764
Devart.Common.DbCommandBase.ExecuteDbDataReader(CommandBehavior behavior) +38
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader() +12
Devart.Data.Linq.Provider.DataProvider.a(b A_0, Object[] A_1, Object[] A_2, Object A_3) +1436
[LinqCommandExecutionException: Error on executing DbCommand.]
Devart.Data.Linq.LinqCommandExecutionException.a(String A_0, Exception A_1) +79
Devart.Data.Linq.Provider.DataProvider.a(b A_0, Object[] A_1, Object[] A_2, Object A_3) +5349
Devart.Data.Linq.Provider.DataProvider.a(b A_0, Object[] A_1) +65
Devart.Data.Linq.Provider.DataProvider.h(Expression A_0) +189
Devart.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +53
System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +269`
Apparently, the problem is that the procedure is marked as 'pipelined' in the model. In this case, it is supposed that the procedure has a return value which is a result set. Thus, the LinqConnect runtime tries to perform a select from this result set (ending with the 'limit 1' clause because of the 'FirstOrDefault' method).
Since MySql functions cannot retrieve result sets as return values, this behaviour leads to a MySQL error. To resolve the problem, please try setting the 'Pipelined' property of this procedure to 'false'.