public static void FireErrors(IScope t)
 {
     t.Error("ErrA");
     using (var scope = t.Create("Nested"))
     {
         scope.Error("ErrB");
     }
     t.Error("ErrC");
 }
Exemple #2
0
 public static void FireErrors(IScope t)
 {
     t.Error("ErrA");
     using (var scope = t.Create("Nested"))
     {
         scope.Error("ErrB");
     }
     t.Error("ErrC");
 }
        bool TestCollectionEquality(IScope scope, IEnumerable expected, IEnumerable actual, int count1, int count2)
        {
            if (count1 != count2)
            {
                scope.Error("Expected ICollection count {0} was {1}", count1, count2);
                return(false);
            }

            if (count1 == 0)
            {
                return(true);
            }

            var e1 = expected.GetEnumerator();
            var e2 = actual.GetEnumerator();

            bool equals = true;

            for (int i = 0; i < count1; i++)
            {
                e1.MoveNext();
                e2.MoveNext();

                using (var child = scope.Create("[" + i + "]"))
                {
                    bool result;
                    if (TryReferenceCheck(child, e1.Current, e2.Current, out result))
                    {
                        equals |= result;
                    }
                    else
                    {
                        var t1 = e1.Current.GetType();
                        var t2 = e2.Current.GetType();

                        if (t1 != t2)
                        {
                            scope.Error("Expected '{0}' was '{1}'", t1, t2);
                            equals = false;
                        }
                        else
                        {
                            var tester = _provider.GetEqualityTester(t1);

                            if (!tester(child, t1, e1.Current, e2.Current))
                            {
                                equals = false;
                            }
                        }
                    }
                }
            }
            return(equals);
        }
Exemple #4
0
        // actual rules.

        // we assume that good citizenship is enforced (no need to check for nulls)
        public static void NameRules(string value, IScope scope)
        {
            // rules are plain .NET code
            if (value.Length == 0)
            {
                scope.Error("String can not be empty");
            }
            if (value.Length > 2500)
            {
                scope.Error("Length must be less than 2500");
            }
        }
        /// <summary>
        /// Runs validation rules against some some <see cref="IEnumerable{T}"/>.
        /// </summary>
        /// <typeparam name="T">type of the items being validated</typeparam>
        /// <param name="parentScope">The parent scope.</param>
        /// <param name="items">Collection of the items to validate</param>
        /// <param name="rules">The rules to run.</param>
        public static void ValidateInScope <T>(this IScope parentScope, IEnumerable <T> items, params Rule <T>[] rules)
        {
            if (parentScope == null)
            {
                throw new ArgumentNullException("parentScope");
            }

            if (items == null)
            {
                parentScope.Error("Collection of type \'{0}\' should not be null.", typeof(T).Name);
            }
            else
            {
                int i = 0;

                foreach (var item in items)
                {
                    using (var scope = parentScope.Create("[" + i + "]"))
                    {
                        scope.CheckObject(item, rules);
                    }
                    i += 1;
                }
            }
        }
Exemple #6
0
 public static void SanitationRules(string value, IScope scope)
 {
     if (value.Contains("-"))
     {
         scope.Error("Can not contain '-'");
     }
 }
Exemple #7
0
 /// <summary>
 /// Determines whether the string is valid server connection (with optional port)
 /// </summary>
 /// <param name="host">The host name to validate.</param>
 /// <param name="scope">The validation scope.</param>
 public static void ValidServerConnection(string host, IScope scope)
 {
     if (!ServerConnectionRegex.IsMatch(host))
     {
         scope.Error("String should be a valid host name.");
     }
 }
Exemple #8
0
 /// <summary>
 /// Verifies that it is ok to send this date directly into the MS SQL DB
 /// </summary>
 /// <param name="dateTime">The dateTime to validate.</param>
 /// <param name="scope">validation scope</param>
 public static void SqlCompatible(DateTime dateTime, IScope scope)
 {
     if (dateTime < SqlMinDateTime)
     {
         scope.Error("Date must be greater than \'{0}\'.", SqlMinDateTime);
     }
 }
Exemple #9
0
 /// <summary>
 /// Returns error if the provided value type has default value
 /// </summary>
 /// <typeparam name="T">value type to check</typeparam>
 /// <param name="item">The item.</param>
 /// <param name="scope">The scope.</param>
 public static void NotDefault <T>(T item, IScope scope) where T : struct
 {
     if (default(T).Equals(item))
     {
         scope.Error("Value should not be equal to \'{0}\'.", default(T));
     }
 }
 /// <summary>
 /// Checks if the specified double is valid.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="scope">The scope.</param>
 public static void Valid(double value, IScope scope)
 {
     if (Double.IsNaN(value) || Double.IsInfinity(value))
     {
         scope.Error("Double should represent a valid value.");
     }
 }
