Exemplo n.º 1
0
    public InstallationForm(TargetAssembly targetAssembly, IPrerequisite[] missingPrerequisites)
    {
        _targetAssembly       = targetAssembly;
        _missingPrerequisites = missingPrerequisites;

        InitializeComponent();
    }
        public virtual void Public_api_arguments_should_not_have_redundant_not_null_annotation()
        {
            var parametersWithRedundantAttribute
                = (from type in GetAllTypes(TargetAssembly.GetTypes())
                   where type.GetTypeInfo().IsVisible&& !typeof(Delegate).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())
                   let interfaceMappings = type.GetInterfaces().Select(i => type.GetTypeInfo().GetRuntimeInterfaceMap(i))
                                           let events = type.GetEvents()
                                                        from method in type.GetMethods(AnyInstance | BindingFlags.Static | BindingFlags.DeclaredOnly)
                                                        .Concat <MethodBase>(type.GetConstructors())
                                                        where method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly
                                                        from parameter in method.GetParameters()
                                                        let parameterType = parameter.ParameterType.IsByRef ? parameter.ParameterType.GetElementType() : parameter.ParameterType
                                                                            let attributes = parameter.GetCustomAttributes(inherit: false)
                                                                                             where (!ShouldHaveNotNullAnnotation(method, type) ||
                                                                                                    !type.GetTypeInfo().IsInterface&& interfaceMappings.Any(im => im.TargetMethods.Contains(method)) ||
                                                                                                    events.Any(e => e.AddMethod == method || e.RemoveMethod == method) ||
                                                                                                    parameterType.GetTypeInfo().IsValueType&& !parameterType.GetTypeInfo().IsNullableType()) &&
                                                                                             attributes.Any(a => a.GetType().Name == nameof(NotNullAttribute) || a.GetType().Name == nameof(CanBeNullAttribute)) ||
                                                                                             parameterType.GetTypeInfo().IsValueType &&
                                                                                             parameterType.GetTypeInfo().IsNullableType() &&
                                                                                             attributes.Any(a => a.GetType().Name == nameof(CanBeNullAttribute))
                                                                                             select type.FullName + "." + method.Name + "[" + parameter.Name + "]").ToList();

            Assert.False(
                parametersWithRedundantAttribute.Count > 0,
                "\r\n-- Redundant NotNull annotations --\r\n" + string.Join(Environment.NewLine, parametersWithRedundantAttribute));
        }
