Меню

Arithmetic operation resulted in an overflow ошибка

For simplicity I will use bytes:

byte a=250;
byte b=8;
byte c=a+b;

if a, b, and c were ‘int’, you would expect 258, but in the case of ‘byte’, the expected result would be 2 (258 & 0xFF), but in a Windows application you get an exception, in a console one you may not (I don’t, but this may depend on IDE, I use SharpDevelop).

Sometimes, however, that behaviour is desired (e.g. you only care about the lower 8 bits of the result).

You could do the following:

byte a=250;
byte b=8;

byte c=(byte)((int)a + (int)b);

This way both ‘a’ and ‘b’ are converted to ‘int’, added, then casted back to ‘byte’.

To be on the safe side, you may also want to try:

...
byte c=(byte)(((int)a + (int)b) & 0xFF);

Or if you really want that behaviour, the much simpler way of doing the above is:

unchecked
{
    byte a=250;
    byte b=8;
    byte c=a+b;
}

Or declare your variables first, then do the math in the ‘unchecked’ section.

Alternately, if you want to force the checking of overflow, use ‘checked’ instead.

Hope this clears things up.

Nurchi

P.S.

Trust me, that exception is your friend 🙂

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
Graphics graph = null;
var bmp = new Bitmap(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width, System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height);
graph = Graphics.FromImage(bmp);
graph.CopyFromScreen(0, 0, 0, 0, bmp.Size);
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string path = desktop + @"ВАЖН0text" ;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
bmp.Save(path+"1.jpg",ImageFormat.Jpeg);

