Example #1
0
            protected override TemplateConstraintResult EvaluateInternal(string?args)
            {
                IReadOnlyList <HostInformation> supportedHosts = ParseArgs(args).ToList();

                //check primary host name first
                bool primaryHostNameMatch = false;

                foreach (HostInformation hostInfo in supportedHosts.Where(h => h.HostName.Equals(EnvironmentSettings.Host.HostIdentifier, StringComparison.OrdinalIgnoreCase)))
                {
                    primaryHostNameMatch = true;
                    if (hostInfo.Version == null || hostInfo.Version.CheckIfVersionIsValid(EnvironmentSettings.Host.Version))
                    {
                        return(TemplateConstraintResult.CreateAllowed(this));
                    }
                }
                if (!primaryHostNameMatch)
                {
                    //if there is no primary host name, check fallback host names
                    foreach (HostInformation hostInfo in supportedHosts.Where(h => EnvironmentSettings.Host.FallbackHostTemplateConfigNames.Contains(h.HostName, StringComparer.OrdinalIgnoreCase)))
                    {
                        if (hostInfo.Version == null || hostInfo.Version.CheckIfVersionIsValid(EnvironmentSettings.Host.Version))
                        {
                            return(TemplateConstraintResult.CreateAllowed(this));
                        }
                    }
                }
                string errorMessage = string.Format(LocalizableStrings.HostConstraint_Message_Restricted, EnvironmentSettings.Host.HostIdentifier, EnvironmentSettings.Host.Version, supportedHosts.ToCsvString());

                return(TemplateConstraintResult.CreateRestricted(this, errorMessage));
            }
Example #2
0
 public TemplateConstraintResult Evaluate(string?args)
 {
     try
     {
         return(EvaluateInternal(args));
     }
     catch (ConfigurationException ce)
     {
         return(TemplateConstraintResult.CreateEvaluationFailure(this, ce.Message, LocalizableStrings.Generic_Constraint_WrongConfigurationCTA));
     }
 }
Example #3
0
 public TemplateConstraintResult Evaluate(string?args)
 {
     if (args == "yes")
     {
         return(TemplateConstraintResult.CreateAllowed(this));
     }
     else if (args == "no")
     {
         return(TemplateConstraintResult.CreateRestricted(this, "cannot run", "do smth"));
     }
     return(TemplateConstraintResult.CreateEvaluationFailure(this, "bad params"));
 }
Example #4
0
            protected override TemplateConstraintResult EvaluateInternal(string?args)
            {
                IEnumerable <OSPlatform> supportedOS = ParseArgs(args);

                foreach (OSPlatform platform in supportedOS)
                {
                    if (RuntimeInformation.IsOSPlatform(platform))
                    {
                        return(TemplateConstraintResult.CreateAllowed(this));
                    }
                }
                return(TemplateConstraintResult.CreateRestricted(this, string.Format(LocalizableStrings.OSConstraint_Message_Restricted, RuntimeInformation.OSDescription, string.Join(", ", supportedOS))));
            }
