public async Task <CreationResultStatus> CoordinateInvocationOrAcquisitionAsync()
        {
            EnsureTemplateResolutionResult();

            if (_templateToInvoke != null)
            {
                // invoke and then check for updates
                CreationResultStatus creationResult = await InvokeTemplateAsync();

                // check for updates on this template (pack)
                await CheckForTemplateUpdateAsync();

                return(creationResult);
            }
            else
            {
                // The command didn't resolve to an installed template. Search for something that does.
                bool anySearchMatches = await SearchForTemplateMatchesAsync();

                if (!anySearchMatches)
                {
                    return(HelpForTemplateResolution.CoordinateHelpAndUsageDisplay(_templateResolutionResult, _environment, _commandInput, _hostDataLoader, _telemetryLogger, _templateCreator, _defaultLanguage));
                }
                else
                {
                    return(CreationResultStatus.Success);
                }
            }
        }
Ejemplo n.º 2
0
        internal TemplateCreationResult(
            CreationResultStatus status,
            string templateName,
            string?localizedErrorMessage     = null,
            ICreationResult?creationOutputs  = null,
            string?outputBaseDir             = null,
            ICreationEffects?creationEffects = null)
        {
            if (string.IsNullOrWhiteSpace(templateName))
            {
                throw new ArgumentException($"'{nameof(templateName)}' cannot be null or whitespace.", nameof(templateName));
            }

            Status       = status;
            ErrorMessage = localizedErrorMessage;
            if (string.IsNullOrWhiteSpace(ErrorMessage) && status != CreationResultStatus.Success)
            {
                throw new ArgumentException($"{nameof(localizedErrorMessage)} cannot be null or empty when {nameof(status)} is not {CreationResultStatus.Success}", nameof(localizedErrorMessage));
            }

            TemplateFullName    = templateName;
            CreationResult      = creationOutputs;
            OutputBaseDirectory = outputBaseDir;
            CreationEffects     = creationEffects;
        }
Ejemplo n.º 3
0
        private async Task <CreationResultStatus> EnterMaintenanceFlowAsync()
        {
            if (!ValidateRemainingParameters())
            {
                ShowUsageHelp();
                return(CreationResultStatus.InvalidParamValues);
            }

            if (InstallHasValue &&
                ((Install.Count > 0) && (Install[0] != null)))
            {
                CreationResultStatus installResult = await EnterInstallFlowAsync().ConfigureAwait(false);

                if (installResult == CreationResultStatus.Success)
                {
                    await PerformCoreTemplateQueryAsync().ConfigureAwait(false);

                    DisplayTemplateList();
                }

                return(installResult);
            }

            //No other cases specified, we've fallen through to "Usage help + List"
            ShowUsageHelp();
            await PerformCoreTemplateQueryAsync().ConfigureAwait(false);

            DisplayTemplateList();

            return(CreationResultStatus.Success);
        }
 public TemplateCreationResult(string message, CreationResultStatus status, string templateFullName, ICreationResult creationOutputs, string outputBaseDir)
 {
     Message             = message;
     Status              = status;
     TemplateFullName    = templateFullName;
     ResultInfo          = creationOutputs;
     OutputBaseDirectory = outputBaseDir;
 }
        private async Task <CreationResultStatus> EnterUpdateFlowAsync(INewCommandInput commandInput, CancellationToken cancellationToken)
        {
            _ = commandInput ?? throw new ArgumentNullException(nameof(commandInput));
            cancellationToken.ThrowIfCancellationRequested();

            bool applyUpdates            = commandInput.ApplyUpdates;
            bool allTemplatesUpToDate    = true;
            CreationResultStatus success = CreationResultStatus.Success;
            var managedTemplatePackages  = await _engineEnvironmentSettings.SettingsLoader.TemplatePackagesManager.GetManagedTemplatePackagesAsync().ConfigureAwait(false);

            foreach (var packagesGrouping in managedTemplatePackages.GroupBy(package => package.ManagedProvider))
            {
                var provider = packagesGrouping.Key;
                IReadOnlyList <CheckUpdateResult> checkUpdateResults = await provider.GetLatestVersionsAsync(packagesGrouping, cancellationToken).ConfigureAwait(false);

                DisplayUpdateCheckResults(checkUpdateResults, commandInput, showUpdates: !applyUpdates);
                if (checkUpdateResults.Any(result => !result.Success))
                {
                    success = CreationResultStatus.CreateFailed;
                }
                allTemplatesUpToDate = checkUpdateResults.All(result => result.Success && result.IsLatestVersion);

                if (applyUpdates)
                {
                    IEnumerable <CheckUpdateResult> updatesToApply = checkUpdateResults.Where(update => update.Success && !update.IsLatestVersion && !string.IsNullOrWhiteSpace(update.LatestVersion));
                    if (!updatesToApply.Any())
                    {
                        continue;
                    }

                    Reporter.Output.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Update_Info_PackagesToBeUpdated);
                    foreach (CheckUpdateResult update in updatesToApply)
                    {
                        Reporter.Output.WriteLine($"{update.TemplatePackage.Identifier}::{update.LatestVersion}".Indent());
                    }
                    Reporter.Output.WriteLine();

                    IReadOnlyList <UpdateResult> updateResults = await provider.UpdateAsync(updatesToApply.Select(update => new UpdateRequest(update.TemplatePackage, update.LatestVersion)), cancellationToken).ConfigureAwait(false);

                    foreach (var updateResult in updateResults)
                    {
                        if (!updateResult.Success)
                        {
                            success = CreationResultStatus.CreateFailed;
                        }
                        await DisplayInstallResultAsync(commandInput, updateResult.UpdateRequest.TemplatePackage.DisplayName, updateResult, cancellationToken).ConfigureAwait(false);
                    }
                }
            }

            if (allTemplatesUpToDate)
            {
                Reporter.Output.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Update_Info_AllPackagesAreUpToDate);
            }

            return(success);
        }
        public async Task <CreationResultStatus> CoordinateInvocationOrAcquisitionAsync(ITemplateMatchInfo templateToInvoke)
        {
            // invoke and then check for updates
            CreationResultStatus creationResult = await InvokeTemplateAsync(templateToInvoke).ConfigureAwait(false);

            // check for updates on this template (pack)
            await CheckForTemplateUpdateAsync(templateToInvoke).ConfigureAwait(false);

            return(creationResult);
        }