Exemplo n.º 3
0
        public override bool Execute()
        {
            DateTime start = DateTime.Now;

            Log.LogMessage(MessageImportance.High, "Amending {0}", TargetAssembly.Select(a => a.ItemSpec).ToArray());
            try
            {
                Program.Amend(TargetAssembly.First().ItemSpec, AmendmentAssemblies.Select(a => a.ItemSpec).ToArray(), ReferenceAssemblies.Select(a => a.ItemSpec).ToArray());
            }
            catch (ReflectionTypeLoadException rtle)
            {
                Log.LogErrorFromException(rtle);
                foreach (var le in rtle.LoaderExceptions)
                {
                    Log.LogErrorFromException(le);
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
                throw;
            }
            Log.LogMessage(MessageImportance.High, "Amending Complete ({0:0.000} seconds)", DateTime.Now.Subtract(start).TotalSeconds);
            return(true);
        }
Exemplo n.º 4
0
        public void Public_api_arguments_should_have_not_null_annotation()
        {
            var parametersMissingAttribute
                = (from type in GetAllTypes(TargetAssembly.GetTypes())
                   where type.GetTypeInfo().IsVisible&& !typeof(Delegate).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())
                   let interfaceMappings = type.GetInterfaces().Select(i => type.GetTypeInfo().GetRuntimeInterfaceMap(i))
                                           let events = type.GetEvents()
                                                        from method in type.GetMethods(AnyInstance | BindingFlags.Static)
                                                        .Concat <MethodBase>(type.GetConstructors())
                                                        where (method.DeclaringType == type) &&
                                                        (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly) &&
                                                        (method is ConstructorInfo ||
                                                         (((MethodInfo)method).GetBaseDefinition().DeclaringType == method.DeclaringType))
                                                        //&& (method.Name != nameof(DbContext.OnConfiguring))
                                                        //&& (method.Name != nameof(DbContext.OnModelCreating))
                                                        where type.GetTypeInfo().IsInterface || !interfaceMappings.Any(im => im.TargetMethods.Contains(method))
                                                        where !events.Any(e => (e.AddMethod == method) || (e.RemoveMethod == method))
                                                        from parameter in method.GetParameters()
                                                        let parameterType = parameter.ParameterType.IsByRef
                       ? parameter.ParameterType.GetElementType()
                       : parameter.ParameterType
                                                                            where !parameterType.GetTypeInfo().IsValueType &&
                                                                            !parameter.GetCustomAttributes()
                                                                            .Any(
                       a => (a.GetType().Name == nameof(NotNullAttribute)) ||
                       (a.GetType().Name == nameof(CanBeNullAttribute)))
                                                                            select type.FullName + "." + method.Name + "[" + parameter.Name + "]")
                  .ToList();

            Assert.False(
                parametersMissingAttribute.Any(),
                "\r\n-- Missing NotNull annotations --\r\n" + string.Join(Environment.NewLine, parametersMissingAttribute));
        }
        public static void AchieveInitialize(AchievementManager __instance)
        {
            dynamic _this = __instance.AsDynamic();

            _this.achivs = Array.CreateInstance(AchievementBaseT, 30);
            dynamic achivs     = _this.achivs.RealObject;
            dynamic achivName  = R_AchivName();
            dynamic achivIndex = R_AchivIndex();

            for (int i = 0; i < achivName.Length; i++)
            {
                for (int j = 0; j < achivName[i].Length; j++)
                {
                    if (achivIndex[i] + j < achivs.Length)
                    {
                        achivs[achivIndex[i] + j] =
                            (dynamic)TargetAssembly.CreateInstance("THMHJ.Achievements." + achivClassNames[i][j]);
                    }
                }
            }
            dynamic specialData = _this.LoadSpecialData().RealObject;

            for (int k = 0; k < specialData.ach.Length; k++)
            {
                for (int l = 0; l < specialData.ach[k].achiv.Length; l++)
                {
                    achivs[achivIndex[k] + l].get = specialData.ach[k].achiv[l].get;
                    for (int m = 0; m < achivs[achivIndex[k] + l].finishedlevel.Length; m++)
                    {
                        achivs[achivIndex[k] + l].finishedlevel[m] = specialData.ach[k].achiv[l].level[m];
                    }
                }
            }
        }
Exemplo n.º 6
0
        public void Public_api_arguments_should_have_not_null_annotation()
        {
            var parametersMissingAttribute
                = (from type in GetAllTypes(TargetAssembly.GetTypes())
                   where type.IsVisible && !typeof(Delegate).IsAssignableFrom(type)
                   let interfaceMappings = type.GetInterfaces().Select(type.GetInterfaceMap)
                                           let events = type.GetEvents()
                                                        from method in type.GetMethods(PublicInstance | BindingFlags.Static)
                                                        .Concat <MethodBase>(type.GetConstructors())
                                                        where method.DeclaringType == type
                                                        where type.IsInterface || !interfaceMappings.Any(im => im.TargetMethods.Contains(method))
                                                        where !events.Any(e => e.AddMethod == method || e.RemoveMethod == method)
                                                        from parameter in method.GetParameters()
                                                        where !parameter.ParameterType.IsValueType &&
                                                        !parameter.GetCustomAttributes()
                                                        .Any(
                       a => a.GetType().Name == "NotNullAttribute" ||
                       a.GetType().Name == "CanBeNullAttribute")
                                                        select type.FullName + "." + method.Name + "[" + parameter.Name + "]")
                  .ToList();

            Assert.False(
                parametersMissingAttribute.Any(),
                "\r\n-- Missing NotNull annotations --\r\n" + string.Join("\r\n", parametersMissingAttribute));
        }
