This commit is contained in:
Andrew Arnott 2012-05-23 13:49:11 -07:00
Коммит 09c2650253
15 изменённых файлов: 1484 добавлений и 0 удалений

14
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,14 @@
_ReSharper.*
MeasureIt
*.vsp
TestResults
obj
bin
*.suo
*.user
*.trx
StyleCop.Cache
*.vs10x
*.tmp
UpgradeLog.*
_UpgradeReport_Files

20
Microsoft.Validation.sln Normal file
Просмотреть файл

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 11
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Validation", "Microsoft.Validation\Microsoft.Validation.csproj", "{E016A630-A79B-4B5D-8997-E66581D62B81}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E016A630-A79B-4B5D-8997-E66581D62B81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E016A630-A79B-4B5D-8997-E66581D62B81}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E016A630-A79B-4B5D-8997-E66581D62B81}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E016A630-A79B-4B5D-8997-E66581D62B81}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,79 @@
//-----------------------------------------------------------------------
// <copyright file="Assumes.InternalErrorException.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Serialization;
/// <content>
/// Contains the inner exception thrown by Assumes.
/// </content>
internal partial class Assumes
{
/// <summary>
/// The exception that is thrown when an internal assumption failed.
/// </summary>
[Serializable]
[SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic", Justification = "Internal exceptions should not be caught.")]
private class InternalErrorException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="InternalErrorException"/> class.
/// </summary>
public InternalErrorException(string message = null, bool showAssert = true)
: base(message ?? Strings.InternalExceptionMessage)
{
ShowAssertDialog(showAssert);
}
/// <summary>
/// Initializes a new instance of the <see cref="InternalErrorException"/> class.
/// </summary>
public InternalErrorException(string message, Exception innerException, bool showAssert = true)
: base(message ?? Strings.InternalExceptionMessage, innerException)
{
ShowAssertDialog(showAssert);
}
/// <summary>
/// Initializes a new instance of the <see cref="InternalErrorException"/> class.
/// </summary>
protected InternalErrorException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Show the assert if showAssert==true.
/// </summary>
/// <param name="showAssert">Whether to show the assert.</param>
/// <remarks>
/// The assertion dialog may yet be suppressed if
/// ((DefaultTraceListener)System.Diagnostics.Trace.Listeners["Default"]).AssertUiEnabled == false
/// </remarks>
private void ShowAssertDialog(bool showAssert)
{
if (showAssert)
{
// In debug builds, throw up a dialog. This allows a dev to
// attach a debugger right at the point where the exception is
// thrown rather than at the point where the exception is caught.
string message = this.Message;
if (this.InnerException != null)
{
message += " " + this.InnerException;
}
Report.Fail(message);
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,219 @@
//-----------------------------------------------------------------------
// <copyright file="Assumes.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
/// <summary>
/// Common runtime checks that throw internal error exceptions upon failure.
/// </summary>
internal static partial class Assumes
{
/// <summary>
/// Throws an exception if the specified value is null.
/// </summary>
/// <typeparam name="T">The type of value to test.</typeparam>
[DebuggerStepThrough]
public static void NotNull<T>([ValidatedNotNull]T value)
where T : class
{
True(value != null);
}
/// <summary>
/// Throws an exception if the specified value is null or empty.
/// </summary>
[DebuggerStepThrough]
public static void NotNullOrEmpty([ValidatedNotNull]string value)
{
NotNull(value);
True(value.Length > 0);
True(value[0] != '\0');
}
/// <summary>
/// Throws an exception if the specified value is null or empty.
/// </summary>
/// <typeparam name="T">The type of value to test.</typeparam>
[DebuggerStepThrough]
public static void NotNullOrEmpty<T>([ValidatedNotNull]ICollection<T> values)
{
Assumes.NotNull(values);
Assumes.True(values.Count > 0);
}
/// <summary>
/// Throws an exception if the specified value is null or empty.
/// </summary>
/// <typeparam name="T">The type of value to test.</typeparam>
[DebuggerStepThrough]
public static void NotNullOrEmpty<T>([ValidatedNotNull]IEnumerable<T> values)
{
Assumes.NotNull(values);
Assumes.True(values.Any());
}
/// <summary>
/// Throws an exception if the specified value is not null.
/// </summary>
/// <typeparam name="T">The type of value to test.</typeparam>
[DebuggerStepThrough]
public static void Null<T>(T value)
where T : class
{
True(value == null);
}
/// <summary>
/// Throws an exception if the specified object is not of a given type.
/// </summary>
/// <typeparam name="T">The type the value is expected to be.</typeparam>
/// <param name="value">The value to test.</param>
[DebuggerStepThrough]
public static void Is<T>(object value)
{
True(value is T);
}
/// <summary>
/// Throws an internal exception if a condition evaluates to true.
/// </summary>
[DebuggerStepThrough]
public static void False(bool condition, string message = null)
{
if (condition)
{
Fail(message);
}
}
/// <summary>
/// Throws an internal exception if a condition evaluates to true.
/// </summary>
[DebuggerStepThrough]
public static void False(bool condition, string unformattedMessage, object arg1)
{
if (condition)
{
Fail(Format(unformattedMessage, arg1));
}
}
/// <summary>
/// Throws an internal exception if a condition evaluates to true.
/// </summary>
[DebuggerStepThrough]
public static void False(bool condition, string unformattedMessage, params object[] args)
{
if (condition)
{
Fail(Format(unformattedMessage, args));
}
}
/// <summary>
/// Throws an internal exception if a condition evaluates to false.
/// </summary>
[DebuggerStepThrough]
public static void True(bool condition, string message = null)
{
if (!condition)
{
Fail(message);
}
}
/// <summary>
/// Throws an internal exception if a condition evaluates to false.
/// </summary>
[DebuggerStepThrough]
public static void True(bool condition, string unformattedMessage, object arg1)
{
if (!condition)
{
Fail(Format(unformattedMessage, arg1));
}
}
/// <summary>
/// Throws an internal exception if a condition evaluates to false.
/// </summary>
[DebuggerStepThrough]
public static void True(bool condition, string unformattedMessage, params object[] args)
{
if (!condition)
{
Fail(Format(unformattedMessage, args));
}
}
/// <summary>
/// Throws an internal exception.
/// </summary>
[DebuggerStepThrough]
public static Exception NotReachable()
{
// Keep these two as separate lines of code, so the debugger can come in during the assert dialog
// that the exception's constructor displays, and the debugger can then be made to skip the throw
// in order to continue the investigation.
var exception = new InternalErrorException();
throw exception;
}
/// <summary>
/// Verifies that a value is not null, and throws an exception about a missing service otherwise.
/// </summary>
/// <typeparam name="T">The interface of the imported part.</typeparam>
[DebuggerStepThrough]
public static void Present<T>(T component)
{
if (component == null)
{
Type coreType = PrivateErrorHelpers.TrimGenericWrapper(typeof(T), typeof(Lazy<>));
Fail(string.Format(CultureInfo.CurrentCulture, Strings.ServiceMissing, coreType.FullName));
}
}
/// <summary>
/// Throws an internal exception.
/// </summary>
/// <returns>Nothing, as this method always throws. The signature allows for "throwing" Fail so C# knows execution will stop.</returns>
public static Exception Fail(string message = null, bool showAssert = true)
{
// Keep these two as separate lines of code, so the debugger can come in during the assert dialog
// that the exception's constructor displays, and the debugger can then be made to skip the throw
// in order to continue the investigation.
var exception = new InternalErrorException(message, showAssert);
throw exception;
}
/// <summary>
/// Throws an internal exception.
/// </summary>
/// <returns>Nothing, as this method always throws. The signature allows for "throwing" Fail so C# knows execution will stop.</returns>
public static Exception Fail(string message, Exception innerException, bool showAssert = true)
{
// Keep these two as separate lines of code, so the debugger can come in during the assert dialog
// that the exception's constructor displays, and the debugger can then be made to skip the throw
// in order to continue the investigation.
var exception = new InternalErrorException(message, innerException, showAssert);
throw exception;
}
/// <summary>
/// Helper method that formats string arguments.
/// </summary>
private static string Format(string format, params object[] arguments)
{
return PrivateErrorHelpers.Format(format, arguments);
}
}
}

Просмотреть файл

@ -0,0 +1,69 @@
//-----------------------------------------------------------------------
// <copyright file="EventHandlerExtensions.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
/// <summary>
/// Extension methods to make it easier to safely invoke events.
/// </summary>
internal static class EventHandlerExtensions
{
/// <summary>
/// Invokes any event handlers that are hooked to the specified event.
/// </summary>
/// <param name="handler">The event. Null is allowed.</param>
/// <param name="sender">The value to pass as the sender of the event.</param>
/// <param name="e">Event arguments to include.</param>
public static void Raise(this Delegate handler, object sender, EventArgs e)
{
Requires.NotNull(sender, "sender");
Requires.NotNull(e, "e");
if (handler != null)
{
handler.DynamicInvoke(sender, e);
}
}
/// <summary>
/// Invokes any event handlers that are hooked to the specified event.
/// </summary>
/// <param name="handler">The event. Null is allowed.</param>
/// <param name="sender">The value to pass as the sender of the event.</param>
/// <param name="e">Event arguments to include.</param>
public static void Raise(this EventHandler handler, object sender, EventArgs e)
{
Requires.NotNull(sender, "sender");
Requires.NotNull(e, "e");
if (handler != null)
{
handler(sender, e);
}
}
/// <summary>
/// Invokes any event handlers that are hooked to the specified event.
/// </summary>
/// <typeparam name="T">The type of EventArgs.</typeparam>
/// <param name="handler">The event. Null is allowed.</param>
/// <param name="sender">The value to pass as the sender of the event.</param>
/// <param name="e">Event arguments to include.</param>
public static void Raise<T>(this EventHandler<T> handler, object sender, T e)
where T : EventArgs
{
Requires.NotNull(sender, "sender");
Requires.NotNull(e, "e");
if (handler != null)
{
handler(sender, e);
}
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
//-----------------------------------------------------------------------
// <copyright file="IDisposableObservable.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
/// <summary>
/// A disposable object that also provides a safe way to query its disposed status.
/// </summary>
internal interface IDisposableObservable : IDisposable
{
/// <summary>
/// Gets a value indicating whether this instance has been disposed.
/// </summary>
bool IsDisposed { get; }
}
}

Просмотреть файл

@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E016A630-A79B-4B5D-8997-E66581D62B81}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Microsoft.Validation</RootNamespace>
<AssemblyName>Microsoft.Validation</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Assumes.cs" />
<Compile Include="Assumes.InternalErrorException.cs" />
<Compile Include="EventHandlerExtensions.cs" />
<Compile Include="IDisposableObservable.cs" />
<Compile Include="PrivateErrorHelpers.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Report.cs" />
<Compile Include="Requires.cs" />
<Compile Include="Strings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Strings.resx</DependentUpon>
</Compile>
<Compile Include="ValidatedNotNullAttribute.cs" />
<Compile Include="Verify.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Strings.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Strings.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,50 @@
//-----------------------------------------------------------------------
// <copyright file="PrivateErrorHelpers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Common utility methods used by the various error detection and reporting classes.
/// </summary>
internal static class PrivateErrorHelpers
{
/// <summary>
/// Trims away a given surrounding type, returning just the generic type argument,
/// if the given type is in fact a generic type with just one type argument and
/// the generic type matches a given wrapper type. Otherwise, it returns the original type.
/// </summary>
/// <param name="type">The type to trim, or return unmodified.</param>
/// <param name="wrapper">The SomeType&lt;&gt; generic type definition to trim away from <paramref name="type"/> if it is present.</param>
/// <returns><paramref name="type"/>, if it is not a generic type instance of <paramref name="wrapper"/>; otherwise the type argument.</returns>
internal static Type TrimGenericWrapper(Type type, Type wrapper)
{
Type[] typeArgs;
if (type.IsGenericType && type.GetGenericTypeDefinition() == wrapper && (typeArgs = type.GetGenericArguments()).Length == 1)
{
return typeArgs[0];
}
else
{
return type;
}
}
/// <summary>
/// Helper method that formats string arguments.
/// </summary>
internal static string Format(string format, params object[] arguments)
{
return String.Format(CultureInfo.CurrentCulture, format, arguments);
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.Validation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corp.")]
[assembly: AssemblyProduct("Microsoft.Validation")]
[assembly: AssemblyCopyright("Copyright © Microsoft Corp. 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("05bbbcbe-7deb-4588-b4dc-7f2a304aca58")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,123 @@
//-----------------------------------------------------------------------
// <copyright file="Report.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
/// <summary>
/// Common runtime checks that trace messages and invoke an assertion failure,
/// but does *not* throw exceptions.
/// </summary>
internal static class Report
{
/// <summary>
/// Verifies that a value is not null, and reports an error about a missing MEF component otherwise.
/// </summary>
/// <typeparam name="T">The interface of the imported part.</typeparam>
[DebuggerStepThrough]
internal static void IfNotPresent<T>(T part)
{
if (part == null)
{
Type coreType = PrivateErrorHelpers.TrimGenericWrapper(typeof(T), typeof(Lazy<>));
if (Environment.GetEnvironmentVariable("CPSUnitTest") != "true")
{
Fail(Strings.ServiceMissing, coreType.FullName);
}
}
}
/// <summary>
/// Reports an error if a condition evaluates to true.
/// </summary>
[DebuggerStepThrough]
internal static void If(bool condition, string message = null)
{
if (condition)
{
Fail(message);
}
}
/// <summary>
/// Reports an error if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
internal static void IfNot(bool condition, string message = null)
{
if (!condition)
{
Fail(message);
}
}
/// <summary>
/// Reports an error if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
internal static void IfNot(bool condition, string message, object arg1)
{
if (!condition)
{
Fail(PrivateErrorHelpers.Format(message, arg1));
}
}
/// <summary>
/// Reports an error if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
internal static void IfNot(bool condition, string message, object arg1, object arg2)
{
if (!condition)
{
Fail(PrivateErrorHelpers.Format(message, arg1, arg2));
}
}
/// <summary>
/// Reports an error if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
internal static void IfNot(bool condition, string message, params object[] args)
{
if (!condition)
{
Fail(PrivateErrorHelpers.Format(message, args));
}
}
/// <summary>
/// Reports a certain failure.
/// </summary>
[DebuggerStepThrough]
internal static void Fail(string message = null)
{
if (message == null)
{
message = "An internal error occurred.";
}
Debug.WriteLine(message);
Debug.Fail(message);
}
/// <summary>
/// Reports a certain failure.
/// </summary>
[DebuggerStepThrough]
internal static void Fail(string message, params object[] args)
{
Fail(PrivateErrorHelpers.Format(message, args));
}
}
}

Просмотреть файл

@ -0,0 +1,308 @@
//-----------------------------------------------------------------------
// <copyright file="Requires.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
/// <summary>
/// Common runtime checks that throw ArgumentExceptions upon failure.
/// </summary>
internal static class Requires
{
/// <summary>
/// Throws an exception if the specified parameter's value is null.
/// </summary>
/// <typeparam name="T">The type of the parameter.</typeparam>
/// <param name="value">The value of the argument.</param>
/// <param name="parameterName">The name of the parameter to include in any thrown exception.</param>
/// <returns>The value of the parameter.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is <c>null</c></exception>
[DebuggerStepThrough]
public static T NotNull<T>([ValidatedNotNull]T value, string parameterName)
where T : class // ensures value-types aren't passed to a null checking method
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
/// <summary>
/// Throws an exception if the specified parameter's value is IntPtr.Zero.
/// </summary>
/// <param name="value">The value of the argument.</param>
/// <param name="parameterName">The name of the parameter to include in any thrown exception.</param>
/// <returns>The value of the parameter.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is IntPtr.Zero</exception>
[DebuggerStepThrough]
public static IntPtr NotNull(IntPtr value, string parameterName)
{
if (value == IntPtr.Zero)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
/// <summary>
/// Throws an exception if the specified parameter's value is null or empty.
/// </summary>
/// <param name="value">The value of the argument.</param>
/// <param name="parameterName">The name of the parameter to include in any thrown exception.</param>
/// <exception cref="ArgumentException">Thrown if <paramref name="value"/> is <c>null</c> or empty.</exception>
[DebuggerStepThrough]
public static void NotNullOrEmpty([ValidatedNotNull]string value, string parameterName)
{
// To the guy that is doing random code cleaning:
// Consider the perfomance when changing the code to delegate to NotNull.
// In general do not chain call to another function, check first and return as earlier as possible.
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
if (value.Length == 0 || value[0] == '\0')
{
throw new ArgumentException(Format(Strings.Argument_EmptyString, parameterName), parameterName);
}
}
/// <summary>
/// Throws an exception if the specified parameter's value is null, empty, or whitespace.
/// </summary>
/// <param name="value">The value of the argument.</param>
/// <param name="parameterName">The name of the parameter to include in any thrown exception.</param>
/// <exception cref="ArgumentException">Thrown if <paramref name="value"/> is <c>null</c> or empty.</exception>
[DebuggerStepThrough]
public static void NotNullOrWhiteSpace([ValidatedNotNull]string value, string parameterName)
{
// To the guy that is doing random code cleaning:
// Consider the perfomance when changing the code to delegate to NotNull.
// In general do not chain call to another function, check first and return as earlier as possible.
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
if (value.Length == 0 || value[0] == '\0')
{
throw new ArgumentException(Format(Strings.Argument_EmptyString, parameterName), parameterName);
}
if (String.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(Format(Strings.Argument_Whitespace, parameterName));
}
}
/// <summary>
/// Throws an exception if the specified parameter's value is null,
/// has no elements or has an element with a null value.
/// </summary>
/// <param name="values">The value of the argument.</param>
/// <param name="parameterName">The name of the parameter to include in any thrown exception.</param>
/// <exception cref="ArgumentException">Thrown if the tested condition is false.</exception>
[DebuggerStepThrough]
public static void NotNullOrEmpty([ValidatedNotNull]System.Collections.IEnumerable values, string parameterName)
{
// To the guy that is doing random code cleaning:
// Consider the perfomance when changing the code to delegate to NotNull.
// In general do not chain call to another function, check first and return as earlier as possible.
if (values == null)
{
throw new ArgumentNullException(parameterName);
}
bool hasElements = false;
foreach (object value in values)
{
hasElements = true;
break;
}
if (!hasElements)
{
throw new ArgumentException(Format(Strings.Argument_EmptyArray, parameterName), parameterName);
}
}
/// <summary>
/// Throws an exception if the specified parameter's value is null,
/// has no elements or has an element with a null value.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequence.</typeparam>
/// <param name="values">The value of the argument.</param>
/// <param name="parameterName">The name of the parameter to include in any thrown exception.</param>
/// <exception cref="ArgumentException">Thrown if the tested condition is false.</exception>
[DebuggerStepThrough]
public static void NotNullEmptyOrNullElements<T>([ValidatedNotNull]IEnumerable<T> values, string parameterName)
where T : class // ensures value-types aren't passed to a null checking method
{
NotNull(values, parameterName);
bool hasElements = false;
foreach (T value in values)
{
hasElements = true;
if (value == null)
{
throw new ArgumentException(Format(Strings.Argument_NullElement, parameterName), parameterName);
}
}
if (!hasElements)
{
throw new ArgumentException(Format(Strings.Argument_EmptyArray, parameterName), parameterName);
}
}
/// <summary>
/// Throws an exception if the specified parameter's value is not null
/// <em>and</em> has an element with a null value.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequence.</typeparam>
/// <param name="values">The value of the argument.</param>
/// <param name="parameterName">The name of the parameter to include in any thrown exception.</param>
/// <exception cref="ArgumentException">Thrown if the tested condition is false.</exception>
[DebuggerStepThrough]
public static void NullOrNotNullElements<T>(IEnumerable<T> values, string parameterName)
{
if (values != null)
{
foreach (T value in values)
{
if (value == null)
{
throw new ArgumentException(Format(Strings.Argument_NullElement, parameterName), parameterName);
}
}
}
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
public static void Range(bool condition, string parameterName, string message = null)
{
if (!condition)
{
FailRange(parameterName, message);
}
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> if a condition does not evaluate to true.
/// </summary>
/// <returns>Nothing. This method always throws.</returns>
[DebuggerStepThrough]
public static Exception FailRange(string parameterName, string message = null)
{
if (String.IsNullOrEmpty(message))
{
throw new ArgumentOutOfRangeException(parameterName);
}
else
{
throw new ArgumentOutOfRangeException(parameterName, message);
}
}
/// <summary>
/// Throws an ArgumentException if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
public static void Argument(bool condition, string parameterName, string message)
{
if (!condition)
{
throw new ArgumentException(message, parameterName);
}
}
/// <summary>
/// Throws an ArgumentException if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
public static void Argument(bool condition, string parameterName, string message, object arg1)
{
if (!condition)
{
throw new ArgumentException(Format(message, arg1), parameterName);
}
}
/// <summary>
/// Throws an ArgumentException if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
public static void Argument(bool condition, string parameterName, string message, object arg1, object arg2)
{
if (!condition)
{
throw new ArgumentException(Format(message, arg1, arg2), parameterName);
}
}
/// <summary>
/// Throws an ArgumentException if a condition does not evaluate to true.
/// </summary>
[DebuggerStepThrough]
public static void Argument(bool condition, string parameterName, string message, params object[] args)
{
if (!condition)
{
throw new ArgumentException(Format(message, args), parameterName);
}
}
/// <summary>
/// Throws an ArgumentException.
/// </summary>
/// <returns>Nothing. It always throws.</returns>
[DebuggerStepThrough]
public static Exception Fail(string message)
{
throw new ArgumentException(message);
}
/// <summary>
/// Throws an ArgumentException.
/// </summary>
/// <returns>Nothing. It always throws.</returns>
[DebuggerStepThrough]
public static Exception Fail(string unformattedMessage, params object[] args)
{
throw Fail(Format(unformattedMessage, args));
}
/// <summary>
/// Throws an ArgumentException.
/// </summary>
[DebuggerStepThrough]
public static Exception Fail(Exception innerException, string unformattedMessage, params object[] args)
{
throw new ArgumentException(Format(unformattedMessage, args), innerException);
}
/// <summary>
/// Helper method that formats string arguments.
/// </summary>
private static string Format(string format, params object[] arguments)
{
return PrivateErrorHelpers.Format(format, arguments);
}
}
}

117
Microsoft.Validation/Strings.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,117 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17905
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.Validation {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Strings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Strings() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Validation.Strings", typeof(Strings).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; must contain at least one element..
/// </summary>
internal static string Argument_EmptyArray {
get {
return ResourceManager.GetString("Argument_EmptyArray", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; cannot be an empty string (&quot;&quot;) or start with the null character..
/// </summary>
internal static string Argument_EmptyString {
get {
return ResourceManager.GetString("Argument_EmptyString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; cannot contain a null (Nothing in Visual Basic) element..
/// </summary>
internal static string Argument_NullElement {
get {
return ResourceManager.GetString("Argument_NullElement", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The parameter &quot;{0}&quot; cannot consist entirely of white space characters..
/// </summary>
internal static string Argument_Whitespace {
get {
return ResourceManager.GetString("Argument_Whitespace", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An internal error occurred. Please contact Microsoft Product Support Services..
/// </summary>
internal static string InternalExceptionMessage {
get {
return ResourceManager.GetString("InternalExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot find an instance of the {0} service..
/// </summary>
internal static string ServiceMissing {
get {
return ResourceManager.GetString("ServiceMissing", resourceCulture);
}
}
}
}

Просмотреть файл

@ -0,0 +1,138 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Argument_EmptyArray" xml:space="preserve">
<value>'{0}' must contain at least one element.</value>
</data>
<data name="Argument_EmptyString" xml:space="preserve">
<value>'{0}' cannot be an empty string ("") or start with the null character.</value>
</data>
<data name="Argument_NullElement" xml:space="preserve">
<value>'{0}' cannot contain a null (Nothing in Visual Basic) element.</value>
</data>
<data name="Argument_Whitespace" xml:space="preserve">
<value>The parameter "{0}" cannot consist entirely of white space characters.</value>
</data>
<data name="InternalExceptionMessage" xml:space="preserve">
<value>An internal error occurred. Please contact Microsoft Product Support Services.</value>
</data>
<data name="ServiceMissing" xml:space="preserve">
<value>Cannot find an instance of the {0} service.</value>
</data>
</root>

Просмотреть файл

@ -0,0 +1,26 @@
//-----------------------------------------------------------------------
// <copyright file="ValidatedNotNullAttribute.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Indicates to Code Analysis that a method validates a particular parameter.
/// </summary>
[ExcludeFromCodeCoverage]
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
internal sealed class ValidatedNotNullAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ValidatedNotNullAttribute"/> class.
/// </summary>
public ValidatedNotNullAttribute()
{
}
}
}

Просмотреть файл

@ -0,0 +1,192 @@
//-----------------------------------------------------------------------
// <copyright file="Verify.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Validation
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
/// <summary>
/// Common runtime checks that throw exceptions upon failure.
/// </summary>
internal static class Verify
{
/// <summary>
/// Indicates what the desired behavior is in the event of a failure.
/// </summary>
internal enum ErrorBehavior
{
/// <summary>
/// An exception should be (re)thrown.
/// </summary>
Throw,
/// <summary>
/// An error should be reported to the user, but then execution flow should resume.
/// </summary>
Report,
/// <summary>
/// An error should be quietly logged, and then execution flow should resume.
/// </summary>
Log,
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if a condition is false.
/// </summary>
[DebuggerStepThrough]
internal static void Operation(bool condition, string message)
{
if (!condition)
{
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if a condition is false.
/// </summary>
[DebuggerStepThrough]
internal static void Operation(bool condition, string unformattedMessage, object arg1)
{
if (!condition)
{
throw new InvalidOperationException(PrivateErrorHelpers.Format(unformattedMessage, arg1));
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if a condition is false.
/// </summary>
[DebuggerStepThrough]
internal static void Operation(bool condition, string unformattedMessage, object arg1, object arg2)
{
if (!condition)
{
throw new InvalidOperationException(PrivateErrorHelpers.Format(unformattedMessage, arg1, arg2));
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if a condition is false.
/// </summary>
[DebuggerStepThrough]
internal static void Operation(bool condition, string unformattedMessage, params object[] args)
{
if (!condition)
{
throw new InvalidOperationException(PrivateErrorHelpers.Format(unformattedMessage, args));
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if a condition is false.
/// </summary>
[DebuggerStepThrough]
internal static void OperationWithHelp(bool condition, string message, string helpLink)
{
if (!condition)
{
var ex = new InvalidOperationException(message);
ex.HelpLink = helpLink;
throw ex;
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/>.
/// </summary>
[DebuggerStepThrough]
internal static void FailOperation(string message, params object[] args)
{
throw new InvalidOperationException(PrivateErrorHelpers.Format(message, args));
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if an object is disposed.
/// </summary>
[DebuggerStepThrough]
internal static void NotDisposed(IDisposableObservable disposedValue, string message = null)
{
Contract.Requires<ArgumentNullException>(disposedValue != null);
if (disposedValue.IsDisposed)
{
string objectName = disposedValue != null ? disposedValue.GetType().FullName : String.Empty;
if (message != null)
{
throw new ObjectDisposedException(objectName, message);
}
else
{
throw new ObjectDisposedException(objectName);
}
}
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if a condition is false.
/// </summary>
[DebuggerStepThrough]
internal static void NotDisposed(bool condition, object disposedValue, string message = null)
{
if (!condition)
{
string objectName = disposedValue != null ? disposedValue.GetType().FullName : String.Empty;
if (message != null)
{
throw new ObjectDisposedException(objectName, message);
}
else
{
throw new ObjectDisposedException(objectName);
}
}
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if a condition is false.
/// </summary>
[DebuggerStepThrough]
internal static void NotDisposed(bool condition, string message)
{
if (!condition)
{
throw new ObjectDisposedException(message);
}
}
/// <summary>
/// Throws an exception if the given value is negative.
/// </summary>
/// <param name="hresult">The HRESULT corresponding to the desired exception.</param>
/// <param name="ignorePreviousComCalls">If true, prevents <c>ThrowExceptionForHR</c> from returning an exception from a previous COM call and instead always use the HRESULT specified.</param>
/// <remarks>
/// No exception is thrown for S_FALSE.
/// </remarks>
[DebuggerStepThrough]
internal static void HResult(int hresult, bool ignorePreviousComCalls = false)
{
if (hresult < 0)
{
if (ignorePreviousComCalls)
{
Marshal.ThrowExceptionForHR(hresult, new IntPtr(-1));
}
else
{
Marshal.ThrowExceptionForHR(hresult);
}
}
}
}
}