Ejemplo n.º 7
0
        // TODO: make sure help / usage works right in these cases.
        private CreationResultStatus EnterMaintenanceFlow()
        {
            if (!TemplateResolver.ValidateRemainingParameters(_commandInput, out IReadOnlyList <string> invalidParams))
            {
                HelpForTemplateResolution.DisplayInvalidParameters(invalidParams);
                if (_commandInput.IsHelpFlagSpecified)
                {
                    // this code path doesn't go through the full help & usage stack, so needs it's own call to ShowUsageHelp().
                    HelpForTemplateResolution.ShowUsageHelp(_commandInput, _telemetryLogger);
                }
                else
                {
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, CommandName).Bold().Red());
                }

                return(CreationResultStatus.InvalidParamValues);
            }

            if (_commandInput.ToUninstallList != null)
            {
                return(EnterUninstallFlow());
            }

            if (_commandInput.ToInstallList != null && _commandInput.ToInstallList.Count > 0 && _commandInput.ToInstallList[0] != null)
            {
                CreationResultStatus installResult = EnterInstallFlow();

                if (installResult == CreationResultStatus.Success)
                {
                    _settingsLoader.Reload();
                    TemplateListResolutionResult resolutionResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(_settingsLoader.UserTemplateCache.TemplateInfo, _hostDataLoader, _commandInput, _defaultLanguage);
                    HelpForTemplateResolution.CoordinateHelpAndUsageDisplay(resolutionResult, EnvironmentSettings, _commandInput, _hostDataLoader, _telemetryLogger, _templateCreator, _defaultLanguage, showUsageHelp: false);
                }

                return(installResult);
            }

            // No other cases specified, we've fallen through to "Optional usage help + List"
            TemplateListResolutionResult templateResolutionResult = TemplateResolver.GetTemplateResolutionResultForListOrHelp(_settingsLoader.UserTemplateCache.TemplateInfo, _hostDataLoader, _commandInput, _defaultLanguage);

            HelpForTemplateResolution.CoordinateHelpAndUsageDisplay(templateResolutionResult, EnvironmentSettings, _commandInput, _hostDataLoader, _telemetryLogger, _templateCreator, _defaultLanguage, showUsageHelp: _commandInput.IsHelpFlagSpecified);

            return(CreationResultStatus.Success);
        }
        public async Task <CreationResultStatus> CoordinateInvocationOrAcquisitionAsync()
        {
            EnsureTemplateResolutionResult();

            if (_templateToInvoke != null)
            {
                // invoke and then check for updates
                CreationResultStatus creationResult = await InvokeTemplateAsync();

                // check for updates on this template (pack)
                await CheckForTemplateUpdateAsync();

                return(creationResult);
            }
            else
            {
                ListOrHelpTemplateListResolutionResult listingTemplateListResolutionResult = TemplateListResolver.GetTemplateResolutionResultForListOrHelp(_settingsLoader.UserTemplateCache.TemplateInfo, _hostDataLoader, _commandInput, _defaultLanguage);
                return(HelpForTemplateResolution.CoordinateHelpAndUsageDisplay(listingTemplateListResolutionResult, _environment, _commandInput, _hostDataLoader, _telemetryLogger, _templateCreator, _defaultLanguage, false));
            }
        }
        private async Task <CreationResultStatus> EnterUninstallFlowAsync(INewCommandInput commandInput, CancellationToken cancellationToken)
        {
            _ = commandInput ?? throw new ArgumentNullException(nameof(commandInput));
            cancellationToken.ThrowIfCancellationRequested();

            CreationResultStatus result = CreationResultStatus.Success;

            if (commandInput.ToUninstallList.Count <= 0 || commandInput.ToUninstallList[0] == null)
            {
                //display all installed template packages
                await DisplayInstalledTemplatePackages(commandInput, cancellationToken).ConfigureAwait(false);

                return(result);
            }

            Dictionary <IManagedTemplatePackageProvider, List <IManagedTemplatePackage> > sourcesToUninstall;

            (result, sourcesToUninstall) = await DetermineSourcesToUninstall(commandInput, cancellationToken).ConfigureAwait(false);

            foreach (KeyValuePair <IManagedTemplatePackageProvider, List <IManagedTemplatePackage> > providerSourcesToUninstall in sourcesToUninstall)
            {
                IReadOnlyList <UninstallResult> uninstallResults = await providerSourcesToUninstall.Key.UninstallAsync(providerSourcesToUninstall.Value, cancellationToken).ConfigureAwait(false);

                foreach (UninstallResult uninstallResult in uninstallResults)
                {
                    if (uninstallResult.Success)
                    {
                        Reporter.Output.WriteLine(
                            string.Format(
                                LocalizableStrings.TemplatePackageCoordinator_Uninstall_Info_Success,
                                uninstallResult.TemplatePackage.DisplayName));
                    }
                    else
                    {
                        Reporter.Error.WriteLine(string.Format(LocalizableStrings.TemplatePackageCoordinator_Uninstall_Error_GenericError, uninstallResult.TemplatePackage.DisplayName, uninstallResult.ErrorMessage));
                        result = CreationResultStatus.CreateFailed;
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 10
0
        private static CreationResultStatus ManipulateAliasValue(string aliasName, IReadOnlyList <string> aliasTokens, AliasRegistry aliasRegistry)
        {
            AliasManipulationResult result       = aliasRegistry.TryCreateOrRemoveAlias(aliasName, aliasTokens);
            CreationResultStatus    returnStatus = CreationResultStatus.OperationNotSpecified;

            switch (result.Status)
            {
            case AliasManipulationStatus.Created:
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.AliasCreated, result.AliasName, result.AliasValue));
                returnStatus = CreationResultStatus.Success;
                break;

            case AliasManipulationStatus.Removed:
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.AliasRemoved, result.AliasName, result.AliasValue));
                returnStatus = CreationResultStatus.Success;
                break;

            case AliasManipulationStatus.RemoveNonExistentFailed:
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.AliasRemoveNonExistentFailed, result.AliasName));
                break;

            case AliasManipulationStatus.Updated:
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.AliasUpdated, result.AliasName, result.AliasValue));
                returnStatus = CreationResultStatus.Success;
                break;

            case AliasManipulationStatus.WouldCreateCycle:
                Reporter.Output.WriteLine(LocalizableStrings.AliasCycleError);
                returnStatus = CreationResultStatus.CreateFailed;
                break;

            case AliasManipulationStatus.InvalidInput:
                Reporter.Output.WriteLine(LocalizableStrings.AliasNotCreatedInvalidInput);
                returnStatus = CreationResultStatus.InvalidParamValues;
                break;
            }

            return(returnStatus);
        }