Exemple #11
0
 /// <summary>
 /// Determines whether the string is valid email address
 /// </summary>
 /// <param name="email">string to validate</param>
 /// <param name="scope">validation scope.</param>
 public static void ValidEmail(string email, IScope scope)
 {
     if (!EmailRegex.IsMatch(email))
     {
         scope.Error("String should be a valid email address.");
     }
 }
 public static void ProgramRules(Program program, IScope scope)
 {
     // custom logic
     if (!program.Active) scope.Error("Program must be active");
     // passing member validation down to the next ruleset
     // (note, that we have multiple rulesets here)
     scope.Validate(program.Name, "Name", NameRules, SanitationRules);
 }
        static bool TestSimpleEquality(IScope scope, object expected, object actual)
        {
            var result = expected.Equals(actual);

            if (!result)
            {
                scope.Error("Object equality failed. Expected '{0}' was '{1}'.", expected, actual);
            }
            return(result);
        }
        static bool TestGenericEquality(IScope scope, MethodInfo info, object expected, object actual)
        {
            var o      = info.Invoke(expected, new[] { actual });
            var result = Convert.ToBoolean(o);

            if (!result)
            {
                scope.Error("Expected IEquatable<T> '{0}' was '{1}'.", expected, actual);
            }
            return(result);
        }
Exemple #15
0
 public static void ProgramRules(Program program, IScope scope)
 {
     // custom logic
     if (!program.Active)
     {
         scope.Error("Program must be active");
     }
     // passing member validation down to the next ruleset
     // (note, that we have multiple rulesets here)
     scope.Validate(program.Name, "Name", NameRules, SanitationRules);
 }
        static void Ncca_Is_Used_Properly(Codebase codebase, IScope scope, int maxInstructions)
        {
            var methods = codebase.Methods
                .Where(m => m.HasBody && m.Body.Instructions.Count > maxInstructions)
                .Where(m => m.Has<NoCodeCoverageAttribute>() ||
                    m.DeclaringType.Has<NoCodeCoverageAttribute>());

            foreach (var method in methods)
            {
                scope.Error("Method is too complex to be marked with NCCA: {0}", method);
            }
        }
Exemple #17
0
        static void Ncca_Is_Used_Properly(Codebase codebase, IScope scope, int maxInstructions)
        {
            var methods = codebase.Methods
                          .Where(m => m.HasBody && m.Body.Instructions.Count > maxInstructions)
                          .Where(m => m.Has <NoCodeCoverageAttribute>() ||
                                 m.DeclaringType.Has <NoCodeCoverageAttribute>());

            foreach (var method in methods)
            {
                scope.Error("Method is too complex to be marked with NCCA: {0}", method);
            }
        }
 public static void ProgramsRules(Program[] programs, IScope scope)
 {
     // Validating items of a collection
     if (programs.Length > 2500)
     {
         scope.Error("Only 2500 programs are allowed");
     }
     else
     {
         // every item will be validated (or only till the first exception hits,
         // that's for the scope to decide
         scope.ValidateInScope(programs, ProgramRules);
     }
 }
Exemple #19
0
        /// <summary>
        /// Ensures that classes marked with <see cref="ImmutableAttribute"/> have only
        /// readonly fields
        /// </summary>
        /// <param name="codebase">The codebase to run against.</param>
        /// <param name="scope">The scope to report to.</param>
        public static void Immutable_Types_Should_Be_Immutable(Codebase codebase, IScope scope)
        {
            var decorated = codebase.Types
                            .Where(t => t.Has <ImmutableAttribute>());

            var failing = decorated
                          .Where(t => t.GetAllFields(codebase)
                                 .Count(f => !f.IsInitOnly && !f.IsStatic) > 0);

            foreach (var definition in failing)
            {
                scope.Error("Type should be immutable: {0}", definition);
            }
        }
        /// <summary>
        /// Ensures that classes marked with <see cref="ImmutableAttribute"/> have only
        /// readonly fields
        /// </summary>
        /// <param name="codebase">The codebase to run against.</param>
        /// <param name="scope">The scope to report to.</param>
        public static void Immutable_Types_Should_Be_Immutable(Codebase codebase, IScope scope)
        {
            var decorated = codebase.Types
                .Where(t => t.Has<ImmutableAttribute>());

            var failing = decorated
                .Where(t => t.GetAllFields(codebase)
                    .Count(f => !f.IsInitOnly && !f.IsStatic) > 0);

            foreach (var definition in failing)
            {
                scope.Error("Type should be immutable: {0}", definition);
            }
        }