Example #5
0
        public async Task <TemplateConstraintResult> EvaluateConstraintAsync(string type, string?args, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (!_templateConstrains.TryGetValue(type, out Task <ITemplateConstraint> task))
            {
                _logger.LogDebug($"The constraint '{type}' is unknown.");
                return(TemplateConstraintResult.CreateInitializationFailure(type, string.Format(LocalizableStrings.TemplateConstraintManager_Error_UnknownType, type)));
            }

            if (!task.IsCompleted)
            {
                try
                {
                    _logger.LogDebug($"The constraint '{type}' is not initialized, waiting for initialization.");
                    await CancellableWhenAll(new[] { task }, cancellationToken).ConfigureAwait(false);

                    _logger.LogDebug($"The constraint '{type}' is initialized successfully.");
                }
                catch (TaskCanceledException)
                {
                    throw;
                }
                catch (Exception)
                {
                    //handled below
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (task.IsFaulted || task.IsCanceled)
            {
                var exception = task.Exception is AggregateException ? task.Exception.InnerException ?? task.Exception : task.Exception;
                _logger.LogDebug($"The constraint '{type}' failed to be initialized, details: {exception}.");
                return(TemplateConstraintResult.CreateInitializationFailure(type, string.Format(LocalizableStrings.TemplateConstraintManager_Error_FailedToInitialize, type, exception.Message)));
            }

            try
            {
                return(task.Result.Evaluate(args));
            }
            catch (Exception e)
            {
                _logger.LogDebug($"The constraint '{type}' failed to be evaluated for the args '{args}', details: {e}.");
                return(TemplateConstraintResult.CreateEvaluationFailure(task.Result, string.Format(LocalizableStrings.TemplateConstraintManager_Error_FailedToEvaluate, type, args, e.Message)));
            }
        }
Example #6
0
        /// <summary>
        /// Gets display string for constraint evaluation result.
        /// </summary>
        internal static string ToDisplayString(this TemplateConstraintResult constraintResult)
        {
            StringBuilder stringBuilder = new StringBuilder();

            string?constraintDisplayName = constraintResult.Constraint?.DisplayName;

            if (string.IsNullOrWhiteSpace(constraintDisplayName))
            {
                constraintDisplayName = constraintResult.ConstraintType;
            }

            stringBuilder.Append($"{constraintDisplayName}: {constraintResult.LocalizedErrorMessage}");
            if (!string.IsNullOrWhiteSpace(constraintResult.CallToAction))
            {
                stringBuilder.Append($" {constraintResult.CallToAction}");
            }
            return(stringBuilder.ToString());
        }
Example #7
0
            protected override TemplateConstraintResult EvaluateInternal(string?args)
            {
                IReadOnlyList <string> supportedWorkloads = ParseArgs(args).ToList();

                bool isSupportedWorkload = supportedWorkloads.Any(_installedWorkloads.Contains);

                if (isSupportedWorkload)
                {
                    return(TemplateConstraintResult.CreateAllowed(this));
                }

                return(TemplateConstraintResult.CreateRestricted(
                           this,
                           string.Format(
                               LocalizableStrings.WorkloadConstraint_Message_Restricted,
                               string.Join(", ", supportedWorkloads),
                               string.Join(", ", _installedWorkloadsString)),
                           _remedySuggestionFactory(supportedWorkloads)
                           ));
            }
            protected override TemplateConstraintResult EvaluateInternal(string?args)
            {
                IReadOnlyList <IVersionSpecification> supportedSdks = ParseArgs(args).ToList();

                foreach (IVersionSpecification supportedSdk in supportedSdks)
                {
                    if (supportedSdk.CheckIfVersionIsValid(_currentSdkVersion.ToString()))
                    {
                        return(TemplateConstraintResult.CreateAllowed(this));
                    }
                }

                string cta = _remedySuggestionFactory(
                    VersionSpecificationsToStrings(supportedSdks),
                    VersionSpecificationsToStrings(_installedSdkVersion.Where(installed =>
                                                                              supportedSdks.Any(supported => supported.CheckIfVersionIsValid(installed.ToString())))));

                return(TemplateConstraintResult.CreateRestricted(
                           this,
                           string.Format(LocalizableStrings.SdkConstraint_Message_Restricted, _currentSdkVersion.ToString(), supportedSdks.ToCsvString()),
                           cta));
            }
Example #9
0
        public async Task <IReadOnlyList <(ITemplateInfo Template, IReadOnlyList <TemplateConstraintResult> Result)> > EvaluateConstraintsAsync(IEnumerable <ITemplateInfo> templates, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var requiredConstraints = templates.SelectMany(t => t.Constraints).Select(c => c.Type).Distinct();
            var tasksToWait         = new List <Task>();

            foreach (var constraintType in requiredConstraints)
            {
                if (!_templateConstrains.TryGetValue(constraintType, out Task <ITemplateConstraint> task))
                {
                    //handled below
                    continue;
                }
                tasksToWait.Add(task);
            }

            if (tasksToWait.Any(t => !t.IsCompleted))
            {
                try
                {
                    var notCompletedTasks = tasksToWait.Where(t => !t.IsCompleted);
                    _logger.LogDebug($"The constraint(s) are not initialized, waiting for initialization.");
                    await CancellableWhenAll(notCompletedTasks, cancellationToken).ConfigureAwait(false);

                    _logger.LogDebug($"The constraint(s) are initialized successfully.");
                }
                catch (TaskCanceledException)
                {
                    throw;
                }
                catch (Exception)
                {
                    //handled below
                }
            }
            cancellationToken.ThrowIfCancellationRequested();

            List <(ITemplateInfo, IReadOnlyList <TemplateConstraintResult>)> evaluationResult = new();

            foreach (ITemplateInfo template in templates)
            {
                List <TemplateConstraintResult> constraintResults = new();
                foreach (var constraint in template.Constraints)
                {
                    if (!_templateConstrains.TryGetValue(constraint.Type, out Task <ITemplateConstraint> task))
                    {
                        _logger.LogDebug($"The constraint '{constraint.Type}' is unknown.");
                        constraintResults.Add(TemplateConstraintResult.CreateInitializationFailure(constraint.Type, string.Format(LocalizableStrings.TemplateConstraintManager_Error_UnknownType, constraint.Type)));
                        continue;
                    }

                    if (task.IsFaulted || task.IsCanceled)
                    {
                        var exception = task.Exception is AggregateException ? task.Exception.InnerException ?? task.Exception : task.Exception;
                        _logger.LogDebug($"The constraint '{constraint.Type}' failed to be initialized, details: {exception}.");
                        constraintResults.Add(TemplateConstraintResult.CreateInitializationFailure(constraint.Type, string.Format(LocalizableStrings.TemplateConstraintManager_Error_FailedToInitialize, constraint.Type, exception.Message)));
                        continue;
                    }

                    try
                    {
                        constraintResults.Add(task.Result.Evaluate(constraint.Args));
                    }
                    catch (Exception e)
                    {
                        _logger.LogDebug($"The constraint '{constraint.Type}' failed to be evaluated for the args '{constraint.Args}', details: {e}.");
                        constraintResults.Add(TemplateConstraintResult.CreateEvaluationFailure(_templateConstrains[constraint.Type].Result, string.Format(LocalizableStrings.TemplateConstraintManager_Error_FailedToEvaluate, constraint.Type, constraint.Args, e.Message)));
                    }
                }
                evaluationResult.Add((template, constraintResults));
            }
            return(evaluationResult);
        }