I am running a service that does some computation and communicates with an ms sql server every minute or so (24/7, uptime is very important) and writes to error log if anything funny happens (like a timeout or lost connection).
This works great, however once in a while I will get this error:
Arithmetic operation resulted in an overflow.
Since this is run on client’s side, and the exception has only occurred 3 times since the project has been launched (a couple of months now) this would be extremely hard to catch and debug.
I am using OleDbDataAdapter to communicate with the server. The data being received from the server was not special in any way, that I am aware of at least! Data should never exceed field sizes etc, so I can’t really think of a reason for this error to occur. Again this is extremly hard to verify since I all I get is the error message.
My question is: Why does this error usually accrue? I have been unable to find any real information about it on the web, so if someone could supply me with some information, that would be very much appreciated.
Thank you!
EDIT: A careful read through the error report showed me that this error has actually occurred during the Fill of DataTable object. Code looks something like this:
DataTable.Clear();
try
{
oledbdataAdapter.Fill(DataTable, sqlString);
}
catch (Exception e)
{
//error has occured, report
}
Can anyone make sense of this?
EDIT2: I have just thought of this … Is it possible this exception would be thrown because the system doesn’t have enough system resources to complete the Fill? This is the only reason I can think of that would explain the exception occurring. It would also explain why it only occurs on some servers and never occurs on dev server …
EDIT3: Here is the whole exception in case it gives anyone any more insight:
System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Data.DataTable.InsertRow(DataRow row, Int32 proposedID, Int32 pos, Boolean fireEvent)
at System.Data.DataTable.LoadDataRow(Object[] values, Boolean fAcceptChanges)
at System.Data.ProviderBase.SchemaMapping.LoadDataRow()
at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping)
at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
at System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
at INDAZajemService.INDAZajem.FillDataSet()
Previously used ASP.Net with VS2013 with SQL database connection to REMOTE database — and thought that I’d mastered how to create SQL-based web apps…until I tried the new ASP.Net Core with VS2015. Tried installing VS2015 Pro and followed PluralSight training
for creating simple Visual C# project «ASP.NET Core Web Application (.NET Core)» — failed! Tried simple code example from other wbesites — also failed. Tried Microsoft’s own example here:
https://docs.asp.net/en/latest/data/ef-mvc/intro.html — also failed. The failures seem to occur when creating the initial database.
Failed error: «Arithmetic operation resulted in an overflow«
I am using Windows 10 Enrterprise (64 bit) clean install. Other software includes Office 2016 (32 bit) | Visio 2016 (32 bit).
I have tried uninstalling any reference to «SQL» from the add/remove programs, and re-installed VS2015. Same problem.
Can anyone shed light on this problem? It’s inhibiting me from learning how to develop the most basic of we apps!
Every «EF» project sample I try gives the same error: «Arithmetic operation resulted in an overflow». In the case of the above Micrsoft sample, I got as far as section «Create a controller and views», but when I click «Add»
(to add a new scaffolded item) I get the following exception (image attached): [trace posted below]
C:Program Filesdotnetdotnet.exe aspnet-codegenerator --project "C:UsersVirgilTurnerdocumentsvisual studio 2015ProjectsContosoUniversitysrcContosoUniversity" controller --force --controllerName StudentsController --model ContosoUniversity.Models.Student --dataContext ContosoUniversity.Data.SchoolContext --relativeFolderPath Controllers --controllerNamespace ContosoUniversity.Controllers --referenceScriptLibraries --useDefaultLayout Finding the generator 'controller'... Running the generator 'controller'... Attempting to compile the application in memory Attempting to figure out the EntityFramework metadata for the model and DbContext: Student Exception has been thrown by the target of an invocation. StackTrace: at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build() at Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EntityFrameworkServices.TryCreateContextUsingAppCode(Type dbContextType, ModelType startupType) Arithmetic operation resulted in an overflow. StackTrace: at System.Data.SqlClient.SNINativeMethodWrapper.SNIOpenSyncExWrapper(SNI_CLIENT_CONSUMER_INFO& pClientConsumerInfo, IntPtr& ppConn) at System.Data.SqlClient.SNINativeMethodWrapper.SNIOpenSyncEx(ConsumerInfo consumerInfo, String constring, IntPtr& pConn, Byte[] spnBuffer, Byte[] instanceName, Boolean fOverrideCache, Boolean fSync, Int32 timeout, Boolean fParallel) at System.Data.SqlClient.SNIHandle..ctor(ConsumerInfo myInfo, String serverName, Byte[] spnBuffer, Boolean ignoreSniOpenTimeout, Int32 timeout, Byte[]& instanceName, Boolean flushCache, Boolean fSync, Boolean fParallel) at System.Data.SqlClient.TdsParserStateObject.CreatePhysicalSNIHandle(String serverName, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Byte[]& instanceName, Byte[] spnBuffer, Boolean flushCache, Boolean async, Boolean fParallel) at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.Open() at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open() at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator.Create() at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated() at ContosoUniversity.Models.DbInitializer.Initialize(SchoolContext context) at ContosoUniversity.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) There was an error creating the DbContext instance to get the model. No parameterless constructor defined for this object. No parameterless constructor defined for this object. at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.<BuildCommandLine>b__6_0() at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args) at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args) RunTime 00:00:22.49
TL;DR: You’re casting 64-bits IntPtr to a Int32… Which causes «overflow»
At first, I thought it’s most likely your ‘+4’, you’re assuming that the padding is 4 bytes wide. Unless you’ve explicitly compiled as platform targeted for x86 (and not x86_64 or «Any CPU»), your «lp» pointer size (of your buffer you’re iterating) would be 64-bits (on «Any CPU», it flips between O/S running 32-bit or 64-bits). Change your +4 to be more dynamic (+4 for 32-bit, +8 for 64-bits) in whatever techniques you chose (i.e. «… + IntPtr.Size» instead of «… + 4»).
On that note…
But then, I’ve realized that you’re getting a casting exception in which you’re attempting to cast a 64-bits pointer (IntPtr) into an «Int» (and then, you assign it to Int32, though «int» is alias to System.Int32 from I remember). It works on your 32-bits O/S or when you explicitly compile/build as «x86» but when you do «Any CPU» or 64-bits mode, you get exceptions during runtime.
Good luck && peace!
Table of Contents
- Overview
- Constant Values
- Checked Keyword
- Unchecked
- Conclusion
- References
Overview
In C#, the Integer type is used a lot to store values within methods. Often we do not think about the limits that the Integer has. By default, the maximum value it can hold is 2147483647. If we try to cram more into an Integer we receive an overflow error as
the range has been met.
The Checked keyword is a way to see if integer arithmetic, including casts, can hold a value and if not it will generate a System.OverflowException error that can be handled elegantly. This keyword has been around since Visual Studio 2003 but little has been
written on it. This article will examine how to use the Checked and Unchecked keywords.
Constant Values
Only constant values will cause the checked expression to fail. If the value is not a constant then it will not raise an overflow exception.
For example, the following line:
will generate an error message stating “The operation overflows at compile time in checked mode”.
However, doing any work with non-constant values will not display an error. In this line we will use a variable to add 1 to the maximum integer value:
int
y = 1;
int
x = 2147483647 + y;
Console.WriteLine(x);
This expression will not raise an error message. Instead, it will sum the value of two positive integers and produce a negative result: -2147483648.
Checked Keyword
You can do overflow checking with compiler options or with the Checked keyword on an expression or method.
To use the compiler option, you can set the /checked option on the Build tab of the project’s properties to check for integer overflows which will cause an exception at run time. This will check all of your code automatically but at a cost
as it might slow down your program to do so. For more information about this option, see
/checked (C# Compiler Options).
For expression checking, wrap the statement you wish to validate in the checked value:
int
x = checked(2147483647 + 1);
You can also check blocks of code encapsulated in braces:
checked
{
int
y = 1;
int
x = 2147483647 + y;
Console.WriteLine(x);
}
The keyword will only validate the code inside the braces. If your code calls other methods they will not be verified by the Checked keyword.
Both examples above raise an overflow exception. Following best practices, wrap these values in a try-catch block so as to handle the raised exception:
using
System;
public
class
Program
{
static
int
maxIntValue = 2147483647;
public
static
voidMain()
{
Console.WriteLine(CheckedMethod());
}
static
int
CheckedMethod()
{
int
x = 0;
try
{
x =
checked
(maxIntValue + 1);
}
catch
(System.OverflowException e)
{
Console.WriteLine("Overflow exception due to unchecked integer value: "
+ e.ToString());
}
return
x;
}
}
The code above will generate the following error: Overflow exception due to unchecked integer value: System.OverflowException: Arithmetic operation resulted in an overflow.
Unchecked
C# also has the Unchecked keyword. This will allow you prevent overflow checking on certain items. It can be applied to expressions within a Checked method or to entire blocks of code if you have enabled the compiler option. This keyword is useful if want to
label multiple items as Checked with a single line as Unchecked.
Conclusion
The Checked/Unchecked keywords are useful for trapping arithmetic overflows of integer values. It provides a way to elegantly trap for these occurrences and to handle the errors gracefully.
Some best practices to observe when using the keywords are:
- Only use the Checked/Unchecked keywords when an overflow is possible.
- Do not turn on the Compiler option in Release mode.
- Checked will not prevent a DivideByZeroException when a divide by zero is attempted.
References
- checked (C# Reference)
- unchecked (C# Reference)
- Arithmetic Overflow Checking using checked/unchecked
On .NET-Core 2.0 x64, I get «Arithmetic operation resulted in an overflow.» on reading the ascender…
/// <summary>
/// Gets the ascender in 26.6 fractional pixels.
/// </summary>
/// <see cref="Face"/>
public Fixed26Dot6 Ascender
{
get
{
// Here => (int)
return Fixed26Dot6.FromRawValue((int)rec.ascender);
}
}
I don’t get what you’re doing there — casting an int64 to an int32 ?
This can’t work…
SharpFont.Native.Init();
SharpFont.Library lib = new SharpFont.Library();
SharpFont.Face fontFace = new SharpFont.Face(lib, @"C:WindowsFontstahoma.ttf");
float size = 12;
if (fontFace!= null)
// fontFace.SetCharSize(0, size, 0, 96);
fontFace.SetCharSize(size, size, 96, 96);
System.Console.WriteLine(fontFace.Size.Metrics.Ascender.ToDouble()); // kaboom...
System.Console.WriteLine(fontFace.Size.Metrics.Descender.ToSingle());
System.Console.WriteLine(fontFace.Size.Metrics.Height.ToSingle());
Dll’s from SharpFontDependenciesfreetype22.6-alldepsmsvc12x64
namespace SharpFont
{
public class Native
{
public static void Init()
{
if (System.Environment.OSVersion.Platform == System.PlatformID.Unix)
return;
System.Reflection.Assembly ass = typeof(Native).Assembly;
string dir = System.IO.Path.GetDirectoryName(ass.Location);
int bitness = System.IntPtr.Size * 8;
string[] embeddedResources = ass.GetManifestResourceNames();
string freetypeLib = "freetype6.x86-" + bitness.ToString() + ".dll";
string fileName = System.IO.Path.Combine(dir, "freetype6.dll");
string found = null;
for (int i = 0; i < embeddedResources.Length; ++i)
{
if (embeddedResources[i].EndsWith(freetypeLib, System.StringComparison.OrdinalIgnoreCase))
{
found = embeddedResources[i];
break;
}
} // Next i
if (string.IsNullOrEmpty(found))
throw new System.Exception("Resource "" + freetypeLib + ""not found");
using (System.IO.Stream strm = ass.GetManifestResourceStream(found))
{
using (System.IO.Stream output = System.IO.File.Create(fileName))
{
strm.CopyTo(output);
} // End Using output
} // End Using strm
} // End Sub Init
} // End Class Native
} // End Namespace SharpFont
Note:
On Linux with the same code, this runs just fine (font file path changed of course).
