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
- WindowsUserNameSecurityTokenAuthenticator.cs
- FilePrompt.cs
- TreeNodeCollectionEditorDialog.cs
- DataGridDesigner.cs
- XPathNodeInfoAtom.cs
- RotateTransform3D.cs
- TagNameToTypeMapper.cs
- WriteLine.cs
- WindowsListViewItemStartMenu.cs
- EntityDataSourceMemberPath.cs
- SoapExtension.cs
- ContractMapping.cs
- DoubleAnimationUsingKeyFrames.cs
- SingleAnimation.cs
- ServiceModelInstallComponent.cs
- StateMachineTimers.cs
- ReadOnlyPropertyMetadata.cs
- SerializationIncompleteException.cs
- SafeNativeMethods.cs
- HttpContext.cs
- TdsParserSafeHandles.cs
- PolygonHotSpot.cs
- TypeSystem.cs
- TransformProviderWrapper.cs
- InternalControlCollection.cs
- ErrorActivity.cs
- X509UI.cs
- XmlSchemaImport.cs
- CompoundFileIOPermission.cs
- DataGridViewCellFormattingEventArgs.cs
- JsonSerializer.cs
- DynamicQueryableWrapper.cs
- LineProperties.cs
- TreeViewAutomationPeer.cs
- CancellableEnumerable.cs
- SwitchLevelAttribute.cs
- FlowLayoutPanel.cs
- WsdlImporterElementCollection.cs
- AppSettingsSection.cs
- FirstMatchCodeGroup.cs
- IdentityHolder.cs
- DataFormats.cs
- ProgressBarAutomationPeer.cs
- SRef.cs
- ItemsChangedEventArgs.cs
- XmlTextReaderImpl.cs
- Pointer.cs
- DecoderExceptionFallback.cs
- XmlIgnoreAttribute.cs
- ResourceLoader.cs
- TypeSystem.cs
- SignerInfo.cs
- RenderData.cs
- PropertyToken.cs
- Context.cs
- InvalidPrinterException.cs
- DeploymentSection.cs
- CodeMemberEvent.cs
- StrokeNodeOperations.cs
- ScriptDescriptor.cs
- XPathScanner.cs
- UserPrincipalNameElement.cs
- DirectoryLocalQuery.cs
- TypedTableGenerator.cs
- JsonXmlDataContract.cs
- storepermissionattribute.cs
- OpenFileDialog.cs
- RichTextBox.cs
- ByValueEqualityComparer.cs
- Closure.cs
- VisualStyleElement.cs
- WinFormsSpinner.cs
- RegionInfo.cs
- FastEncoderWindow.cs
- CompositeDesignerAccessibleObject.cs
- EntityPropertyMappingAttribute.cs
- AmbientProperties.cs
- XmlConvert.cs
- _IPv6Address.cs
- SqlCrossApplyToCrossJoin.cs
- ReadWriteSpinLock.cs
- OneOfTypeConst.cs
- ExceptionUtil.cs
- mediaeventshelper.cs
- WebPartEditorApplyVerb.cs
- OracleParameterBinding.cs
- EventMappingSettings.cs
- PersonalizationAdministration.cs
- ConnectionPoint.cs
- XmlSchemaType.cs
- Visual3DCollection.cs
- IList.cs
- XmlWriterSettings.cs
- SoapFault.cs
- NoResizeSelectionBorderGlyph.cs
- TextElementAutomationPeer.cs
- ConfigurationLockCollection.cs
- ComponentEvent.cs
- HttpResponseBase.cs
- ComponentChangedEvent.cs