Exemplo n.º 7
0
    private bool PromptInstallation(
        TargetAssembly targetAssembly,
        IPrerequisite[] missingPrerequisites)
    {
        // Installation must be requested explicitly by setting the environment variable
        var isInstallationAccepted = string.Equals(
            Environment.GetEnvironmentVariable(PromptEnvironmentVariableName),
            "true",
            StringComparison.OrdinalIgnoreCase
            );

        if (!isInstallationAccepted)
        {
            using (ConsoleEx.WithForegroundColor(ConsoleColor.DarkRed))
            {
                Console.Error.WriteLine($"Your system is missing runtime components required by {targetAssembly.Title}:");
                foreach (var prerequisite in missingPrerequisites)
                {
                    Console.Error.WriteLine($"  - {prerequisite.DisplayName}");
                }
                Console.Error.WriteLine();
            }

            using (ConsoleEx.WithForegroundColor(ConsoleColor.Gray))
            {
                Console.Error.Write("To install the missing components automatically, set the environment variable ");

                using (ConsoleEx.WithForegroundColor(ConsoleColor.DarkCyan))
                    Console.Error.Write(PromptEnvironmentVariableName);

                Console.Error.Write(" to ");

                using (ConsoleEx.WithForegroundColor(ConsoleColor.DarkCyan))
                    Console.Error.Write("true");

                Console.Error.Write(", and then run the application again:");
                Console.Error.WriteLine();
            }

            using (ConsoleEx.WithForegroundColor(ConsoleColor.White))
            {
                Console.Error.Write($"  set {PromptEnvironmentVariableName}=true");
                using (ConsoleEx.WithForegroundColor(ConsoleColor.DarkGray))
                    Console.Error.Write("      (Command Prompt)");

                Console.Error.WriteLine();

                Console.Error.Write($"  $env:{PromptEnvironmentVariableName}=\"true\"");
                using (ConsoleEx.WithForegroundColor(ConsoleColor.DarkGray))
                    Console.Error.Write("   (Powershell)");

                Console.Error.WriteLine();
            }

            return(false);
        }

        return(true);
    }
