Ejemplo n.º 1
0
        private static string GetMethod(StackFrame frame)
        {
            Assumption.AssertNotNull(frame, nameof(frame));

            MethodBase?method = frame.GetMethod();

            if (method == null)
            {
                return(frame.ToString());
            }

            var methodName = method.Name;

            if (method.ReflectedType != null)
            {
                methodName = string.Format("{0}.{1}", method.ReflectedType.FullName, methodName);
            }

            var parameters = method.GetParameters();

            if (parameters.Length > 0)
            {
                return(string.Format("{0}({1})", methodName, string.Join(", ", parameters.Select(p => string.Format("{0} {1}", p.ParameterType, p.Name)))));
            }

            return(string.Format("{0}()", methodName));
        }
Ejemplo n.º 2
0
 public LogItem(MethodBase?method, string message, LogLevel level)
 {
     Method   = method;
     Message  = message;
     DateTime = DateTime.Now;
     Level    = level;
 }
Ejemplo n.º 3
0
        private static string GetFileName(StackFrame frame)
        {
            Assumption.AssertNotNull(frame, nameof(frame));

            string?returnVal = defaultFileName;

            if (frame == null)
            {
                return(returnVal);
            }

            returnVal = frame.GetFileName();
            if (!string.IsNullOrWhiteSpace(returnVal))
            {
                return(returnVal);
            }

            MethodBase?method = frame.GetMethod();

            if (method != null && method.ReflectedType != null)
            {
                returnVal = method.ReflectedType.FullName;
            }
            if (!string.IsNullOrWhiteSpace(returnVal))
            {
                return(returnVal);
            }

            return(defaultFileName);
        }
Ejemplo n.º 4
0
        internal static void Log(LogConfiguration config, MethodBase?method, string message, LogLevel level)
        {
            if (level < config.LogLevel)
            {
                return;
            }

            lock (configLock)
            {
                // If we race, we may hit this lock first. So we should always make sure that the buffer
                // is initialized before we use it.
                if (!logs.ContainsKey(config))
                {
                    logs.Add(config, new List <LogItem>());
                    logSize.Add(config, 0);
                }

                logs[config].Add(new LogItem(method, message, level));
            }

            lock (logBufferInUseLock)
            {
                logBufferInUse = true;
            }
        }