Ejemplo n.º 11
0
        private async Task <CreationResultStatus> ExecuteAsync()
        {
            // this is checking the initial parse, which is template agnostic.
            if (_commandInput.HasParseError)
            {
                return(HelpForTemplateResolution.HandleParseError(_commandInput, _telemetryLogger));
            }

            if (_commandInput.IsHelpFlagSpecified)
            {
                _telemetryLogger.TrackEvent(CommandName + TelemetryConstants.HelpEventSuffix);
            }

            if (_commandInput.ShowAliasesSpecified)
            {
                return(AliasSupport.DisplayAliasValues(EnvironmentSettings, _commandInput, _aliasRegistry, CommandName));
            }

            if (_commandInput.ExpandedExtraArgsFiles && string.IsNullOrEmpty(_commandInput.Alias))
            {   // Only show this if there was no alias expansion.
                // ExpandedExtraArgsFiles must be checked before alias expansion - it'll get reset if there's an alias.
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.ExtraArgsCommandAfterExpansion, string.Join(" ", _commandInput.Tokens)));
            }

            if (string.IsNullOrEmpty(_commandInput.Alias))
            {
                // The --alias param is for creating / updating / deleting aliases.
                // If it's not present, try expanding aliases now.
                CreationResultStatus aliasExpansionResult = AliasSupport.CoordinateAliasExpansion(_commandInput, _aliasRegistry, _telemetryLogger);

                if (aliasExpansionResult != CreationResultStatus.Success)
                {
                    return(aliasExpansionResult);
                }
            }

            if (!ConfigureLocale())
            {
                return(CreationResultStatus.InvalidParamValues);
            }

            if (!Initialize())
            {
                return(CreationResultStatus.Success);
            }

            try
            {
                bool isHiveUpdated = SyncOptionalWorkloads();
                if (isHiveUpdated)
                {
                    Reporter.Output.WriteLine(LocalizableStrings.OptionalWorkloadsSynchronized);
                }
            }
            catch (HiveSynchronizationException hiex)
            {
                Reporter.Error.WriteLine(hiex.Message.Bold().Red());
            }

            bool forceCacheRebuild = _commandInput.HasDebuggingFlag("--debug:rebuildcache");

            try
            {
                _settingsLoader.RebuildCacheFromSettingsIfNotCurrent(forceCacheRebuild);
            }
            catch (EngineInitializationException eiex)
            {
                Reporter.Error.WriteLine(eiex.Message.Bold().Red());
                Reporter.Error.WriteLine(LocalizableStrings.SettingsReadError);
                return(CreationResultStatus.CreateFailed);
            }

            try
            {
                if (!string.IsNullOrEmpty(_commandInput.Alias) && !_commandInput.IsHelpFlagSpecified)
                {
                    return(AliasSupport.ManipulateAliasIfValid(_aliasRegistry, _commandInput.Alias, _commandInput.Tokens.ToList(), AllTemplateShortNames));
                }

                if (_commandInput.CheckForUpdates || _commandInput.CheckForUpdatesNoPrompt)
                {
                    bool applyUpdates          = _commandInput.CheckForUpdatesNoPrompt;
                    CliTemplateUpdater updater = new CliTemplateUpdater(EnvironmentSettings, Installer, CommandName);
                    bool updateCheckResult     = await updater.CheckForUpdatesAsync(_settingsLoader.InstallUnitDescriptorCache.Descriptors.Values.ToList(), applyUpdates);

                    return(updateCheckResult ? CreationResultStatus.Success : CreationResultStatus.CreateFailed);
                }

                if (_commandInput.SearchOnline)
                {
                    return(await CliTemplateSearchCoordinator.SearchForTemplateMatchesAsync(EnvironmentSettings, _commandInput, _defaultLanguage).ConfigureAwait(false));
                }

                if (string.IsNullOrWhiteSpace(TemplateName))
                {
                    return(EnterMaintenanceFlow());
                }

                return(await EnterTemplateManipulationFlowAsync().ConfigureAwait(false));
            }
            catch (TemplateAuthoringException tae)
            {
                Reporter.Error.WriteLine(tae.Message.Bold().Red());
                return(CreationResultStatus.CreateFailed);
            }
        }