Exemplo n.º 8
0
 private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
 {
     if (e.NewValue is InspectorTreeItem treeItem && treeItem.ShowMethods)
     {
         ViewModel.Methods.Clear();
         var type = TargetAssembly.GetType(treeItem.FullName);
         type.GetMethods().ToList().ForEach(AddItemToViewModel);
     }
Exemplo n.º 9
0
        public override bool Execute()
        {
            DateTime start = DateTime.Now;

            Log.LogMessage(MessageImportance.High, "Amending {0}", TargetAssembly.Select(a => a.ItemSpec).ToArray());
            Program.Amend(TargetAssembly.First().ItemSpec, AmendmentAssemblies.Select(a => a.ItemSpec).ToArray(), ReferenceAssemblies.Select(a => a.ItemSpec).ToArray());
            Log.LogMessage(MessageImportance.High, "Amending Complete ({0:0.000} seconds)", DateTime.Now.Subtract(start).TotalSeconds);
            return(true);
        }
Exemplo n.º 10
0
 public void WriteTo(string path)
 {
     Log.Information("Writing assembly {@OrigName:l} [{@OrigPath:l}] to location {@DestPath:l}",
                     TargetAssembly.Name.Name,
                     PathHelper.GetUserFriendlyPath(TargetAssembly.MainModule.FullyQualifiedName),
                     PathHelper.GetUserFriendlyPath(path));
     TargetAssembly.Write(path);
     Log.Information("Write completed successfuly.");
 }
Exemplo n.º 11
0
        public void TestSetup()
        {
            Console.Write(Assembly.GetExecutingAssembly().Location);
            string currentPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var    assembly    = Assembly.LoadFrom(currentPath + @"\Test.DataAccess.dll");

            Assert.IsNotNull(assembly);
            this.tartgetAssembly = new TargetAssembly(assembly);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Writes the assembly info.
        /// </summary>
        /// <param name="xw">The xw.</param>
        /// <param name="forReadability">if set to <c>true</c> [for readability].</param>
        protected virtual void WriteAssemblyInfo(XmlWriter xw, bool forReadability)
        {
            if (TargetAssembly != null)
            {
                xw.WriteStartElement("Assembly");
                TargetAssembly.WriteAttributes(xw);

                xw.WriteEndElement();
            }
        }
Exemplo n.º 13
0
    public AssemblyOptions(string targetAssemblyName, string?defaultNamespace = null, string?rootFolder = null)
    {
        TargetAssembly   = AssemblyOptions.LoadAssembly(targetAssemblyName);
        DefaultNamespace = defaultNamespace;
        RootFolder       = rootFolder;

        if (TargetAssembly is not null && string.IsNullOrWhiteSpace(DefaultNamespace))
        {
            DefaultNamespace = TargetAssembly.GetName().Name;
        }
    }
Exemplo n.º 14
0
        public bool GenerateForAllUsedIncomplete()
        {
            var allAssemblyTypes = new Dictionary<string, Type>();

            foreach (Type t in TargetAssembly.GetTypes().Where(t => t.IsPublic))
            {
                if (!allAssemblyTypes.ContainsKey(t.Name))
                    allAssemblyTypes.Add(t.Name, t);
            }

            bool added = false;

            foreach (Type type in UsedTypes.ToArray())
            {
                if (!TypeIsWrapped(type))
                    throw new InvalidOperationException();

                if (!CompleteTypes.ContainsKey(type))
                {
                    var wci = new WrapperClassInfo(type, this);
                    CompleteTypes.Add(type, wci);

                    foreach (
                        Type inheritedType in
                            allAssemblyTypes.Values.Where(t => t.IsSubclassOf(wci.WrappedType) && t.IsPublic)
                                .Where(TypeIsWrapped))
                    {
                        if (inheritedType.GetCustomAttributes(typeof(ObsoleteAttribute), true).Count() == 0
                            && !UsedTypes.Contains(inheritedType))
                            UsedTypes.Add(inheritedType);
                    }

                    var sb = new StringBuilder();

                    if (wci.IsInterface)
                        wci.GenerateInterfaceCode(sb);
                    else
                        wci.GenerateClassCode(sb);

                    if (wci.FilePathBase.IndexOfAny(new[] { '\\', '/' }) != -1)
                        Directory.CreateDirectory(Path.GetDirectoryName(wci.FilePathBase));

                    WriteTextToFile(wci.FilePathBase + ".cs", sb.ToString(), true);

                    wci.GenerateUserClassFile();

                    added = true;
                }
            }

            return added;
        }
Exemplo n.º 15
0
        public Type GetListTypeFor(WrapperPropInfo wpi)
        {
            if (wpi.PropertyType.IsArray)
            {
                return(wpi.PropertyType.DeclaringType);
            }
            string fullPropName = wpi.FullNameDest;

            Type listType;

            string listTypeName;

            listType = LoadListTypeForProperty(fullPropName);

            if (listType != null)
            {
                return(listType);
            }

            // Try to find type from get*BySomething))
            if (fullPropName.EndsWith("s"))
            {
                string singularName = wpi.Name.Substring(0, wpi.Name.Length - 1);

                string singularGetNameStart = "get" + singularName + "By";

                Type guessedReturnType = wpi.ClassInfo.WrappedType
                                         .GetMethods(BindingFlags.Instance | BindingFlags.Public)
                                         .Where(mi => mi.ReturnType != typeof(void))
                                         .Where(mi => mi.Name.StartsWith(singularGetNameStart))
                                         .Where(mi => mi.Name.Length > singularGetNameStart.Length)
                                         .Select(mi => mi.ReturnType)
                                         .FirstOrDefault();

                if (guessedReturnType == null)
                {
                    // Try to find type from name
                    guessedReturnType = TargetAssembly.GetTypes()
                                        .Where(t => t.Name == "Html" + singularName || t.Name == singularName).FirstOrDefault();
                }

                if (guessedReturnType != null)
                {
                    Console.WriteLine("Guessed list type " + guessedReturnType.FullName + " for " + fullPropName);
                    return(guessedReturnType);
                }
            }

            listType = GetListTypeFor(fullPropName);

            return(listType);
        }
Exemplo n.º 16
0
    protected override bool InstallPrerequisites(
        TargetAssembly targetAssembly,
        IPrerequisite[] missingPrerequisites)
    {
        // Prompt the user
        if (!PromptInstallation(targetAssembly, missingPrerequisites))
        {
            return(false);
        }

        // Perform the installation
        return(PerformInstallation(targetAssembly, missingPrerequisites));
    }
Exemplo n.º 17
0
        public virtual void All_test_bases_must_be_implemented()
        {
            var concreteTests = TargetAssembly.GetTypes().Where(c => c.BaseType != typeof(object) && !c.IsAbstract).ToList();
            var nonImplementedBases
                = (from baseType in GetBaseTestClasses()
                   where !IgnoredTestBases.Contains(baseType) &&
                   !concreteTests.Any(c => Implements(c, baseType))
                   select baseType.FullName)
                  .ToList();

            Assert.False(
                nonImplementedBases.Count > 0,
                "\r\n-- Missing derived classes for --\r\n" + string.Join(Environment.NewLine, nonImplementedBases));
        }
        public virtual void Async_methods_should_have_overload_with_cancellation_token_and_end_with_async_suffix()
        {
            var asyncMethods
                = (from type in GetAllTypes(TargetAssembly.GetTypes())
                   where type.GetTypeInfo().IsVisible
                   from method in type.GetMethods(AnyInstance | BindingFlags.Static)
                   where method.DeclaringType == type &&
                   (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly)
                   where typeof(Task).GetTypeInfo().IsAssignableFrom(method.ReturnType.GetTypeInfo())
                   select method).ToList();

            var asyncMethodsWithToken
                = (from method in asyncMethods
                   where method.GetParameters().Any(pi => pi.ParameterType == typeof(CancellationToken))
                   select method).ToList();

            var asyncMethodsWithoutToken
                = (from method in asyncMethods
                   where method.GetParameters().All(pi => pi.ParameterType != typeof(CancellationToken))
                   select method).ToList();

            var missingOverloads
                = (from methodWithoutToken in asyncMethodsWithoutToken
                   where !asyncMethodsWithToken
                   .Any(
                       methodWithToken => methodWithoutToken.Name == methodWithToken.Name &&
                       methodWithoutToken.DeclaringType == methodWithToken.DeclaringType)
                   // ReSharper disable once PossibleNullReferenceException
                   select methodWithoutToken.DeclaringType.Name + "." + methodWithoutToken.Name)
                  .Except(GetCancellationTokenExceptions())
                  .ToList();

            Assert.False(
                missingOverloads.Count > 0,
                "\r\n-- Missing async overloads --\r\n" + string.Join(Environment.NewLine, missingOverloads));

            var missingSuffixMethods
                = asyncMethods
                  .Where(method => !method.Name.EndsWith("Async") && method.DeclaringType != null)
                  .Select(method => method.DeclaringType.Name + "." + method.Name)
                  .Except(GetAsyncSuffixExceptions())
                  .ToList();

            Assert.False(
                missingSuffixMethods.Count > 0,
                "\r\n-- Missing async suffix --\r\n" + string.Join(Environment.NewLine, missingSuffixMethods));
        }
    public int Run(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += (_, e) => ReportError(e.ExceptionObject.ToString());

        try
        {
            var targetAssembly = TargetAssembly.Resolve();

            try
            {
                // Hot path: attempt to run the target first without any checks
                return(targetAssembly.Run(args));
            }
            // Possible exception causes:
            // - .NET host not found (DirectoryNotFoundException)
            // - .NET host failed to initialize (ApplicationException)
            catch
            {
                // Check for and install missing prerequisites
                var missingPrerequisites = targetAssembly.GetMissingPrerequisites();
                if (missingPrerequisites.Any())
                {
                    var isInstallationSuccessful = InstallPrerequisites(targetAssembly, missingPrerequisites);

                    // User canceled installation or reboot is required
                    if (!isInstallationSuccessful)
                    {
                        return(0xB007);
                    }

                    // Reset environment to update PATH and other variables
                    // that may have been changed by the installation process.
                    EnvironmentEx.RefreshEnvironmentVariables();
                }

                // Attempt to run the target again, this time without ignoring exceptions
                return(targetAssembly.Run(args));
            }
        }
        catch (Exception ex)
        {
            ReportError(ex.ToString());
            return(0xDEAD);
        }
    }
Exemplo n.º 20
0
        public void Async_methods_should_have_overload_with_cancellation_token_and_end_with_async_suffix()
        {
            var asyncMethods
                = (from type in GetAllTypes(TargetAssembly.GetTypes())
                   where type.IsVisible
                   from method in type.GetMethods(PublicInstance /* | BindingFlags.Static*/)
                   where GetBasestTypeInAssembly(method.DeclaringType) == type
                   where typeof(Task).IsAssignableFrom(method.ReturnType)
                   select method).ToList();

            var asyncMethodsWithToken
                = (from method in asyncMethods
                   where method.GetParameters().Any(pi => pi.ParameterType == typeof(CancellationToken))
                   select method).ToList();

            var asyncMethodsWithoutToken
                = (from method in asyncMethods
                   where method.GetParameters().All(pi => pi.ParameterType != typeof(CancellationToken))
                   select method).ToList();

            var missingOverloads
                = (from methodWithoutToken in asyncMethodsWithoutToken
                   where !asyncMethodsWithToken
                   .Any(methodWithToken => methodWithoutToken.Name == methodWithToken.Name &&
                        methodWithoutToken.ReflectedType == methodWithToken.ReflectedType)
                   // ReSharper disable once PossibleNullReferenceException
                   select methodWithoutToken.DeclaringType.Name + "." + methodWithoutToken.Name)
                  .Except(GetCancellationTokenExceptions())
                  .ToList();

            Assert.False(
                missingOverloads.Any(),
                "\r\n-- Missing async overloads --\r\n" + string.Join("\r\n", missingOverloads));

            var missingSuffixMethods
                = asyncMethods
                  .Where(method => !method.Name.EndsWith("Async"))
                  .Select(method => method.DeclaringType.Name + "." + method.Name)
                  .Except(GetAsyncSuffixExceptions())
                  .ToList();

            Assert.False(
                missingSuffixMethods.Any(),
                "\r\n-- Missing async suffix --\r\n" + string.Join("\r\n", missingSuffixMethods));
        }
Exemplo n.º 21
0
        public IEnumerable <Type> GetDetectableTypes()
        {
            var list = TargetAssembly.GetTypes().Where(t => t.BaseType == BaseDetectableType)
                       .Select(t =>
            {
                var attrib = t.GetCustomAttribute(typeof(DetectAttribute), false) as DetectAttribute;
                var order  = (attrib == null) ? 100 : attrib.Priority;
                return(new
                {
                    Order = order,
                    Type = t
                });
            })
                       .OrderBy(t => t.Order)
                       .Select(t => t.Type);

            return(list);
        }
Exemplo n.º 22
0
        public void Public_inheritable_apis_should_be_virtual()
        {
            var nonVirtualMethods
                = (from type in GetAllTypes(TargetAssembly.GetTypes())
                   where type.IsVisible &&
                   !type.IsSealed &&
                   type.GetConstructors(AnyInstance).Any(c => c.IsPublic || c.IsFamily || c.IsFamilyOrAssembly) &&
                   type.Namespace != null &&
                   !type.Namespace.EndsWith(".Compiled")
                   from method in type.GetMethods(PublicInstance)
                   where method.DeclaringType == type &&
                   !(method.IsVirtual && !method.IsFinal)
                   select type.FullName + "." + method.Name)
                  .ToList();

            Assert.False(
                nonVirtualMethods.Any(),
                "\r\n-- Missing virtual APIs --\r\n" + string.Join("\r\n", nonVirtualMethods));
        }
Exemplo n.º 23
0
        public void Public_inheritable_apis_should_be_virtual()
        {
            var nonVirtualMethods
                = (from t in GetAllTypes(TargetAssembly.GetTypes())
                   where t.IsVisible &&
                   !t.IsSealed &&
                   t.GetConstructors(PublicInstance).Any() &&
                   t.Namespace != null &&
                   !t.Namespace.EndsWith(".Compiled")
                   from m in t.GetMethods(PublicInstance)
                   where m.DeclaringType != null &&
                   m.DeclaringType.Assembly == TargetAssembly &&
                   !(m.IsVirtual && !m.IsFinal)
                   select t.Name + "." + m.Name)
                  .ToList();

            Assert.False(
                nonVirtualMethods.Any(),
                "\r\n-- Missing virtual APIs --\r\n" + string.Join("\r\n", nonVirtualMethods));
        }
Exemplo n.º 24
0
        public void Async_methods_should_end_with_async_suffix()
        {
            var asyncMethods
                = (from type in GetAllTypes(TargetAssembly.GetTypes())
                   where type.IsVisible
                   from method in type.GetMethods(PublicInstance /* | BindingFlags.Static*/)
                   where GetBasestTypeInAssembly(method.DeclaringType) == type
                   where typeof(Task).IsAssignableFrom(method.ReturnType)
                   select method).ToList();

            var missingSuffixMethods
                = asyncMethods
                  .Where(method => !method.Name.EndsWith("Async"))
                  .Select(method => method.DeclaringType.Name + "." + method.Name)
                  .Except(GetAsyncSuffixExceptions())
                  .ToList();

            Assert.False(
                missingSuffixMethods.Any(),
                "\r\n-- Missing async suffix --\r\n" + string.Join("\r\n", missingSuffixMethods));
        }
Exemplo n.º 25
0
        public void Async_methods_should_have_overload_with_cancellation_token_and_end_with_async_suffix()
        {
            var asyncMethodsWithToken
                = (from t in GetAllTypes(TargetAssembly.GetTypes())
                   where t.IsVisible
                   from m in t.GetMethods(PublicInstance)
                   where typeof(Task).IsAssignableFrom(m.ReturnType) &&
                   m.GetParameters().Any(pi => pi.ParameterType == typeof(CancellationToken))
                   select m).ToList();

            var asyncMethodsWithoutToken
                = (from t in GetAllTypes(TargetAssembly.GetTypes())
                   where t.IsVisible
                   from m in t.GetMethods(PublicInstance)
                   where typeof(Task).IsAssignableFrom(m.ReturnType) &&
                   m.GetParameters().All(pi => pi.ParameterType != typeof(CancellationToken))
                   select m).ToList();

            var missingOverloads
                = (from m1 in asyncMethodsWithoutToken
                   where !asyncMethodsWithToken
                   .Any(m2 => m1.Name == m2.Name &&
                        m1.ReflectedType == m2.ReflectedType)
                   // ReSharper disable once PossibleNullReferenceException
                   select m1.DeclaringType.Name + "." + m1.Name).ToList();

            Assert.False(
                missingOverloads.Any(),
                "\r\n-- Missing async overloads --\r\n" + string.Join("\r\n", missingOverloads));

            var missingSuffixMethods
                = asyncMethodsWithToken
                  .Where(mi => !mi.Name.EndsWith("Async"))
                  .Select(mi => mi.DeclaringType.Name + "." + mi.Name)
                  .ToList();

            Assert.False(
                missingSuffixMethods.Any(),
                "\r\n-- Missing async suffix --\r\n" + string.Join("\r\n", missingSuffixMethods));
        }
        public virtual void Public_inheritable_apis_should_be_virtual()
        {
            var nonVirtualMethods
                = (from type in GetAllTypes(TargetAssembly.GetTypes())
                   where type.GetTypeInfo().IsVisible &&
                   !type.GetTypeInfo().IsSealed &&
                   type.GetConstructors(AnyInstance).Any(c => c.IsPublic || c.IsFamily || c.IsFamilyOrAssembly) &&
                   type.Namespace?.EndsWith(".Compiled") == false &&
                   ShouldHaveVirtualMethods(type)
                   from method in type.GetMethods(AnyInstance)
                   where method.DeclaringType == type &&
                   !(method.IsVirtual && !method.IsFinal) &&
                   !method.Name.StartsWith("add_") &&
                   !method.Name.StartsWith("remove_") &&
                   (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly) &&
                   method.Name != "GenerateCacheKeyCore"
                   select type.FullName + "." + method.Name)
                  .ToList();

            Assert.False(
                nonVirtualMethods.Count > 0,
                "\r\n-- Missing virtual APIs --\r\n" + string.Join(Environment.NewLine, nonVirtualMethods));
        }
    protected override bool InstallPrerequisites(
        TargetAssembly targetAssembly,
        IPrerequisite[] missingPrerequisites)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // Prompt the user
        using (var promptForm = new InstallationPromptForm(targetAssembly, missingPrerequisites))
        {
            Application.Run(promptForm);
            if (!promptForm.Result)
            {
                return(false);
            }
        }

        // Perform the installation
        using (var installationForm = new InstallationForm(targetAssembly, missingPrerequisites))
        {
            Application.Run(installationForm);
            return(installationForm.Result);
        }
    }
        public void Public_api_arguments_should_have_not_null_annotation()
        {
            var parametersMissingAttribute
                = (from t in GetAllTypes(TargetAssembly.GetTypes())
                   where t.IsVisible
                   let ims = t.GetInterfaces().Select(t.GetInterfaceMap)
                             from m in t.GetMethods(PublicInstance | BindingFlags.Static)
                             .Concat <MethodBase>(t.GetConstructors())
                             where m.DeclaringType != null &&
                             m.DeclaringType.Assembly == TargetAssembly
                             where t.IsInterface || !ims.Any(im => im.TargetMethods.Contains(m))
                             from p in m.GetParameters()
                             where !p.ParameterType.IsValueType &&
                             !p.GetCustomAttributes()
                             .Any(
                       a => a.GetType().Name == "NotNullAttribute" ||
                       a.GetType().Name == "CanBeNullAttribute")
                             select t.Name + "." + m.Name + "[" + p.Name + "]")
                  .ToList();

            Assert.False(
                parametersMissingAttribute.Any(),
                "\r\n-- Missing NotNull annotations --\r\n" + string.Join("\r\n", parametersMissingAttribute));
        }
        public virtual void Public_api_bool_parameters_should_not_be_prefixed()
        {
            var prefixes = new[]
            {
                "is",
                "can",
                "has"
            };

            var parameters = (
                from type in GetAllTypes(TargetAssembly.GetExportedTypes())
                where !type.Namespace.Contains("Internal")
                from method in type.GetTypeInfo().DeclaredMethods
                where !method.IsPrivate
                from parameter in method.GetParameters()
                where parameter.ParameterType.UnwrapNullableType() == typeof(bool) &&
                prefixes.Any(parameter.Name.StartsWith)
                select $"{type.FullName}.{method.Name}[{parameter.Name}]")
                             .ToList();

            Assert.False(
                parameters.Count > 0,
                "\r\n-- Prefixed bool parameteres --\r\n" + string.Join(Environment.NewLine, parameters));
        }
Exemplo n.º 30
0
    private bool PerformInstallation(
        TargetAssembly targetAssembly,
        IPrerequisite[] missingPrerequisites)
    {
        using (ConsoleEx.WithForegroundColor(ConsoleColor.White))
            Console.Out.WriteLine($"{targetAssembly.Title}: installing prerequisites");

        var currentStep = 1;
        var totalSteps  = missingPrerequisites.Length * 2;

        // Download
        var installers = new List <IPrerequisiteInstaller>();

        foreach (var prerequisite in missingPrerequisites)
        {
            Console.Out.Write($"[{currentStep}/{totalSteps}] ");
            Console.Out.Write($"Downloading {prerequisite.DisplayName}... ");

            using (var progress = new ConsoleProgress(Console.Error))
            {
                var installer = prerequisite.DownloadInstaller(progress.Report);
                installers.Add(installer);
            }

            Console.Out.Write("Done");
            Console.Out.WriteLine();

            currentStep++;
        }

        // Install
        var isRebootRequired = false;

        foreach (var installer in installers)
        {
            Console.Out.Write($"[{currentStep}/{totalSteps}] ");
            Console.Out.Write($"Installing {installer.Prerequisite.DisplayName}... ");

            var installationResult = installer.Run();

            Console.Out.Write("Done");
            Console.Out.WriteLine();

            FileEx.TryDelete(installer.FilePath);

            if (installationResult == PrerequisiteInstallerResult.RebootRequired)
            {
                isRebootRequired = true;
            }

            currentStep++;
        }

        using (ConsoleEx.WithForegroundColor(ConsoleColor.White))
            Console.Out.WriteLine("Prerequisites installed successfully.");
        Console.Out.WriteLine();

        // Finalize
        if (isRebootRequired)
        {
            using (ConsoleEx.WithForegroundColor(ConsoleColor.DarkYellow))
            {
                Console.Out.WriteLine($"You need to restart Windows before you can run {targetAssembly.Title}.");
                Console.Out.WriteLine("Would you like to do it now? [y/n]");
            }

            var isRebootAccepted = Console.ReadKey(true).Key == ConsoleKey.Y;
            if (isRebootAccepted)
            {
                OperatingSystem.Reboot();
            }

            return(false);
        }

        return(true);
    }