Exemple #21
0
 public static void ProgramsRules(Program[] programs, IScope scope)
 {
     // Validating items of a collection
     if (programs.Length > 2500)
     {
         scope.Error("Only 2500 programs are allowed");
     }
     else
     {
         // every item will be validated (or only till the first exception hits,
         // that's for the scope to decide
         scope.ValidateInScope(programs, ProgramRules);
     }
 }
 static void CheckObject <T>(this IScope self, T item, params Rule <T>[] rules)
 {
     // [abdullin]: I know
     // ReSharper disable CompareNonConstrainedGenericWithNull
     if (item == null)
     // ReSharper restore CompareNonConstrainedGenericWithNull
     {
         self.Error("Object of type \'{0}\' should not be null.", typeof(T).Name);
     }
     else
     {
         foreach (var rule in rules)
         {
             rule(item, self);
         }
     }
 }
        static bool TryReferenceCheck(IScope scope, object expected, object actual, out bool result)
        {
            var expectedIsNull = ReferenceEquals(expected, null);
            var actualIsNull   = ReferenceEquals(actual, null);

            if (expectedIsNull && actualIsNull)
            {
                result = true;
                return(true);
            }

            if (expectedIsNull || actualIsNull)
            {
                var expectedString = expectedIsNull ? "<null>" : expected.GetType().Name;
                var actualString   = actualIsNull ? "<null>" : actual.GetType().Name;

                result = false;
                scope.Error("Expected {0} was {1}", expectedString, actualString);
                return(true);
            }
            result = false;
            return(false);
        }
		static bool TestSimpleEquality(IScope scope, object expected, object actual)
		{
			var result = expected.Equals(actual);
			if (!result)
			{
				scope.Error("Object equality failed. Expected '{0}' was '{1}'.", expected, actual);
			}
			return result;
		}
		static bool TestGenericEquality(IScope scope, MethodInfo info, object expected, object actual)
		{
			var o = info.Invoke(expected, new[] {actual});
			var result = Convert.ToBoolean(o);
			if (!result)
			{
				scope.Error("Expected IEquatable<T> '{0}' was '{1}'.", expected, actual);
			}
			return result;
		}
		bool TestCollectionEquality(IScope scope, IEnumerable expected, IEnumerable actual, int count1, int count2)
		{
			if (count1 != count2)
			{
				scope.Error("Expected ICollection count {0} was {1}", count1, count2);
				return false;
			}

			if (count1 == 0)
			{
				return true;
			}

			var e1 = expected.GetEnumerator();
			var e2 = actual.GetEnumerator();

			bool equals = true;

			for (int i = 0; i < count1; i++)
			{
				e1.MoveNext();
				e2.MoveNext();

				using (var child = scope.Create("[" + i + "]"))
				{
					bool result;
					if (TryReferenceCheck(child, e1.Current, e2.Current, out result))
					{
						equals |= result;
					}
					else
					{
						var t1 = e1.Current.GetType();
						var t2 = e2.Current.GetType();

						if (t1 != t2)
						{
							scope.Error("Expected '{0}' was '{1}'", t1, t2);
							equals = false;
						}
						else
						{
							var tester = _provider.GetEqualityTester(t1);

							if (!tester(child, t1, e1.Current, e2.Current))
							{
								equals = false;
							}
						}
					}
				}
			}
			return equals;
		}
		static bool TryReferenceCheck(IScope scope, object expected, object actual, out bool result)
		{
			var expectedIsNull = ReferenceEquals(expected, null);
			var actualIsNull = ReferenceEquals(actual, null);
			if (expectedIsNull && actualIsNull)
			{
				result = true;
				return true;
			}

			if (expectedIsNull || actualIsNull)
			{
				var expectedString = expectedIsNull ? "<null>" : expected.GetType().Name;
				var actualString = actualIsNull ? "<null>" : actual.GetType().Name;

				result = false;
				scope.Error("Expected {0} was {1}", expectedString, actualString);
				return true;
			}
			result = false;
			return false;
		}
 public static void SanitationRules(string value, IScope scope)
 {
     if (value.Contains("-")) scope.Error("Can not contain '-'");
 }
		/// <summary>
		/// Determines whether the string is valid email address
		/// </summary>
		/// <param name="email">string to validate</param>
		/// <param name="scope">validation scope.</param>
		public static void ValidEmail(string email, IScope scope)
		{
			if (!EmailRegex.IsMatch(email))
				scope.Error("String should be a valid email address.");
		}
		/// <summary>
		/// Determines whether the string is valid server connection (with optional port)
		/// </summary>
		/// <param name="host">The host name to validate.</param>
		/// <param name="scope">The validation scope.</param>
		public static void ValidServerConnection(string host, IScope scope)
		{
			if (!ServerConnectionRegex.IsMatch(host))
				scope.Error("String should be a valid host name.");
		}
 /// <summary>
 /// Checks if the specified double is valid.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="scope">The scope.</param>
 public static void Valid(double value, IScope scope)
 {
     if (Double.IsNaN(value) || Double.IsInfinity(value))
         scope.Error("Double should represent a valid value.");
 }
 // actual rules.
 // we assume that good citizenship is enforced (no need to check for nulls)
 public static void NameRules(string value, IScope scope)
 {
     // rules are plain .NET code
     if (value.Length == 0) scope.Error("String can not be empty");
     if (value.Length > 2500) scope.Error("Length must be less than 2500");
 }
 /// <summary>
 /// Verifies that it is ok to send this date directly into the MS SQL DB
 /// </summary>
 /// <param name="dateTime">The dateTime to validate.</param>
 /// <param name="scope">validation scope</param>
 public static void SqlCompatible(DateTime dateTime, IScope scope)
 {
     if (dateTime < SqlMinDateTime)
         scope.Error("Date must be greater than \'{0}\'.", SqlMinDateTime);
 }