Code Monkey home page Code Monkey logo

vs-validation's Introduction

Microsoft.VisualStudio.Validation

NuGet package Build Status codecov

This project is available as the Microsoft.VisualStudio.Validation NuGet package.

Basic input validation via the Requires class throws an ArgumentException.

Requires.NotNull(arg1, nameof(arg1));
Requires.NotNullOrEmpty(arg2, nameof(arg2));

State validation via the Verify class throws an InvalidOperationException.

Verify.Operation(condition, "some error occurred.");

Internal integrity checks via the Assumes class throws an InternalErrorException.

Assumes.True(condition, "some error");

Warning signs that should not throw exceptions via the Report class.

Report.IfNot(condition, "some error");

vs-validation's People

Contributors

aarnott avatar adrianvmsft avatar crmann1 avatar csigs avatar csiusers avatar danieleoh avatar danyeh avatar dependabot[bot] avatar devlead avatar drewnoakes avatar eilon avatar iron9light avatar juchom avatar kartheekp-ms avatar khoiph1 avatar matteo-prosperi avatar mohit-chakraborty avatar scottdorman avatar stevebush avatar trevors20 avatar v-zbsail avatar vivlimmsft avatar xuachen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vs-validation's Issues

For 3rd party usage of this library, allow customing default exception messages to not mention Microsoft Support

This library is used outside of VS, for example in the Git Extensions project (which also uses JTF and vs-mef).

Currently a violation of e.g. Assumes.NotNull produces an exception with message:

An internal error occurred. Please contact Microsoft Support.

Microsoft does not provide support for Git Extensions :)

What's more, the InternalErrorException exception type is private so the library cannot easily trap these and switch them.

Requires.NotNull should accept values of type `T?`

https://dotnetfiddle.net/rB8FPD

In the following code, the Requires.NotNull call displays a warning

image

The Requires.NotNull function should accept values of type T? instead of T

#nullable enable

using System;
using Microsoft;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("Hello World");
		
		Foo? str = null;

		Requires.NotNull(str, "");
	}
	
	private class Foo {
	}
}

Add analyzer and code fix provider for Requires.NotNull/Range

When the caret is positioned on a parameter declaration for a reference type, we should offer a code fix to add:

Requires.NotNull(p1, nameof(p1));

Similarly, when positioned on an integer/float parameter declaration, we can offer a code fix to add:

Requires.Range(p1 >= 0, nameof(p1));

Replace the single-iteration foreach loops

The single-iteration foreach loops in Requires.NotNullOrEmpty(IEnumerable values, string? parameterName) and Requires.NotNullOrEmpty<T>(IEnumerable<T> values, string? parameterName) can be replaced by a direct call to GetEnumerator().MoveNext(). This results in a slight performance boost and fewer IL instructions generated.

Add helper for adding data to an exception while throwing it

The actual code is below, which could be used as follows.

            throw new ArgumentException("Overlapping spans").AddData(bufferSpans.Key, bufferSpans.Value[s], bufferSpans.Value[s - 1]);
// or
            throw new ArgumentException("Overlapping spans").Modify((e) => e.Data.Add("bufferSpans", bufferSpans));
    public static class ExceptionsWithData
    {
        /// <summary>
        /// Add <paramref name="data"/> to the Data member of <paramref name="e"/> before returning the modified exception.
        /// </summary>
        /// <remarks>
        /// <para>This method should be used to add context (beyond the message and callstack we normally get) to the exception
        /// that would be useful when debugging Watson crashes.</para>
        /// <para>Do not use this method when you expect the exception to be handled.</para>
        /// </remarks>
        public static T AddData<T>(this T e, params object[] data) where T : Exception
        {
            if (data.Length > 0)
            {
                e.Data.Add("AddData", data);
            }
 
            return e;
        }
 
        /// <summary>
        /// Modify <paramref name="e"/> by performing <paramref name="action"/> on it before returning the modified exception.
        /// </summary>
        /// <remarks>
        /// <para>This method should be used to add context (beyond the message and callstack we normally get) to the exception
        /// that would be useful when debugging Watson crashes.</para>
        /// <para>Do not use this method when you expect the exception to be handled.</para>
        /// </remarks>
        public static T Modify<T>(this T e, Action<T> action) where T : Exception
        {
            if (action != null)
            {
                action(e);
            }
 
            return e;
        }
    }

Overload Requires.NotNullOrEmpty to avoid enumerator allocation