Ejemplo n.º 12
0
        private async Task TrackItemGenAsync(string eventToTrack, GenStatusEnum status, UserSelectionContext context, string templateName, GenSourceEnum genSource, CreationResultStatus genStatus = CreationResultStatus.Success, string message = "")
        {
            // TODO: Remove TelemetryProperties.Framework and use TelemetryProperties.FrontendFramework
            var properties = new Dictionary <string, string>
            {
                { TelemetryProperties.Status, status.ToString() },
                { TelemetryProperties.Framework, context.FrontEndFramework },
                { TelemetryProperties.FrontendFramework, context.FrontEndFramework },
                { TelemetryProperties.BackendFramework, context.BackEndFramework },
                { TelemetryProperties.TemplateName, templateName },
                { TelemetryProperties.GenEngineStatus, genStatus.ToString() },
                { TelemetryProperties.GenEngineMessage, message },
                { TelemetryProperties.EventName, eventToTrack },
                { TelemetryProperties.GenSource, genSource.ToString() },
                { TelemetryProperties.ProjectType, context.ProjectType },
                { TelemetryProperties.VsProjectCategory, context.Platform },
            };

            AddPropertiesFromPropertyBag(context, properties);

            await TelemetryService.Current.TrackEventAsync(eventToTrack, properties).ConfigureAwait(false);
        }
Ejemplo n.º 13
0
        private async Task TrackProjectAsync(GenStatusEnum status, string templateName, UserSelectionContext context, Guid vsProjectId, GenItemsTelemetryData genItemsTelemetryData = null, double?timeSpent = null, Dictionary <ProjectMetricsEnum, double> performanceCounters = null, CreationResultStatus genStatus = CreationResultStatus.Success, string message = "")
        {
            // TODO: Remove TelemetryProperties.Framework and use TelemetryProperties.FrontendFramework
            var properties = new Dictionary <string, string>()
            {
                { TelemetryProperties.Status, status.ToString() },
                { TelemetryProperties.ProjectType, context.ProjectType },
                { TelemetryProperties.Framework, context.FrontEndFramework },
                { TelemetryProperties.FrontendFramework, context.FrontEndFramework },
                { TelemetryProperties.BackendFramework, context.BackEndFramework },
                { TelemetryProperties.TemplateName, templateName },
                { TelemetryProperties.GenEngineStatus, genStatus.ToString() },
                { TelemetryProperties.GenEngineMessage, message },
                { TelemetryProperties.EventName, TelemetryEvents.ProjectGen },
                { TelemetryProperties.Language, context.Language },
                { TelemetryProperties.VisualStudioActiveProjectGuid, vsProjectId.ToString() },
                { TelemetryProperties.VsProjectCategory, context.Platform },
            };

            AddPropertiesFromPropertyBag(context, properties);

            var metrics = new Dictionary <string, double>();

            if (genItemsTelemetryData.PagesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.PagesCount, genItemsTelemetryData.PagesCount.Value);
            }

            if (genItemsTelemetryData.FeaturesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.FeaturesCount, genItemsTelemetryData.FeaturesCount.Value);
            }

            if (genItemsTelemetryData.ServicesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.ServicesCount, genItemsTelemetryData.ServicesCount.Value);
            }

            if (genItemsTelemetryData.TestingCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.TestingCount, genItemsTelemetryData.TestingCount.Value);
            }

            if (timeSpent.HasValue)
            {
                metrics.Add(TelemetryMetrics.TimeSpent, timeSpent.Value);
            }

            if (performanceCounters != null)
            {
                foreach (var perfCounter in performanceCounters)
                {
                    metrics.Add(TelemetryMetrics.ProjectMetricsTimeSpent + perfCounter.Key.ToString(), perfCounter.Value);
                }
            }

            GenContext.ToolBox.Shell.SafeTrackProjectVsTelemetry(properties, genItemsTelemetryData.PageIdentities, genItemsTelemetryData.FeatureIdentities, genItemsTelemetryData.ServiceIdentities, genItemsTelemetryData.TestingIdentities, metrics, status == GenStatusEnum.Completed);

            await TelemetryService.Current.TrackEventAsync(TelemetryEvents.ProjectGen, properties, metrics).ConfigureAwait(false);
        }
Ejemplo n.º 14
0
        public async Task TrackNewItemAsync(TemplateType templateType, UserSelectionContext context, Guid vsProjectId, GenItemsTelemetryData genItemsTelemetryData = null, double?timeSpent = null, CreationResultStatus genStatus = CreationResultStatus.Success, string message = "")
        {
            var itemType       = templateType.GetNewItemType();
            var itemTypeString = itemType != null?itemType.ToString() : string.Empty;

            // TODO: Remove TelemetryProperties.Framework and use TelemetryProperties.FrontendFramework
            var properties = new Dictionary <string, string>()
            {
                { TelemetryProperties.ProjectType, context.ProjectType },
                { TelemetryProperties.Framework, context.FrontEndFramework },
                { TelemetryProperties.FrontendFramework, context.FrontEndFramework },
                { TelemetryProperties.BackendFramework, context.BackEndFramework },
                { TelemetryProperties.GenEngineStatus, genStatus.ToString() },
                { TelemetryProperties.GenEngineMessage, message },
                { TelemetryProperties.EventName, TelemetryEvents.NewItemGen },
                { TelemetryProperties.VisualStudioActiveProjectGuid, vsProjectId.ToString() },
                { TelemetryProperties.Language, context.Language },
                { TelemetryProperties.VsProjectCategory, context.Platform },
                { TelemetryProperties.NewItemType, itemTypeString },
            };

            AddPropertiesFromPropertyBag(context, properties);

            var metrics = new Dictionary <string, double>();

            if (genItemsTelemetryData.PagesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.PagesCount, genItemsTelemetryData.PagesCount.Value);
            }

            if (timeSpent.HasValue)
            {
                metrics.Add(TelemetryMetrics.TimeSpent, timeSpent.Value);
            }

            if (genItemsTelemetryData.FeaturesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.FeaturesCount, genItemsTelemetryData.FeaturesCount.Value);
            }

            if (genItemsTelemetryData.ServicesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.ServicesCount, genItemsTelemetryData.ServicesCount.Value);
            }

            if (genItemsTelemetryData.TestingCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.TestingCount, genItemsTelemetryData.TestingCount.Value);
            }

            GenContext.ToolBox.Shell.SafeTrackNewItemVsTelemetry(properties, genItemsTelemetryData.PageIdentities, genItemsTelemetryData.FeatureIdentities, genItemsTelemetryData.ServiceIdentities, genItemsTelemetryData.TestingIdentities, metrics);

            await TelemetryService.Current.TrackEventAsync(TelemetryEvents.NewItemGen, properties, metrics).ConfigureAwait(false);
        }