Ejemplo n.º 5
0
        private static bool IsNamespaceIgnored(MethodBase?method)
        {
            if (method == null || method.DeclaringType == null || string.IsNullOrWhiteSpace(method.DeclaringType.Namespace))
            {
                return(false);
            }

            var ns = method.DeclaringType.Namespace;

            foreach (var item in IgnoredNamespaces)
            {
                if (item.EndsWith("*"))
                {
                    if (ns.StartsWith(item.TrimEnd('*'), StringComparison.OrdinalIgnoreCase))
                    {
                        return(true);
                    }
                }

                if (item.Equals(ns, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 6
0
        public static MethodBase?Resolve(this MethodRef?methodRef)
        {
            if (methodRef == null)
            {
                return(null);
            }

            MethodBase?method = null;

            if (TryUseFastReflection(methodRef.DeclaringType, out Module manifest))
            {
                method = manifest.ResolveMethod(methodRef.MetadataToken);
            }
            else
            {
                TypeInfo declaringType = methodRef.DeclaringType.ResolvedType.GetTypeInfo();
                var      candidates    = methodRef.Name == ConstructorInfo.ConstructorName
                    ? (MethodBase[])declaringType.GetConstructors(AllInstanceMembers)
                    : declaringType.GetMethods(AllMembers);
                method = FindMethodByParameters(candidates, methodRef.Name, methodRef.ParameterTypes);
            }

            if (method is null)
            {
                throw new InvalidOperationException("Unable to find method: " + methodRef);
            }

            if (methodRef.GenericMethodArguments.Length > 0)
            {
                var constructedMethod = ((MethodInfo)method).MakeGenericMethod(methodRef.GenericMethodArguments.Select(Resolve).ToArray() !);
                return(constructedMethod);
            }

            return(method);
        }
Ejemplo n.º 7
0
    /// <summary>
    /// The constructor of the 'ParameterBase' class. 
    /// </summary>
    /// <param name="commandName">The command as used on the command line.</param>
    /// <param name="commandAssembly">The assembly which implements the command.</param>
    /// <param name="displayHelper">A displayHelper for the message rendering.</param>
    /// <exception cref="System.ArgumentException"></exception>
    public ParameterBase(String commandName, Assembly commandAssembly, IDisplayHelper? displayHelper = null)
    {
      MethodBase? methodBase = MethodBase.GetCurrentMethod();

      if (commandAssembly == null)
      {
        throw new System.ArgumentException($"The argument '{nameof(commandAssembly)}' must not be null in function '{methodBase?.ReflectedType?.Name}.ctor'");
      }
      this.CommandAssembly = commandAssembly;

      if (String.IsNullOrWhiteSpace(commandName))
      {
        throw new System.ArgumentException($"The argument '{nameof(commandName)}' must not be null or empty in function '{methodBase?.ReflectedType?.Name}.ctor'");
      }
      this.CommandName = commandName;

      this.DisplayHelper = displayHelper;

      //
      // Fill the 'PropertyMetaInfoList' with each property that qualifies as 
      // parameter property and isn't marked as internal.
      //
      this.PropertyMetaInfoList = this.GetType().GetProperties()
      .Where(prop => prop.CanRead && prop.CanWrite)
      .Where(prop => prop.GetGetMethod() != null)
      .Where(prop => prop.GetSetMethod() != null)
      .Select(prop => new PropertyMetaInfo(prop))
      .Where(propMetaInfo => !propMetaInfo.IsInternal).ToList();
    }
Ejemplo n.º 8
0
        public static bool TryPatch(this Harmony harmony, MethodBase?original, MethodInfo?prefix = null, MethodInfo?postfix = null, MethodInfo?transpiler = null, MethodInfo?finalizer = null)
        {
            if (original is null || (prefix is null && postfix is null && transpiler is null && finalizer is null))
            {
                Trace.TraceError($"HarmonyExtensions.TryPatch: 'original' or all methods are null");
                return(false);
            }

            var prefixMethod     = prefix is null ? null : new HarmonyMethod(prefix);
            var postfixMethod    = postfix is null ? null : new HarmonyMethod(postfix);
            var transpilerMethod = transpiler is null ? null : new HarmonyMethod(transpiler);
            var finalizerMethod  = finalizer is null ? null : new HarmonyMethod(finalizer);

            try
            {
                harmony.Patch(original, prefixMethod, postfixMethod, transpilerMethod, finalizerMethod);
            }
            catch (Exception e)
            {
                Trace.TraceError($"HarmonyExtensions.TryPatch: Exception occurred: {e}, original '{original}'");
                return(false);
            }

            return(true);
        }
Ejemplo n.º 9
0
    public static string GetTypeName()
    {
        StackTrace trace = new StackTrace();
        StackFrame?frame = trace.GetFrame(3);

        if (frame is null)
        {
            return(string.Empty);
        }
        MethodBase?method = frame.GetMethod();

        if (method is null)
        {
            return(string.Empty);
        }
        Type?declaringType = method.DeclaringType;

        if (declaringType is null)
        {
            return(string.Empty);
        }
        string?name = declaringType.ReflectedType?.FullName;

        if (string.IsNullOrEmpty(name))
        {
            return(declaringType.FullName ?? string.Empty);
        }
        return(name);
    }
Ejemplo n.º 10
0
        private string?CreateSourceName()
        {
            StackTrace st = new StackTrace(this, fNeedFileInfo: false);

            if (st.FrameCount > 0)
            {
                StackFrame sf     = st.GetFrame(0) !;
                MethodBase?method = sf.GetMethod();
                if (method == null)
                {
                    return(null);
                }

                Module module = method.Module;

                if (!(module is RuntimeModule rtModule))
                {
                    if (module is System.Reflection.Emit.ModuleBuilder moduleBuilder)
                    {
                        rtModule = moduleBuilder.InternalModule;
                    }
                    else
                    {
                        throw new ArgumentException(SR.Argument_MustBeRuntimeReflectionObject);
                    }
                }

                return(rtModule.GetRuntimeAssembly().GetSimpleName());
            }

            return(null);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Implement explicit overload selection using subscript syntax ([]).
        /// </summary>
        public static NewReference mp_subscript(BorrowedReference tp, BorrowedReference idx)
        {
            var self = (OverloadMapper)GetManagedObject(tp) !;

            // Note: if the type provides a non-generic method with N args
            // and a generic method that takes N params, then we always
            // prefer the non-generic version in doing overload selection.

            Type[]? types = Runtime.PythonArgsToTypeArray(idx);
            if (types == null)
            {
                return(Exceptions.RaiseTypeError("type(s) expected"));
            }

            MethodBase?mi = MethodBinder.MatchSignature(self.m.info, types);

            if (mi == null)
            {
                var e = "No match found for signature";
                return(Exceptions.RaiseTypeError(e));
            }

            var mb = new MethodBinding(self.m, self.target)
            {
                info = mi
            };

            return(mb.Alloc());
        }
        public static TraceAnnotationInfo Create(MethodBase?method)
        {
            if (method is null)
            {
                return(TraceAnnotationInfo.Default);
            }
            else
            {
                string defaultResourceName = method.DeclaringType is null ? method.Name : method.DeclaringType.Name + "." + method.Name;
                var    attributes          = method.GetCustomAttributes(true);
                foreach (var attr in attributes)
                {
                    if (attr.GetType() is Type attrType && attrType.FullName == TraceAttributeFullName)
                    {
                        try
                        {
                            string resourceName  = attrType.GetProperty("ResourceName")?.GetValue(attr) as string ?? defaultResourceName;
                            string operationName = attrType.GetProperty("OperationName")?.GetValue(attr) as string ?? TraceAnnotationInfo.DefaultOperationName;
                            return(new TraceAnnotationInfo(resourceName, operationName));
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex, "Unable to access properties on type {AssemblyQualifiedName}", attrType.AssemblyQualifiedName);
                        }
                    }
                }

                return(new TraceAnnotationInfo(resourceName: defaultResourceName, operationName: TraceAnnotationInfo.DefaultOperationName));
            }
        }
Ejemplo n.º 13
0
    /// <summary>
    /// Implementation of the abstract base function 'Validate'.
    /// </summary>
    /// <param name="propertyMetaInfo"></param>
    /// <param name="parameterObject"></param>     
    public override void Validate(PropertyMetaInfo propertyMetaInfo, ParameterBase parameterObject)
    {
      MethodBase? methodBase = MethodBase.GetCurrentMethod();
      //
      // Make sure the 'ValidationAttribute' is assigned to the right 
      // property type. (A string in this case)
      //
#pragma warning disable CS8604
      if (propertyMetaInfo.Type.ToLower().IndexOf("string") < 0)
      {
        propertyMetaInfo.ValidationError = new ValidationError(propertyMetaInfo, propertyMetaInfo.PropertyInfo.GetValue(parameterObject)?.ToString(), $"The attribute '{methodBase?.DeclaringType}' is not allowed on properties of type: '{propertyMetaInfo.Type}'.");
        return;
      }

      //
      // The actual validation.
      //
      if (propertyMetaInfo.PropertyInfo.GetValue(parameterObject)?.ToString()?.Length < this.MinLength)
      {
        propertyMetaInfo.ValidationError = new ValidationError(propertyMetaInfo, propertyMetaInfo.PropertyInfo.GetValue(parameterObject)?.ToString(), $"{ValidationErrorMessage}");
        return;
      }
#pragma warning restore CS8604

      //
      // The validation passed.
      //
      propertyMetaInfo.ValidationError = null;
    }
Ejemplo n.º 14
0
        public bool Equals(MethodBase?methodBase)
        {
            if (methodBase is null)
            {
                return(false);
            }
            if (methodBase.GetReturnType() != this.ReturnType)
            {
                return(false);
            }
            var methodParamTypes = methodBase.GetParameterTypes();

            if (methodParamTypes.Length != this.ParameterTypes.Length)
            {
                return(false);
            }
            for (var i = 0; i < this.ParameterTypes.Length; i++)
            {
                if (methodParamTypes[i] != this.ParameterTypes[i])
                {
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 15
0
        internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames)
        {
            int          iRetVal     = 0;
            const string PackageName = "System.Diagnostics";

            // Check if this method is part of the System.Diagnostics
            // package. If so, increment counter keeping track of
            // System.Diagnostics functions
            for (int i = 0; i < iNumFrames; i++)
            {
                MethodBase?mb = StackF.GetMethodBase(i);
                if (mb != null)
                {
                    Type?t = mb.DeclaringType;
                    if (t == null)
                    {
                        break;
                    }
                    string?ns = t.Namespace;
                    if (ns == null)
                    {
                        break;
                    }
                    if (!string.Equals(ns, PackageName, StringComparison.Ordinal))
                    {
                        break;
                    }
                }
                iRetVal++;
            }

            return(iRetVal);
        }
Ejemplo n.º 16
0
        private void RunScriptChecked(UpgradeScript script)
        {
            try
            {
                script.Method.Invoke();
            }
            catch (Exception e)
            {
                int line = 0;

                StackTrace stack = new StackTrace(e, true);
                for (int frameIndex = 0; frameIndex < stack.FrameCount; frameIndex++)
                {
                    StackFrame?frame  = stack.GetFrame(frameIndex);
                    MethodBase?method = frame?.GetMethod();
                    if (method == null)
                    {
                        continue;
                    }

                    VersionAttribute?attr = method.GetCustomAttribute <VersionAttribute>();
                    if (attr != null)
                    {
                        line = frame?.GetFileLineNumber() ?? 0;
                        break;
                    }
                }

                throw new InvalidOperationException($"Error in script version {script.Major}.{script.Minor}.{script.Patch}, line {line} -> {e.Message}", e);
            }
        }
Ejemplo n.º 17
0
    /// <summary>
    /// Retrieves background attributes that specify a fixture that has the specified constructor.
    /// </summary>
    /// <param name="constructor">The constructor of a fixture.</param>
    /// <returns>The background attributes that specify a fixture that has the specified constructor.</returns>
    protected virtual List <BackgroundAttribute> RetrieveBackgroundAttributes(MethodBase?constructor)
    {
        var backgroundList = new List <BackgroundAttribute>();

        if (constructor is null || constructor.DeclaringType == typeof(object))
        {
            return(backgroundList);
        }

        try
        {
            var ilBytes = constructor.GetMethodBody()?.GetILAsByteArray();
            if (ilBytes is not null)
            {
                backgroundList.AddRange(RetrieveBackgroundAttributes(
                                            ilBytes.Select((ilByte, index) => new { ILByte = ilByte, Index = index })
                                            .Where(x => x.ILByte == OpCodes.Call.Value)
                                            .Select(x => constructor.Module.ResolveMethod(BitConverter.ToInt32(ilBytes, x.Index + 1)))
                                            .FirstOrDefault(m => m?.IsConstructor ?? false)
                                            ));
            }
        }
        catch
        {
            // ignored
        }

        backgroundList.AddRange(constructor.GetCustomAttributes <BackgroundAttribute>().ToList());
        return(backgroundList);
    }
Ejemplo n.º 18
0
 private static void RequireNoRefArgs(MethodBase?method)
 {
     if (method?.GetParameters().Any(p => p.ParameterType.IsByRef) == true)
     {
         throw new NotSupportedException($"TryExpression is not supported as an argument to method '{method}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression.");
     }
 }
    public static void Run()
    {
        var        sfCallee     = new StackFrame(1, false);
        MethodBase?calleeMethod = sfCallee.GetMethod();
        Type?      calleeType   = calleeMethod?.DeclaringType;

        var        sfCaller     = new StackFrame(2, false);
        MethodBase?callerMethod = sfCaller.GetMethod();
        Type?      callerType   = callerMethod?.DeclaringType;

        Debug.Assert(calleeMethod?.IsAssembly ?? false, "Die Verwendung des Attributs \"InternalProtected\" ist nur auf Methoden, " +
                     "Eigenschaften und Konstruktoren sinnvoll, die den Zugriffsmodifizierer \"internal\" verwenden.");

        if (IsAssignableFrom(callerType, calleeType) || IsAssignableFrom(calleeType, callerType))
        {
            return;
        }

        const string unknown = "<unbekannt>";

        const string format = "Die Methode \"{0}.{1}\" wurde von der Methode \"{2}.{3}\" aufgerufen. " +
                              "Sie ist aber \"InternalProtected\" deklariert und darf nur von abgeleiteten Typen oder Basistypen aufgerufen werden.";
        string message = string.Format(CultureInfo.CurrentCulture, format,

                                       calleeMethod.DeclaringType?.Name ?? unknown,

                                       calleeMethod.Name,

                                       callerMethod?.DeclaringType?.Name ?? unknown,

                                       callerMethod?.Name ?? unknown);

        throw new InvalidOperationException(message);
    }
Ejemplo n.º 20
0
    private static bool IsTestMethod(MethodBase?method)
    {
        if (method == null)
        {
            return(false);
        }

        return(method.GetCustomAttribute <FactAttribute>() != null || method.GetCustomAttribute <TheoryAttribute>() != null);
    }
Ejemplo n.º 21
0
        /// <summary>
        /// Constructor of the 'ValueSetAttribute' class.
        /// </summary>
        /// <param name="valueSet">An array of objects which form the value set.</param>
        public ValueSetAttribute(Object[] valueSet) : base()
        {
            MethodBase?methodBase = MethodBase.GetCurrentMethod();

            if (valueSet.Length == 0)
            {
                throw new ArgumentException($"Argument '{nameof(valueSet)}' must not be empty in function '{methodBase?.ReflectedType?.Name}.ctor'.");
            }
            this.ValueSet = valueSet.ToList();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Constructor of the 'HelpAttribute' class.
        /// </summary>
        /// <param name="help"></param>
        /// <exception cref="System.ArgumentException"></exception>
        public HelpAttribute(string help)
        {
            MethodBase?methodBase = MethodBase.GetCurrentMethod();

            if (String.IsNullOrWhiteSpace(help))
            {
                throw new ArgumentException($"Argument '{nameof(help)}' must not be null or empty in function '{methodBase?.ReflectedType?.Name}.ctor'.", $"{nameof(help)}");
            }
            this.Help = help;
        }
Ejemplo n.º 23
0
        public static void PatchVirtual(
            this Harmony self,
            MethodBase?original,
            IMonitor monitor,
            LogLevel problemLogLevel = LogLevel.Error,
            LogLevel successLogLevel = LogLevel.Trace,
            HarmonyMethod?prefix     = null,
            HarmonyMethod?postfix    = null,
            HarmonyMethod?finalizer  = null
            )
        {
            if (original is null)
            {
                monitor.Log($"Could not patch method - the mod may not work correctly.\nReason: Unknown method to patch.", problemLogLevel);
                return;
            }

            Type?declaringType = original.DeclaringType;

            if (declaringType == null)
            {
                throw new ArgumentException($"{nameof(original)}.{nameof(original.DeclaringType)} is null.");
            }
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                IEnumerable <Type> subtypes = Enumerable.Empty <Type>();
                try
                {
                    subtypes = assembly.GetTypes().Where(t => t.IsAssignableTo(declaringType));
                }
                catch (Exception ex)
                {
                    monitor.Log($"There was a problem while getting types defined in assembly {assembly.GetName().Name}, ignoring it. Reason:\n{ex}", LogLevel.Trace);
                }

                foreach (Type subtype in subtypes)
                {
                    var originalParameters = original.GetParameters();
                    var subtypeOriginal    = AccessTools.Method(
                        subtype,
                        original.Name,
                        originalParameters.Select(p => p.ParameterType).ToArray()
                        );
                    if (subtypeOriginal is null)
                    {
                        continue;
                    }
                    if (!subtypeOriginal.IsDeclaredMember())
                    {
                        continue;
                    }
                    if (!subtypeOriginal.HasMethodBody())
                    {
                        continue;
                    }
Ejemplo n.º 24
0
    /// <summary>
    /// Constructor of the 'PropertyMetaInfo' class
    /// </summary>
    /// <param name="propertyInfo">The property info of the corresponding parameter property.</param>
    /// <exception cref="System.ArgumentException"></exception>
    public PropertyMetaInfo(PropertyInfo propertyInfo)
    {
      MethodBase? methodBase = MethodBase.GetCurrentMethod();

      if (propertyInfo == null)
      {
        throw new ArgumentException($"Argument '{nameof(propertyInfo)}' must not be null in function '{methodBase?.ReflectedType?.Name}.ctor'.", $"{propertyInfo}");
      }
      this.PropertyInfo = propertyInfo;
      this.ValidationError = null;
    }
Ejemplo n.º 25
0
 public RegexMethodDetails(
     MethodBase?methodWithTimeout,
     bool methodWithTimeoutNeedsRegexOptions,
     bool hasRegexOptionsAsLastParameter,
     string?reasonIfNotAllowed
     )
 {
     MethodWithTimeout = methodWithTimeout;
     MethodWithTimeoutNeedsRegexOptions = methodWithTimeoutNeedsRegexOptions;
     HasRegexOptionsAsLastParameter     = hasRegexOptionsAsLastParameter;
     ReasonIfNotAllowed = reasonIfNotAllowed;
 }
Ejemplo n.º 26
0
    private static void AppendParameters(StringBuilder builder, MethodBase?method, ExceptionSettings settings)
    {
        var typeColor  = settings.Style.ParameterType.ToMarkup();
        var nameColor  = settings.Style.ParameterName.ToMarkup();
        var parameters = method?.GetParameters()
                         .Select(x => $"[{typeColor}]{GetParameterName(x).EscapeMarkup()}[/] [{nameColor}]{x.Name?.EscapeMarkup()}[/]");

        if (parameters != null)
        {
            builder.Append(string.Join(", ", parameters));
        }
    }
Ejemplo n.º 27
0
        public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] argumentTypes, ParameterModifier[] modifiers)
#endif
        {
            if (match.Length == 0)
            {
                return(null);
            }
#if CSHARP8
            MethodBase?result = null;
#else
            MethodBase result = null;
#endif
            // SelectMethod on the default binder throws an exception if passed
            // typebuilders. this comes up when trying to bind to proxy methods
            // during analysis when (the proxy type is not yet complete). we
            // skip the default binder in this case and fall back on our own logic
            bool allRuntimeTypes = true;
            for (var i = 0; i < argumentTypes.Length; i++)
            {
                if (argumentTypes[i] is System.Reflection.Emit.TypeBuilder)
                {
                    allRuntimeTypes = false;
                    break;
                }
            }
            if (allRuntimeTypes)
            {
                result = _binder.SelectMethod(bindingAttr, match, argumentTypes, modifiers);
            }
            if (result != null)
            {
                return(result);
            }
            foreach (var candidate in match)
            {
                if (MatchByMagicBindingRules(bindingAttr, candidate, argumentTypes, modifiers))
                {
                    if (result != null)
                    {
                        throw new AmbiguousMatchException();
                    }
                    else
                    {
                        result = candidate;
                        continue;
                    }
                }
            }

            return(result);
        }
        protected static FileConfiguration GetConfig(MethodBase?method, string fileName, string configurationFile = ".editorconfig")
        {
            if (method == null)
            {
                throw new ArgumentException("The method must not be null", nameof(method));
            }

            var file        = GetFileFromMethod(method, fileName);
            var parser      = new EditorConfigParser(configurationFile);
            var fileConfigs = parser.Parse(file);

            fileConfigs.Should().NotBeNull();
            return(fileConfigs);
        }
Ejemplo n.º 29
0
    /// <summary>
    /// If a 'DisplayHelper' was provided during construction,
    /// a validation summary screen for this parameter object will be created.
    /// Otherwise an empty string will be returned.
    /// <para>
    /// The message provided in argument 'message' will be shown on top of the summary.
    /// </para>
    /// <para>
    /// The summary will be returned as a string with a line length matching with the 
    /// value of argument screenWidth.
    /// </para>
    /// </summary>
    /// <param name="message"></param>
    /// <param name="screenWidth"></param>
    /// <returns>The resulting string</returns>
    public virtual string CreateValidationSummary(string message, int screenWidth = 80)
    {
      MethodBase? methodBase = MethodBase.GetCurrentMethod();

      if (String.IsNullOrWhiteSpace(message))
      {
        throw new System.ArgumentException($"Argument '{nameof(message)}' must not be null or empty in function '{methodBase?.ReflectedType?.Name}.{methodBase?.Name}'.");
      }
      if (this.DisplayHelper != null)
      {
        return this.DisplayHelper.CreateValidationSummary(this, message, screenWidth);
      }
      return string.Empty;
    }
Ejemplo n.º 30
0
    private static MethodBase GetTestMethod()
    {
        var stackTrace = new StackTrace();

        MethodBase?testMethod = stackTrace.GetFrames().Select(stackFrame => stackFrame.GetMethod()).FirstOrDefault(IsTestMethod);

        if (testMethod == null)
        {
            // If called after the first await statement, the test method is no longer on the stack,
            // but has been replaced with the compiler-generated async/wait state machine.
            throw new InvalidOperationException("Fakers can only be used from within (the start of) a test method.");
        }

        return(testMethod);
    }