I'm looking at a CPS trace where Requires.NotNullOrEmpty is allocating a fair number of enumerators. The type is statically known to implement IReadOnlyCollection<T>, so an overload that accepted that type could make the cheaper call to Count.

Unfortunately it's unclear which interfaces to support. With overloads for both ICollection<T> and IReadOnlyCollection<T>, calling Requires.NotNullOrEmpty(new List<int>(), "") would not compile due to ambiguity, which isn't a great experience. Is there a clean way to get this benefit for common types without runtime type checks?

I can rewrite the code to avoid the allocations, but it'd be better if this applied across the board for free by simply compiling against a newer version of the library.

Nuget package is getting flagged by ClearlyDefined as containing source code under LGPL-2.1 license

Hi,

We use ClearlyDefined for information about licenses used in software that we reference. Following text in the NOTICE file is causing ClearlyDefine to recognize the package as containing source code licensed under LGPL-2:

Notwithstanding any other terms, you may reverse engineer this software to the extent
required to debug changes to any libraries licensed under the GNU Lesser General Public License.

Can you change the wording to eliminate references to GNU LGPL?

Thanks!

.NET Core SDK adoption blockers

This issue tracks the adoption blocker issues to switching to the .NET Core project system in VS2017:

Functional issues

  • dotnet/Nerdbank.GitVersioning#93 Nerdbank.GitVersioning interop with .NET SDK
  • dotnet/sdk#703 DocumentationFile cannot be set in project file
  • dotnet/sdk#651 AssemblyInfo.cs should not be generated on package restore
  • XLF -> resx generation support (ideally via full Multilingual App Toolkit support)
  • ReadOnlySourceTree package support in and for .NET SDK
  • MicroBuild signing plugin support in and for .NET SDK
  • Get unit tests running at least on net45 if not also netcoreapp1.0
  • Verify that pdbgit works properly
  • novotnyllc/MSBuildSdkExtras#6 Get nupkg lib folders right.
  • Must be able to run Microsoft ship requirement set of FxCop rules (FxCop port)
  • Totally portable toolset so it can run without VS2017 installation, or VS2017 installed on MicroBuild agents

Reliability issues

  • dotnet/roslyn#16410 VS crashes on open of .NET Core projects far too frequently
  • dotnet/roslyn#16673 VS crashes when SolutionCreator.UpdateDocumentAsync gets NullReferenceException back over jsonrpc
  • NuGet/Home#4289 PackTask frequently fails with file access conflict

Non-blocking (because some workaround exists) but tracking

Please release a more recent version of this package

I'm currently trying to update dependencies in my solution to versions corresponding to the new VS version, but I'm running into a problem: the NuGet Package Microsoft.VisualStudio.LanguageServices in version 4.5.0-2.final references Mcirosoft.VisualStudio.Validation in version >= 17.0.71 but the only available non-prerelease version of it on NuGet is 17.0.65.

Could you please release a more recent non-prerelease version of this package on NuGet? Thanks in advance!

Add NotDefault and ValidElements

It would be nice to have a convenience method on Requires which easily allows validating a collection against a predicate. This method could look similar to:

[DebuggerStepThrough]
public static void ValidElements<T>([ValidatedNotNull] IEnumerable<T>? values, Predicate<T> predicate, string parameterName, string message)
{
    if (predicate is null)
    {
        throw new ArgumentNullException(nameof(predicate));
    }

    if (values is object)
    {
        foreach (T value in values)
        {
            if (!predicate(value))
            {
                throw new ArgumentException(message, parameterName);
            }
        }
    }
}

This could then be used like

public void SetFieldWidths(params int[] fieldWidths)
{
    Requires.NotNullOrEmpty(fieldWidths, nameof(fieldWidths));
    Requires.ValidElements(fieldWidths.SkipLast(1), fw => fw >= 0, "All width's except the last must be greater than 0", nameof(fieldWidths));
}

Similarly, adding a Requires.NotDefault<T> for enums.

Incorrect description of Requires.NotNullOrEmpty for enumerables

The description of Requires.NotNullOrEmpty mentions the following:

Throws an exception if the specified parameter is null, has no elements or has an element with a null value.

It confused me for a second that caused me to check the source code to see what it's actually doing.
This method does not check if there's an element that's null. There's Requires.NotNullEmptyOrNullElements for that. This is what I expected, but the summary is incorrect in this case.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.