Ejemplo n.º 15
0
        private async Task TrackItemGenAsync(string eventToTrack, GenStatusEnum status, string appType, string pageFx, string templateName, GenSourceEnum genSource, CreationResultStatus genStatus = CreationResultStatus.Success, string message = "")
        {
            var properties = new Dictionary <string, string>()
            {
                { TelemetryProperties.Status, status.ToString() },
                { TelemetryProperties.Framework, pageFx },
                { TelemetryProperties.TemplateName, templateName },
                { TelemetryProperties.GenEngineStatus, genStatus.ToString() },
                { TelemetryProperties.GenEngineMessage, message },
                { TelemetryProperties.EventName, eventToTrack },
                { TelemetryProperties.GenSource, genSource.ToString() }
            };

            await TelemetryService.Current.TrackEventAsync(eventToTrack, properties).ConfigureAwait(false);
        }
Ejemplo n.º 16
0
        private async Task TrackProjectAsync(GenStatusEnum status, string templateName, string appType, string appFx, Guid vsProjectId, int?pagesCount = null, int?featuresCount = null, string pageIdentities = "", string featureIdentites = "", double?timeSpent = null, CreationResultStatus genStatus = CreationResultStatus.Success, string message = "")
        {
            var properties = new Dictionary <string, string>()
            {
                { TelemetryProperties.Status, status.ToString() },
                { TelemetryProperties.ProjectType, appType },
                { TelemetryProperties.Framework, appFx },
                { TelemetryProperties.TemplateName, templateName },
                { TelemetryProperties.GenEngineStatus, genStatus.ToString() },
                { TelemetryProperties.GenEngineMessage, message },
                { TelemetryProperties.EventName, TelemetryEvents.ProjectGen },
                { TelemetryProperties.VisualStudioActiveProjectGuid, vsProjectId.ToString() },
                { TelemetryProperties.VsProjectCategory, "Uwp" }
            };

            var metrics = new Dictionary <string, double>();

            if (pagesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.PagesCount, pagesCount.Value);
            }

            if (timeSpent.HasValue)
            {
                metrics.Add(TelemetryMetrics.TimeSpent, timeSpent.Value);
            }

            if (featuresCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.FeaturesCount, featuresCount.Value);
            }

            TelemetryService.Current.SafeTrackProjectVsTelemetry(properties, pageIdentities, featureIdentites, metrics, status == GenStatusEnum.Completed);

            await TelemetryService.Current.TrackEventAsync(TelemetryEvents.ProjectGen, properties, metrics).ConfigureAwait(false);
        }
