Code:
/ WCF / WCF / 3.5.30729.1 / untmp / Orcas / SP / ndp / cdf / src / WCF / SMDiagnostics / System / ServiceModel / Diagnostics / Utility.cs / 2 / Utility.cs
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------- namespace System.ServiceModel.Diagnostics { using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Diagnostics; using System.Threading; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; class Utility { ExceptionUtility exceptionUtility; [Obsolete("For SMDiagnostics.dll use only. Call DiagnosticUtility.Utility instead")] internal Utility(ExceptionUtility exceptionUtility) { this.exceptionUtility = exceptionUtility; } ExceptionUtility ExceptionUtility { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return this.exceptionUtility; } } // Call this when a p/invoke with an 'out SafeHandle' parameter returns an error. This will safely clean up the handle. internal static void CloseInvalidOutSafeHandle(SafeHandle handle) { // Workaround for 64-bit CLR bug VSWhidbey 546830 - sometimes invalid SafeHandles come back null. if (handle != null) { #pragma warning disable 618 AssertUtility.DebugAssert(handle.IsInvalid, "CloseInvalidOutSafeHandle called with a valid handle!"); #pragma warning restore 618 // Calls SuppressFinalize. handle.SetHandleAsInvalid(); } } // Same as CloseInvalidOutSafeHandle but marked SecurityCritical for use in PT scenarios ////// Critical - calls SetHandleAsInvalid which has a LinkDemand for UnmanagedCode /// [SecurityCritical] internal static void CloseInvalidOutSafeHandleCritical(SafeHandle handle) { // Workaround for 64-bit CLR bug VSWhidbey 546830 - sometimes invalid SafeHandles come back null. if (handle != null) { #pragma warning disable 618 AssertUtility.DebugAssert(handle.IsInvalid, "CloseInvalidOutSafeHandle called with a valid handle!"); #pragma warning restore 618 // Calls SuppressFinalize. handle.SetHandleAsInvalid(); } } // Copy of the above for CriticalHandles. internal static void CloseInvalidOutCriticalHandle(CriticalHandle handle) { if (handle != null) { #pragma warning disable 618 AssertUtility.DebugAssert(handle.IsInvalid, "CloseInvalidOutCriticalHandle called with a valid handle!"); #pragma warning restore 618 handle.SetHandleAsInvalid(); } } [SuppressMessage("Reliability", "Reliability113", Justification = "These are the core methods that should be used for all other Guid(string) calls.")] internal Guid CreateGuid(string guidString) { bool success = false; Guid result = Guid.Empty; try { result = new Guid(guidString); success = true; } finally { if (!success) { #pragma warning disable 618 AssertUtility.DebugAssert(false, "Creation of the Guid failed."); #pragma warning restore 618 } } return result; } [SuppressMessage("Reliability", "Reliability113", Justification = "These are the core methods that should be used for all other Guid(string) calls.")] internal bool TryCreateGuid(string guidString, out Guid result) { bool success = false; result = Guid.Empty; try { result = new Guid(guidString); success = true; } catch (ArgumentException e) { // ignore this ExceptionUtility.TraceHandledException(e, TraceEventType.Warning); } catch (FormatException e) { // ignore this ExceptionUtility.TraceHandledException(e, TraceEventType.Warning); } catch (OverflowException e) { // ignore this ExceptionUtility.TraceHandledException(e, TraceEventType.Warning); } return success; } internal byte[] AllocateByteArray(int size) { try { // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls). return new byte[size]; } catch (OutOfMemoryException exception) { // Convert OOM into an exception that can be safely handled by higher layers. throw ExceptionUtility.ThrowHelperError(new InsufficientMemoryException(TraceSR.GetString( TraceSR.BufferAllocationFailed, size), exception)); } } internal char[] AllocateCharArray(int size) { try { // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls). return new char[size]; } catch (OutOfMemoryException exception) { // Convert OOM into an exception that can be safely handled by higher layers. throw ExceptionUtility.ThrowHelperError(new InsufficientMemoryException(TraceSR.GetString( TraceSR.BufferAllocationFailed, size * sizeof(char)), exception)); } } ////// Critical - sets up a callback with a CER, must guard utility argument (in this case, 'this') /// Safe - safe for callers /// [SecurityCritical, SecurityTreatAsSafe] internal AsyncCallback ThunkCallback(AsyncCallback callback) { return (new AsyncThunk(callback, this)).ThunkFrame; } ////// Critical - sets up a callback with a CER, must guard utility argument (in this case, 'this') /// Safe - safe for callers /// [SecurityCritical, SecurityTreatAsSafe] internal TimerCallback ThunkCallback(TimerCallback callback) { return (new TimerThunk(callback, this)).ThunkFrame; } ////// Critical - sets up a callback with a CER, must guard utility argument (in this case, 'this') /// Safe - safe for callers /// [SecurityCritical, SecurityTreatAsSafe] internal WaitOrTimerCallback ThunkCallback(WaitOrTimerCallback callback) { return (new WaitOrTimerThunk(callback, this)).ThunkFrame; } ////// Critical - sets up a callback with a CER, must guard utility argument (in this case, 'this') /// Safe - safe for callers /// [SecurityCritical, SecurityTreatAsSafe] internal IOCompletionCallback ThunkCallback(IOCompletionCallback callback) { return (new IOCompletionThunk(callback, this)).ThunkFrame; } ////// Critical - sets up a callback with a CER, must guard utility argument (in this case, 'this') /// Safe - safe for callers /// [SecurityCritical, SecurityTreatAsSafe] internal WaitCallback ThunkCallback(WaitCallback callback) { return (new WaitThunk(callback, this)).ThunkFrame; } ////// Critical - stores the utility parameter for derived classes /// [SecurityCritical(SecurityCriticalScope.Everything)] class Thunkwhere T : class { protected T callback; protected Utility utility; public Thunk(T callback, Utility utility) { #pragma warning disable 618 AssertUtility.DebugAssert(utility != null, "Null utility passed to Thunk."); AssertUtility.DebugAssert(callback != null, "Null callback passed to Thunk."); #pragma warning restore 618 this.callback = callback; this.utility = utility; } } /// /// Critical - uses RuntimeHelpers.PrepareConstrainedRegions which has a LinkDemand for UnmanagedCode /// caller must guard utility parameter -- calls from catch/finally block have special requirements /// [SecurityCritical(SecurityCriticalScope.Everything)] sealed class AsyncThunk : Thunk{ public AsyncThunk(AsyncCallback callback, Utility utility) : base(callback, utility) { } public AsyncCallback ThunkFrame { get { return new AsyncCallback(UnhandledExceptionFrame); } } void UnhandledExceptionFrame(IAsyncResult result) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(result); } catch (Exception exception) { if (!this.utility.HandleAtThreadBase(exception)) { throw; } } } } /// /// Critical - uses RuntimeHelpers.PrepareConstrainedRegions which has a LinkDemand for UnmanagedCode /// caller must guard utility parameter -- calls from catch/finally block have special requirements /// [SecurityCritical(SecurityCriticalScope.Everything)] sealed class TimerThunk : Thunk{ public TimerThunk(TimerCallback callback, Utility utility) : base(callback, utility) { } public TimerCallback ThunkFrame { get { return new TimerCallback(UnhandledExceptionFrame); } } void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(state); } catch (Exception exception) { if (!this.utility.HandleAtThreadBase(exception)) { throw; } } } } /// /// Critical - uses RuntimeHelpers.PrepareConstrainedRegions which has a LinkDemand for UnmanagedCode /// caller must guard utility parameter -- calls from catch/finally block have special requirements /// [SecurityCritical(SecurityCriticalScope.Everything)] sealed class WaitOrTimerThunk : Thunk{ public WaitOrTimerThunk(WaitOrTimerCallback callback, Utility utility) : base(callback, utility) { } public WaitOrTimerCallback ThunkFrame { get { return new WaitOrTimerCallback(UnhandledExceptionFrame); } } void UnhandledExceptionFrame(object state, bool timedOut) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(state, timedOut); } catch (Exception exception) { if (!this.utility.HandleAtThreadBase(exception)) { throw; } } } } /// /// Critical - uses RuntimeHelpers.PrepareConstrainedRegions which has a LinkDemand for UnmanagedCode /// caller must guard utility parameter -- calls from catch/finally block have special requirements /// [SecurityCritical(SecurityCriticalScope.Everything)] unsafe sealed class IOCompletionThunk { IOCompletionCallback callback; Utility utility; public IOCompletionThunk(IOCompletionCallback callback, Utility utility) { #pragma warning disable 618 AssertUtility.DebugAssert(utility != null, "Null utility passed to Thunk."); AssertUtility.DebugAssert(callback != null, "Null callback passed to Thunk."); #pragma warning restore 618 this.callback = callback; this.utility = utility; } public IOCompletionCallback ThunkFrame { get { return new IOCompletionCallback(UnhandledExceptionFrame); } } void UnhandledExceptionFrame(uint error, uint bytesRead, NativeOverlapped* nativeOverlapped) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(error, bytesRead, nativeOverlapped); } catch (Exception exception) { if (!this.utility.HandleAtThreadBase(exception)) { throw; } } } } ////// Critical - uses RuntimeHelpers.PrepareConstrainedRegions which has a LinkDemand for UnmanagedCode /// caller must guard utility parameter -- calls from catch/finally block have special requirements /// [SecurityCritical(SecurityCriticalScope.Everything)] sealed class WaitThunk : Thunk{ public WaitThunk(WaitCallback callback, Utility utility) : base(callback, utility) { } public WaitCallback ThunkFrame { get { return new WaitCallback(UnhandledExceptionFrame); } } void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { this.callback(state); } catch (Exception exception) { if (!this.utility.HandleAtThreadBase(exception)) { throw; } } } } /// /// RequiresReview - does an InheritanceDemand because this method is called within a CER /// the method must not be overridden by PT code or allowed to call into PT code /// [SecurityRequiresReview] [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal virtual bool CallHandler(Exception exception) { return false; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] void TraceExceptionNoThrow(Exception exception, TraceEventType eventType) { try { // This call exits the CER. However, when still inside a catch, normal ThreadAbort is prevented. // Rude ThreadAbort will still be allowed to terminate processing. ExceptionUtility.TraceHandledException(exception, eventType); } #pragma warning suppress 56500 catch { } } // Returns true if the exception is handled. ////// RequiresReview - must not call into PT code as it is called within a CER /// [SecurityRequiresReview] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] bool HandleAtThreadBase(Exception exception) { // These exceptions have to do with thread control. Let them go through unimpeded. if (ExceptionUtility.IsInfrastructureException(exception)) { TraceExceptionNoThrow(exception, TraceEventType.Warning); return false; } TraceExceptionNoThrow(exception, TraceEventType.Critical); try { return CallHandler(exception); } #pragma warning suppress 56500 // covered by FXCop catch (Exception secondException) { // Don't let a new exception hide the original exception. TraceExceptionNoThrow(secondException, TraceEventType.Error); } return false; } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- ImageSourceValueSerializer.cs
- Queue.cs
- SymbolEqualComparer.cs
- SelectionRange.cs
- HtmlContainerControl.cs
- TdsParserStaticMethods.cs
- ObjectStateEntryBaseUpdatableDataRecord.cs
- WaitForChangedResult.cs
- DataControlButton.cs
- ParsedAttributeCollection.cs
- SystemUdpStatistics.cs
- DataGridViewRowsAddedEventArgs.cs
- DataColumnSelectionConverter.cs
- SymbolTable.cs
- StylusEditingBehavior.cs
- TextElementCollectionHelper.cs
- ImageListUtils.cs
- Util.cs
- TypeGeneratedEventArgs.cs
- HandledEventArgs.cs
- FilterRepeater.cs
- CheckBoxPopupAdapter.cs
- SqlFunctionAttribute.cs
- SafeThreadHandle.cs
- SendMailErrorEventArgs.cs
- SortFieldComparer.cs
- LowerCaseStringConverter.cs
- VoiceSynthesis.cs
- SignatureHelper.cs
- ControlParameter.cs
- SetterBase.cs
- EdmToObjectNamespaceMap.cs
- WSDualHttpSecurityMode.cs
- SessionEndedEventArgs.cs
- SyntaxCheck.cs
- Intellisense.cs
- SQLDecimal.cs
- KoreanLunisolarCalendar.cs
- PatternMatcher.cs
- ErrorTableItemStyle.cs
- __TransparentProxy.cs
- Aes.cs
- NativeMethods.cs
- ColorPalette.cs
- SiteMapNode.cs
- GregorianCalendarHelper.cs
- ObservableDictionary.cs
- Size3DValueSerializer.cs
- BamlLocalizabilityResolver.cs
- SQLBinary.cs
- JsonEncodingStreamWrapper.cs
- MailWriter.cs
- SectionXmlInfo.cs
- FormsAuthenticationModule.cs
- PageAdapter.cs
- WebPartVerbCollection.cs
- InvokeHandlers.cs
- recordstatefactory.cs
- CompiledIdentityConstraint.cs
- FontFaceLayoutInfo.cs
- EntityDataSourceQueryBuilder.cs
- PropertyRef.cs
- ComponentConverter.cs
- SqlAliasesReferenced.cs
- DateTimeValueSerializerContext.cs
- ReferenceEqualityComparer.cs
- base64Transforms.cs
- SortDescription.cs
- CommandID.cs
- GridViewCancelEditEventArgs.cs
- EventMemberCodeDomSerializer.cs
- DataKeyCollection.cs
- HwndHostAutomationPeer.cs
- TransformedBitmap.cs
- PartitionResolver.cs
- DebugViewWriter.cs
- MessageFormatterConverter.cs
- OneWayElement.cs
- CounterSetInstance.cs
- HMACMD5.cs
- WebScriptMetadataInstanceContextProvider.cs
- DataSourceXmlElementAttribute.cs
- PropertyValueUIItem.cs
- mda.cs
- DataGridAddNewRow.cs
- DefaultProfileManager.cs
- MissingMethodException.cs
- SamlSubjectStatement.cs
- ComplexTypeEmitter.cs
- TraceSource.cs
- EditingCoordinator.cs
- ProfileParameter.cs
- MemberListBinding.cs
- SafeSecurityHandles.cs
- QueueSurrogate.cs
- NegatedCellConstant.cs
- SystemTcpConnection.cs
- ListItem.cs
- HyperlinkAutomationPeer.cs
- Point3DConverter.cs