Ток добавь ссылку на WinForms или используй SystemInformation или чёто другое для получения разрешения.
P.S. По поводу скриншота с камеры код из интернета прекрасно работает, прооверил без ошибок

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication2
{
    class Program
    {

        private const int WM_CAP_DRIVER_CONNECT = 0x40a;
        private const int WM_CAP_DRIVER_DISCONNECT = 0x40b;
        private const int WS_CHILD = 0x40000000;
        private const int WS_POPUP = unchecked((int)0x80000000);
        private const int WM_CAP_SAVEDIB = 0x419;

        [DllImport("avicap32.dll", EntryPoint = "capCreateCaptureWindowA")]
        public static extern IntPtr capCreateCaptureWindowA(string lpszWindowName, int dwStyle, int X, int Y, int nWidth, int nHeight, int hwndParent, int nID);

        [DllImport("user32", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        public static void Main()
        {
            String dName = "".PadRight(100);
            String dVersion = "".PadRight(100);
            IntPtr hWndC = capCreateCaptureWindowA("VFW Capture", WS_POPUP | WS_CHILD, 0, 0, 320, 240, 0, 0); // узнать дескриптор камеры
            SendMessage(hWndC, WM_CAP_DRIVER_CONNECT, 0, 0); //подключиться к камере
            string path = @"D:test.jpg";
            IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
            SendMessage(hWndC, WM_CAP_SAVEDIB, 0, hBmp.ToInt32()); // сохранить скриншот
            SendMessage(hWndC, WM_CAP_DRIVER_DISCONNECT, 0, 0); //отключить камеру
        }
    }
}

** Troubleshooting ** «Arithmetic operation resulted in an overflow» when using «Data Entry — Shareholdings and Investments»

Troubleshooting

Problem

User clicks «Data Entry — Shareholdings and Investments». User tries to make some changes. User receives an error.

Symptom

Example #1 (Controller 10.1.1):

IBM Cognos Controller Error
Unhandled exception has occurred in your application. If you click Continue, the application will ignore the error and attempt to continue. If you click Quit, the application will close immediately.
Arithmetic operation resulted in an overflow.
[Details] [Continue] [Quit]

Example #2 (Controller 10.4.0):

Arithmetic operation resulted in an overflow.
at Microsoft.VisualBasic.CompilerServices.Conversions.ToShort(Object Value)
at Cognos.Controller.Forms.Form.frmShareholdReg.ZTrim(Int16& Col)
at Cognos.Controller.Forms.Form.frmShareholdReg.EnableDisable()
at Cognos.Controller.Forms.Form.frmShareholdReg.DoFillFlexGrid()
at Cognos.Controller.Forms.Form.frmShareholdReg.IForm_DoClick(Int32 lCmd, String& sTag)
at Cognos.Controller.Button.stdButton.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.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Cause

There are several possible causes for this error:

Scenario #1 — (likely) The client PC’s Regional Settings are causing a problem.

  • In one real-life customer case (Example #1 — Controller 10.1.1), the ‘bad’ client PCs were using Norwegian Regional Settings
  • In a different real-life customer case (Example #2 — Controller 10.4.0), the ‘bad’ client PCs were using Swedish Regional Settings.

Scenario #2 — (rare / unlikely) Invalid cache files inside end user’s Windows user profile

  • For more details, see separate IBM Technote #1611542.

Resolving The Problem

Scenario #1

Example #1

(Controller 10.1.1)

In one real-life customer example, the problem was solved by changing the client device’s Regional Settings from the current (Norwegian) to English (UK), and then back again. In other words, the end user performed the following tasks (based on Windows 7):

1. Open «Control Panel»

2. Open «Clock, Language, and Region»

3. Click «Region and Language»

4. Inside tab «Formats», change format from current (Norway) to «English (United Kingdom)»

5. Looff from Windows

6. Re-logon to Windows

7. Lanch Controller and test (Controller functionality should now work OK)

8. Afterwards, open «Control Panel»

9. Open «Clock, Language, and Region»

10. Click «Region and Language»

11. Inside tab «Formats», change format from current «English (United Kingdom)» to «Norway»

12. Logoff from Windows

13. Re-logon to Windows

14. Launch Controller and test (Controller functionality should now still work OK)

Example #2

(Controller 10.4.0)

In a different real-life customer example, the customer was deploying Controller via Citrix. 

  • The default ‘bad’ regional settings were ‘Swedish’
  • After changing the user’s regional settings to ‘Finnish’ (by publishing a ‘regional settings’ Citrix application, see separate IBM Technote #267757 ) it solved the error.
 

Scenario #2
Delete Controller cache files.

  • See separate IBM Technote #1611542.

Related Information

[{«Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Product»:{«code»:»SS9S6B»,»label»:»IBM Cognos Controller»},»ARM Category»:[{«code»:»a8m0z000000Gmx2AAC»,»label»:»Error»}],»ARM Case Number»:»TS003562429″,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»All Versions»,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

Was this topic helpful?

Document Information

Modified date:

16 April 2020

  • Remove From My Forums
  • Вопрос

  • Regarding the script below, a user replied that they were able to get the shared C# script working via removing a variable. I am not versed in C# and I am having a hard time figuring out the fix. Any ideas?

    Was getting the following error:

    Exception calling «ReadPrivilege» with «1» argument(s): «Arithmetic operation resulted in an overflow.»
    At line:232 char:1
    + $blah = $lsa.ReadPrivilege(«SeInteractiveLogonRight»)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : OverflowException

    Had to remove the ‘elemOff’ variable and just use ‘buffer’ directly.   The casting to (int) was causing overflow.

    Thanks for script

    # All of this C# code is used to call the Win32 API function we need, and deal with its output.
    
    $csharp = @'
        using System;
        using System.Runtime.InteropServices;
        using System.Security;
        using System.Security.Principal;
        using System.ComponentModel;
    
        namespace LsaSecurity
        {
            using LSA_HANDLE = IntPtr;
    
            [StructLayout(LayoutKind.Sequential)]
            public struct LSA_OBJECT_ATTRIBUTES
            {
                public int Length;
                public IntPtr RootDirectory;
                public IntPtr ObjectName;
                public int Attributes;
                public IntPtr SecurityDescriptor;
                public IntPtr SecurityQualityOfService;
            }
    
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
            public struct LSA_UNICODE_STRING
            {
                public ushort Length;
                public ushort MaximumLength;
                [MarshalAs(UnmanagedType.LPWStr)]
                public string Buffer;
            }
    
            [StructLayout(LayoutKind.Sequential)]
            public struct LSA_ENUMERATION_INFORMATION
            {
               public IntPtr PSid;
            }
    
            sealed public class Win32Sec
            {
                [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
                           SuppressUnmanagedCodeSecurityAttribute]
                public static extern uint LsaOpenPolicy(LSA_UNICODE_STRING[] SystemName,
                                                        ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
                                                        int AccessMask,
                                                        out IntPtr PolicyHandle);
    
                [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
                           SuppressUnmanagedCodeSecurityAttribute]
                public static extern uint LsaEnumerateAccountsWithUserRight(LSA_HANDLE PolicyHandle,
                                                                            LSA_UNICODE_STRING[] UserRights,
                                                                            out IntPtr EnumerationBuffer,
                                                                            out int CountReturned);
    
                [DllImport("advapi32")]
                public static extern int LsaNtStatusToWinError(int NTSTATUS);
    
                [DllImport("advapi32")]
                public static extern int LsaClose(IntPtr PolicyHandle);
    
                [DllImport("advapi32")]
                public static extern int LsaFreeMemory(IntPtr Buffer);
            }
    
            public class LsaWrapper : IDisposable
            {
                public enum Access : int
                {
                    POLICY_READ = 0x20006,
                    POLICY_ALL_ACCESS = 0x00F0FFF,
                    POLICY_EXECUTE = 0X20801,
                    POLICY_WRITE = 0X207F8
                }
    
                const uint STATUS_ACCESS_DENIED = 0xc0000022;
                const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
                const uint STATUS_NO_MEMORY = 0xc0000017;
                const uint STATUS_NO_MORE_ENTRIES = 0xc000001A;
    
                IntPtr lsaHandle;
    
                public LsaWrapper()
                    : this(null)
                { }
    
                // local system if systemName is null
                public LsaWrapper(string systemName)
                {
                    LSA_OBJECT_ATTRIBUTES lsaAttr;
                    lsaAttr.RootDirectory = IntPtr.Zero;
                    lsaAttr.ObjectName = IntPtr.Zero;
                    lsaAttr.Attributes = 0;
                    lsaAttr.SecurityDescriptor = IntPtr.Zero;
                    lsaAttr.SecurityQualityOfService = IntPtr.Zero;
                    lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
                    lsaHandle = IntPtr.Zero;
                
                    LSA_UNICODE_STRING[] system = null;
    
                    if (systemName != null)
                    {
                        system = new LSA_UNICODE_STRING[1];
                        system[0] = InitLsaString(systemName);
                    }
    
                    uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr,
                                                      (int)Access.POLICY_ALL_ACCESS,
                                                      out lsaHandle);
                    if (ret == 0) { return; }
    
                    if (ret == STATUS_ACCESS_DENIED)
                    {
                        throw new UnauthorizedAccessException();
                    }
                    if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
                    {
                        throw new OutOfMemoryException();
                    }
                    throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
                }
    
                public SecurityIdentifier[] ReadPrivilege(string privilege)
                {
                    LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
                    privileges[0] = InitLsaString(privilege);
                    IntPtr buffer;
                    int count = 0;
                    uint ret = Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out buffer, out count);
                
                    if (ret == 0)
                    {
                        SecurityIdentifier[] sids = new SecurityIdentifier[count];
    
                        for (int i = 0, elemOffs = (int)buffer; i < count; i++)
                        {
                            LSA_ENUMERATION_INFORMATION lsaInfo = (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure(
                                (IntPtr)elemOffs, typeof(LSA_ENUMERATION_INFORMATION));
    
                            sids[i] = new SecurityIdentifier(lsaInfo.PSid);
    
                            elemOffs += Marshal.SizeOf(typeof(LSA_ENUMERATION_INFORMATION));
                        }
    
                        return sids;
                    }
    
                    if (ret == STATUS_ACCESS_DENIED)
                    {
                        throw new UnauthorizedAccessException();
                    }
                    if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
                    {
                        throw new OutOfMemoryException();
                    }
    
                    throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
                }
    
                public void Dispose()
                {
                    if (lsaHandle != IntPtr.Zero)
                    {
                        Win32Sec.LsaClose(lsaHandle);
                        lsaHandle = IntPtr.Zero;
                    }
                    GC.SuppressFinalize(this);
                }
    
                ~LsaWrapper()
                {
                    Dispose();
                }
    
                public static LSA_UNICODE_STRING InitLsaString(string s)
                {
                    // Unicode strings max. 32KB
                    if (s.Length > 0x7ffe)
                       throw new ArgumentException("String too long");
                    LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
                    lus.Buffer = s;
                    lus.Length = (ushort)(s.Length * sizeof(char));
                    lus.MaximumLength = (ushort)(lus.Length + sizeof(char));
                    return lus;
                }
            }
        }
    '@
    
    Add-Type -TypeDefinition $csharp
    
    # Here's the code that uses the C# classes we've added.
    
    $lsa = New-Object LsaSecurity.LsaWrapper
    $sids = $lsa.ReadPrivilege('SeInteractiveLogonRight')
    
    # ReadPrivilege() returns an array of [SecurityIdentifier] objects.  We'll try to translate them into a more human-friendly
    # NTAccount object here (which will give us a DomainUser string), and output the value whether the translation succeeds or not.
    
    foreach ($sid in $sids)
    {
        try
        {
            $sid.Translate([System.Security.Principal.NTAccount]).Value
        }
        catch
        {
            $sid.Value
        }
    }

Ответы

  • What you are really doing is wrapping P/Invoke (unmanaged Win32 API) using .NET in PowerShell.

    If you are not very experienced with P/Invoke and unmanaged code (particularly concepts like pointers and marshalling), you are likely to be in over your head very quickly.

    Therefore, your question is not trivial and may be entirely outside the scope of this forum.

    How about starting with explaining what the script is supposed to do? What problem are you solving?


    — Bill Stewart [Bill_Stewart]

    • Помечено в качестве ответа

      14 апреля 2020 г. 17:01

after deployed or installed your application to remote server or clients computer, user happened to use your program over a period of time and error popped out. Your program may be in arithmetic operation resulted in a workflow vb.net, arithmetic operation resulted in a workflow oracle, arithmetic operation resulted in a workflow windows 10, arithmetic operation resulted in a asp.net.

This is what will happen next..

Your client raises a ticket to solve this high critical issue, and imaging you haven’t done this before — what would you do?

If you are reading here, yes you are at right place to grab solution.

Before get into the solution let’s find what caused this error

What is root cause?

If you are beginner to any programming language, it is good to learn how program function behind logic executed, and better way to optimize and utilize the memory allocation.

Any variable declaration will occupy memory depends on the types such as int, string, array, float, point etc. Each variable has highest or maximum size allotted by default

There are times unknowingly or coding practice will lead to exceed the maximum size, and uncleared memory size after function or logic executed.

What will happen of uncleared memory? 

Just a hint, any variable declaration will affect gradually your computer memory. Apart from RAM memory, local computer physical location stores any file you open gets saved automatically as reference. If you do not clear this temporary folder the size keeps increasing and causes slowness and yields overflow error anytime. 

Where is that — physical folder saves files?

It is in operating system (os) folder c: drive. Yes-now let’s see in detail step by step  

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ariston net ошибка связи
  • Ariston margherita 2000 als129x коды ошибок