Ejemplo n.º 17
0
        // TODO: make sure help / usage works right in these cases.
        private CreationResultStatus EnterMaintenanceFlow()
        {
            if (!TemplateListResolver.ValidateRemainingParameters(_commandInput, out IReadOnlyList <string> invalidParams))
            {
                HelpForTemplateResolution.DisplayInvalidParameters(invalidParams);
                if (_commandInput.IsHelpFlagSpecified)
                {
                    _telemetryLogger.TrackEvent(CommandName + "-Help");
                    HelpForTemplateResolution.ShowUsageHelp(_commandInput);
                }
                else
                {
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, CommandName).Bold().Red());
                }

                return(CreationResultStatus.InvalidParamValues);
            }

            if (_commandInput.ToUninstallList != null)
            {
                if (_commandInput.ToUninstallList.Count > 0 && _commandInput.ToUninstallList[0] != null)
                {
                    IEnumerable <string> failures = Installer.Uninstall(_commandInput.ToUninstallList);

                    foreach (string failure in failures)
                    {
                        Console.WriteLine(LocalizableStrings.CouldntUninstall, failure);
                    }
                }
                else
                {
                    Console.WriteLine(LocalizableStrings.CommandDescription);
                    Console.WriteLine();
                    Console.WriteLine(LocalizableStrings.InstalledItems);

                    foreach (string value in _settingsLoader.InstallUnitDescriptorCache.InstalledItems.Values)
                    {
                        Console.WriteLine($" {value}");
                    }

                    return(CreationResultStatus.Success);
                }
            }

            if (_commandInput.ToInstallList != null && _commandInput.ToInstallList.Count > 0 && _commandInput.ToInstallList[0] != null)
            {
                CreationResultStatus installResult = EnterInstallFlow();

                if (installResult == CreationResultStatus.Success)
                {
                    _settingsLoader.Reload();
                    TemplateListResolutionResult resolutionResult = QueryForTemplateMatches();
                    HelpForTemplateResolution.CoordinateHelpAndUsageDisplay(resolutionResult, EnvironmentSettings, _commandInput, _hostDataLoader, _telemetryLogger, _templateCreator, _defaultLanguage);
                }

                return(installResult);
            }

            //No other cases specified, we've fallen through to "Usage help + List"
            HelpForTemplateResolution.ShowUsageHelp(_commandInput);
            TemplateListResolutionResult templateResolutionResult = QueryForTemplateMatches();

            HelpForTemplateResolution.CoordinateHelpAndUsageDisplay(templateResolutionResult, EnvironmentSettings, _commandInput, _hostDataLoader, _telemetryLogger, _templateCreator, _defaultLanguage);

            return(CreationResultStatus.Success);
        }
        private async Task <CreationResultStatus> EnterInstallFlowAsync(INewCommandInput commandInput, CancellationToken cancellationToken)
        {
            _ = commandInput ?? throw new ArgumentNullException(nameof(commandInput));
            cancellationToken.ThrowIfCancellationRequested();

            CreationResultStatus resultStatus = CreationResultStatus.Success;

            _telemetryLogger.TrackEvent(commandInput.CommandName + TelemetryConstants.InstallEventSuffix, new Dictionary <string, string> {
                { TelemetryConstants.ToInstallCount, commandInput.ToInstallList.Count.ToString() }
            });

            var details = new Dictionary <string, string>();

            if (commandInput.InstallNuGetSourceList?.Count > 0)
            {
                details[InstallerConstants.NuGetSourcesKey] = string.Join(InstallerConstants.NuGetSourcesSeparator.ToString(), commandInput.InstallNuGetSourceList);
            }
            if (commandInput.IsInteractiveFlagSpecified)
            {
                details[InstallerConstants.InteractiveModeKey] = "true";
            }

            // In future we might want give user ability to pick IManagerSourceProvider by Name or GUID
            var managedSourceProvider             = _engineEnvironmentSettings.SettingsLoader.TemplatePackagesManager.GetBuiltInManagedProvider(InstallationScope.Global);
            List <InstallRequest> installRequests = new List <InstallRequest>();

            foreach (string installArg in commandInput.ToInstallList)
            {
                string[] splitByColons = installArg.Split(new[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
                string   identifier    = splitByColons[0];
                string?  version       = null;
                //'*' is placeholder for the latest version
                if (splitByColons.Length > 1 && splitByColons[1] != "*")
                {
                    version = splitByColons[1];
                }
                foreach (string expandedIdentifier in InstallRequestPathResolution.ExpandMaskedPath(identifier, _engineEnvironmentSettings))
                {
                    installRequests.Add(new InstallRequest(expandedIdentifier, version, details: details));
                }
            }

            if (!installRequests.Any())
            {
                Reporter.Error.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Install_Error_FoundNoPackagesToInstall);
                return(CreationResultStatus.NotFound);
            }

            //validate if installation requests have unique identifier
            HashSet <string> identifiers = new HashSet <string>();

            foreach (InstallRequest installRequest in installRequests)
            {
                if (identifiers.Add(installRequest.PackageIdentifier))
                {
                    continue;
                }
                Reporter.Error.WriteLine(string.Format(LocalizableStrings.TemplatePackageCoordinator_Install_Error_SameInstallRequests, installRequest.PackageIdentifier));
                return(CreationResultStatus.Cancelled);
            }

            Reporter.Output.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Install_Info_PackagesToBeInstalled);
            foreach (InstallRequest installRequest in installRequests)
            {
                Reporter.Output.WriteLine(installRequest.DisplayName.Indent());
            }
            Reporter.Output.WriteLine();

            IReadOnlyList <InstallResult> installResults = await managedSourceProvider.InstallAsync(installRequests, cancellationToken).ConfigureAwait(false);

            foreach (InstallResult result in installResults)
            {
                await DisplayInstallResultAsync(commandInput, result.InstallRequest.DisplayName, result, cancellationToken).ConfigureAwait(false);

                if (!result.Success)
                {
                    resultStatus = CreationResultStatus.CreateFailed;
                }
            }
            return(resultStatus);
        }
Ejemplo n.º 19
0
        // TODO: make sure help / usage works right in these cases.
        private CreationResultStatus EnterMaintenanceFlow()
        {
            if (!TemplateListResolver.ValidateRemainingParameters(_commandInput, out IReadOnlyList <string> invalidParams))
            {
                HelpForTemplateResolution.DisplayInvalidParameters(invalidParams);
                if (_commandInput.IsHelpFlagSpecified)
                {
                    // this code path doesn't go through the full help & usage stack, so needs it's own call to ShowUsageHelp().
                    HelpForTemplateResolution.ShowUsageHelp(_commandInput, _telemetryLogger);
                }
                else
                {
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, CommandName).Bold().Red());
                }

                return(CreationResultStatus.InvalidParamValues);
            }

            if (_commandInput.ToUninstallList != null)
            {
                if (_commandInput.ToUninstallList.Count > 0 && _commandInput.ToUninstallList[0] != null)
                {
                    IEnumerable <string> failures = Installer.Uninstall(_commandInput.ToUninstallList);

                    foreach (string failure in failures)
                    {
                        Console.WriteLine(LocalizableStrings.CouldntUninstall, failure);
                    }
                }
                else
                {
                    Console.WriteLine(LocalizableStrings.CommandDescription);
                    Console.WriteLine();
                    Console.WriteLine(LocalizableStrings.InstalledItems);

                    foreach (KeyValuePair <Guid, string> entry in _settingsLoader.InstallUnitDescriptorCache.InstalledItems)
                    {
                        Console.WriteLine($"  {entry.Value}");

                        if (_settingsLoader.InstallUnitDescriptorCache.Descriptors.TryGetValue(entry.Value, out IInstallUnitDescriptor descriptor))
                        {
                            if (descriptor.Details != null && descriptor.Details.TryGetValue("Version", out string versionValue))
                            {
                                Console.WriteLine($"    {LocalizableStrings.Version} {versionValue}");
                            }
                        }

                        HashSet <string> displayStrings = new HashSet <string>(StringComparer.Ordinal);

                        foreach (TemplateInfo info in _settingsLoader.UserTemplateCache.TemplateInfo.Where(x => x.ConfigMountPointId == entry.Key))
                        {
                            string str = $"      {info.Name} ({info.ShortName})";

                            if (info.Tags != null && info.Tags.TryGetValue("language", out ICacheTag languageTag))
                            {
                                str += " " + string.Join(", ", languageTag.ChoicesAndDescriptions.Select(x => x.Key));
                            }

                            displayStrings.Add(str);
                        }

                        if (displayStrings.Count > 0)
                        {
                            Console.WriteLine($"    {LocalizableStrings.Templates}:");

                            foreach (string displayString in displayStrings)
                            {
                                Console.WriteLine(displayString);
                            }
                        }
                    }

                    return(CreationResultStatus.Success);
                }
            }

            if (_commandInput.ToInstallList != null && _commandInput.ToInstallList.Count > 0 && _commandInput.ToInstallList[0] != null)
            {
                CreationResultStatus installResult = EnterInstallFlow();

                if (installResult == CreationResultStatus.Success)
                {
                    _settingsLoader.Reload();
                    TemplateListResolutionResult resolutionResult = QueryForTemplateMatches();
                    HelpForTemplateResolution.CoordinateHelpAndUsageDisplay(resolutionResult, EnvironmentSettings, _commandInput, _hostDataLoader, _telemetryLogger, _templateCreator, _defaultLanguage);
                }

                return(installResult);
            }

            //No other cases specified, we've fallen through to "Usage help + List"
            TemplateListResolutionResult templateResolutionResult = QueryForTemplateMatches();

            HelpForTemplateResolution.CoordinateHelpAndUsageDisplay(templateResolutionResult, EnvironmentSettings, _commandInput, _hostDataLoader, _telemetryLogger, _templateCreator, _defaultLanguage);

            return(CreationResultStatus.Success);
        }
Ejemplo n.º 20
0
        private async Task TrackProjectAsync(GenStatusEnum status, string templateName, string appType, string appFx, string appPlatform, Guid vsProjectId, string language, GenItemsTelemetryData genItemsTelemetryData = null, double?timeSpent = null, Dictionary <ProjectMetricsEnum, double> performanceCounters = null, CreationResultStatus genStatus = CreationResultStatus.Success, string message = "")
        {
            var properties = new Dictionary <string, string>()
            {
                { TelemetryProperties.Status, status.ToString() },
                { TelemetryProperties.ProjectType, appType },
                { TelemetryProperties.Framework, appFx },
                { TelemetryProperties.TemplateName, templateName },
                { TelemetryProperties.GenEngineStatus, genStatus.ToString() },
                { TelemetryProperties.GenEngineMessage, message },
                { TelemetryProperties.EventName, TelemetryEvents.ProjectGen },
                { TelemetryProperties.Language, language },
                { TelemetryProperties.VisualStudioActiveProjectGuid, vsProjectId.ToString() },
                { TelemetryProperties.VsProjectCategory, appPlatform },
            };

            var metrics = new Dictionary <string, double>();

            if (genItemsTelemetryData.PagesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.PagesCount, genItemsTelemetryData.PagesCount.Value);
            }

            if (genItemsTelemetryData.FeaturesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.FeaturesCount, genItemsTelemetryData.FeaturesCount.Value);
            }

            if (timeSpent.HasValue)
            {
                metrics.Add(TelemetryMetrics.TimeSpent, timeSpent.Value);
            }

            if (performanceCounters != null)
            {
                foreach (var perfCounter in performanceCounters)
                {
                    metrics.Add(TelemetryMetrics.ProjectMetricsTimeSpent + perfCounter.Key.ToString(), perfCounter.Value);
                }
            }

            TelemetryService.Current.SafeTrackProjectVsTelemetry(properties, genItemsTelemetryData.PageIdentities, genItemsTelemetryData.FeatureIdentities, metrics, status == GenStatusEnum.Completed);

            await TelemetryService.Current.TrackEventAsync(TelemetryEvents.ProjectGen, properties, metrics).ConfigureAwait(false);
        }
        private async Task TrackProjectAsync(GenStatusEnum status, string templateName, string appType, string appFx, int?pagesCount = null, int?featuresCount = null, double?timeSpent = null, CreationResultStatus genStatus = CreationResultStatus.Success, string message = "")
        {
            Dictionary <string, string> properties = new Dictionary <string, string>()
            {
                { TelemetryProperties.Status, status.ToString() },
                { TelemetryProperties.ProjectType, appType },
                { TelemetryProperties.Framework, appFx },
                { TelemetryProperties.TemplateName, templateName },
                { TelemetryProperties.GenEngineStatus, genStatus.ToString() },
                { TelemetryProperties.GenEngineMessage, message },
                { TelemetryProperties.EventName, TelemetryEvents.ProjectGen }
            };

            Dictionary <string, double> metrics = new Dictionary <string, double>();

            if (pagesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.PagesCount, pagesCount.Value);
            }

            if (timeSpent.HasValue)
            {
                metrics.Add(TelemetryMetrics.TimeSpent, timeSpent.Value);
            }

            if (featuresCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.FeaturesCount, featuresCount.Value);
            }

            await TelemetryService.Current.TrackEventAsync(TelemetryEvents.ProjectGen, properties, metrics).ConfigureAwait(false);
        }
        private async Task <(CreationResultStatus, Dictionary <IManagedTemplatePackageProvider, List <IManagedTemplatePackage> >)> DetermineSourcesToUninstall(INewCommandInput commandInput, CancellationToken cancellationToken)
        {
            _ = commandInput ?? throw new ArgumentNullException(nameof(commandInput));
            cancellationToken.ThrowIfCancellationRequested();

            CreationResultStatus result = CreationResultStatus.Success;
            IReadOnlyList <IManagedTemplatePackage> templatePackages = await _engineEnvironmentSettings.SettingsLoader.TemplatePackagesManager.GetManagedTemplatePackagesAsync().ConfigureAwait(false);

            var packagesToUninstall = new Dictionary <IManagedTemplatePackageProvider, List <IManagedTemplatePackage> >();

            foreach (string templatePackageIdentifier in commandInput.ToUninstallList)
            {
                bool templatePackageIdentified = false;

                foreach (IManagedTemplatePackage templatePackage in templatePackages)
                {
                    if (templatePackage.Identifier.Equals(templatePackageIdentifier, StringComparison.OrdinalIgnoreCase))
                    {
                        templatePackageIdentified = true;
                        if (packagesToUninstall.TryGetValue(templatePackage.ManagedProvider, out List <IManagedTemplatePackage> packages))
                        {
                            packages.Add(templatePackage);
                        }
                        else
                        {
                            packagesToUninstall[templatePackage.ManagedProvider] = new List <IManagedTemplatePackage>()
                            {
                                templatePackage
                            };
                        }
                    }
                }

                if (templatePackageIdentified)
                {
                    continue;
                }

                result = CreationResultStatus.NotFound;
                Reporter.Error.WriteLine(
                    string.Format(
                        LocalizableStrings.TemplatePackageCoordinator_Error_PackageNotFound,
                        templatePackageIdentifier).Bold().Red());
                if (await IsTemplateShortNameAsync(templatePackageIdentifier, cancellationToken).ConfigureAwait(false))
                {
                    var packages = await GetTemplatePackagesByShortNameAsync(templatePackageIdentifier, cancellationToken).ConfigureAwait(false);

                    var managedPackages = packages.OfType <IManagedTemplatePackage>();
                    if (managedPackages.Any())
                    {
                        Reporter.Error.WriteLine(
                            string.Format(
                                LocalizableStrings.TemplatePackageCoordinator_Error_TemplateIncludedToPackages,
                                templatePackageIdentifier));
                        foreach (IManagedTemplatePackage managedPackage in managedPackages)
                        {
                            IEnumerable <ITemplateInfo> templates = await managedPackage.GetTemplates(_engineEnvironmentSettings).ConfigureAwait(false);

                            var templateGroupsCount = templates.GroupBy(x => x.GroupIdentity, x => !string.IsNullOrEmpty(x.GroupIdentity), StringComparer.OrdinalIgnoreCase).Count();
                            Reporter.Error.WriteLine(
                                string.Format(
                                    LocalizableStrings.TemplatePackageCoordinator_Error_PackageNameContainsTemplates,
                                    managedPackage.DisplayName,
                                    templateGroupsCount).Indent());
                        }
                        Reporter.Error.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Uninstall_Error_UninstallCommandHeader);
                        Reporter.Error.WriteCommand(commandInput.UninstallCommandExample(managedPackages?.First().Identifier ?? ""));
                        //TODO:
                        //Reporter.Error.WriteLine($"To list the templates installed in a package, use dotnet new3 <new option> <package name>.");
                    }
                    else
                    {
                        Reporter.Error.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Uninstall_Error_ListPackagesHeader);
                        Reporter.Error.WriteCommand(commandInput.UninstallCommandExample(noArgs: true));
                    }
                }
                else
                {
                    Reporter.Error.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Uninstall_Error_ListPackagesHeader);
                    Reporter.Error.WriteCommand(commandInput.UninstallCommandExample(noArgs: true));
                }
                Reporter.Error.WriteLine();
            }
            return(result, packagesToUninstall);
        }
 public TemplateCreationResult(string message, CreationResultStatus status, string templateFullName)
     : this(message, status, templateFullName, null, null)
 {
 }
        public async Task TrackNewItemAsync(TemplateType templateType, string appType, string appFx, string appPlatform, Guid vsProjectId, int?pagesCount = null, int?featuresCount = null, string pageIdentities = "", string featuresIdentities = "", double?timeSpent = null, CreationResultStatus genStatus = CreationResultStatus.Success, string message = "")
        {
            var newItemType = templateType == TemplateType.Page ? NewItemType.Page : NewItemType.Feature;

            var properties = new Dictionary <string, string>()
            {
                { TelemetryProperties.ProjectType, appType },
                { TelemetryProperties.Framework, appFx },
                { TelemetryProperties.GenEngineStatus, genStatus.ToString() },
                { TelemetryProperties.GenEngineMessage, message },
                { TelemetryProperties.EventName, TelemetryEvents.NewItemGen },
                { TelemetryProperties.VisualStudioActiveProjectGuid, vsProjectId.ToString() },
                { TelemetryProperties.VsProjectCategory, appPlatform },
                { TelemetryProperties.NewItemType, newItemType.ToString() },
            };

            var metrics = new Dictionary <string, double>();

            if (pagesCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.PagesCount, pagesCount.Value);
            }

            if (timeSpent.HasValue)
            {
                metrics.Add(TelemetryMetrics.TimeSpent, timeSpent.Value);
            }

            if (featuresCount.HasValue)
            {
                metrics.Add(TelemetryMetrics.FeaturesCount, featuresCount.Value);
            }

            TelemetryService.Current.SafeTrackNewItemVsTelemetry(properties, pageIdentities, featuresIdentities, metrics);

            await TelemetryService.Current.TrackEventAsync(TelemetryEvents.NewItemGen, properties, metrics).ConfigureAwait(false);
        }