public void Dispose_WithIndependentInterval_DoesNotClashWithNonoverlappingInterval() { const string independentInterval = "independentTestInterval"; const string nonOverlappingInterval = "nonOverlappingInterval"; using (var telemetry = TelemetryActivity.Create(CreateNewTelemetryEvent())) { telemetry.StartIntervalMeasure(); Thread.Sleep(1000); using (telemetry.StartIndependentInterval(independentInterval)) { Thread.Sleep(1000); } telemetry.EndIntervalMeasure(nonOverlappingInterval); } var independentIntervalValue = _telemetryEvent[independentInterval]; independentIntervalValue.Should().NotBeNull(); int independentActualCount = Convert.ToInt32(independentIntervalValue); Assert.True(independentActualCount >= 1, $"The telemetry duration count should at least be 1 seconds."); var overlappingIntervalValue = _telemetryEvent[nonOverlappingInterval]; overlappingIntervalValue.Should().NotBeNull(); int actualCount = Convert.ToInt32(overlappingIntervalValue); Assert.True(actualCount >= 2, $"The telemetry duration count should at least be 2 seconds."); }
public void Dispose_will_dispose_activity() { using (var telemetry = TelemetryActivity.Create(CreateNewTelemetryEvent())) { } Assert.True(_activityDisposed); }
public void Create_will_start_activity() { using (var telemetry = TelemetryActivity.Create(CreateNewTelemetryEvent())) { } Assert.Equal("testEvent", _activityName); }
public void Dispose_WithEmptyParentId_EmitsNoParentId() { var parentId = Guid.Empty; using (var telemetry = TelemetryActivity.Create(parentId, CreateNewTelemetryEvent())) { } Assert.Null(_telemetryEvent["ParentId"]); }
public void Dispose_Always_EmitsDuration() { using (var telemetry = TelemetryActivity.Create(CreateNewTelemetryEvent())) { Thread.Sleep(10); } var duration = (double)_telemetryEvent["Duration"]; Assert.InRange(duration, 0d, 10d); }
public void Dispose_WithOperationIdAndWithoutParentId_EmitsOperationIdAndNotParentId() { Guid operationId; using (var telemetry = TelemetryActivity.Create(CreateNewTelemetryEvent())) { operationId = telemetry.OperationId; } Assert.Null(_telemetryEvent["ParentId"]); Assert.Equal(operationId.ToString(), _telemetryEvent["OperationId"]); }
public void Dispose_Always_EmitsEndTime() { using (var telemetry = TelemetryActivity.Create(CreateNewTelemetryEvent())) { } var endTime = _telemetryEvent["EndTime"] as string; Assert.NotNull(endTime); TelemetryUtility.VerifyDateTimeFormat(endTime); }
public void Dispose_WithOperationIdAndParentId_EmitsOperationIdAndParentId() { var parentId = Guid.NewGuid(); Guid operationId; using (var telemetry = TelemetryActivity.Create(parentId, CreateNewTelemetryEvent())) { operationId = telemetry.OperationId; } Assert.Equal(parentId.ToString(), _telemetryEvent["ParentId"]); Assert.Equal(operationId.ToString(), _telemetryEvent["OperationId"]); }
public void Dispose_WithIntervalMeasure_EmitsIntervalMeasure() { const string measureName = "testInterval"; var secondsToWait = 1; using (var telemetry = TelemetryActivity.Create(CreateNewTelemetryEvent())) { telemetry.StartIntervalMeasure(); Thread.Sleep(secondsToWait * 1000); telemetry.EndIntervalMeasure(measureName); } var value = _telemetryEvent[measureName]; value.Should().NotBeNull(); var actualCount = Convert.ToInt32(value); Assert.True(actualCount >= secondsToWait, $"The telemetry duration count should at least be {secondsToWait} seconds."); }
public async Task WalkDependenciesAsync_WithCancellationToken_ThrowsAsync() { using (var pathContext = new SimpleTestPathContext()) { var projectName = "TestProject"; var projectDirectory = Path.Combine(pathContext.SolutionRoot, projectName); var packageSpec = PackageReferenceSpecBuilder.Create(projectName, projectDirectory) .WithTargetFrameworks(new string[] { "net46", "net47" }) .WithPackagesLockFile() .Build(); var restoreRequest = ProjectTestHelpers.CreateRestoreRequest(packageSpec, pathContext, _logger); var projectRestoreRequest = new ProjectRestoreRequest(restoreRequest, packageSpec, restoreRequest.ExistingLockFile, _collector);; var cmd = new ProjectRestoreCommand(projectRestoreRequest); // Assert exception var ex = await Assert.ThrowsAnyAsync <OperationCanceledException>(async() => { var cts = new CancellationTokenSource(); cts.Cancel(); // Act: call TryRestoreAsync() that calls WalkDependenciesAsync() await cmd.TryRestoreAsync( projectRange: It.IsAny <LibraryRange>(), frameworkRuntimePairs: new FrameworkRuntimePair[] { new FrameworkRuntimePair(NuGetFramework.Parse("net46"), null), new FrameworkRuntimePair(NuGetFramework.Parse("net47"), null), }, userPackageFolder: It.IsAny <NuGetv3LocalRepository>(), fallbackPackageFolders: It.IsAny <IReadOnlyList <NuGetv3LocalRepository> >(), remoteWalker: It.IsAny <RemoteDependencyWalker>(), context: It.IsAny <RemoteWalkContext>(), forceRuntimeGraphCreation: false, token: cts.Token, telemetryActivity: TelemetryActivity.Create(Guid.NewGuid(), "TestTelemetry"), telemetryPrefix: "testTelemetryPrefix"); }); } }
public async Task <VerifySignaturesResult> VerifySignaturesAsync(ISignedPackageReader package, SignedPackageVerifierSettings settings, CancellationToken token, Guid parentId = default(Guid)) { if (package == null) { throw new ArgumentNullException(nameof(package)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var valid = false; var trustResults = new List <PackageVerificationResult>(); var packageSigningTelemetryEvent = new PackageSigningTelemetryEvent(); using (var telemetry = TelemetryActivity.Create(parentId, packageSigningTelemetryEvent)) { var isSigned = await package.IsSignedAsync(token); if (isSigned) { try { var signature = await package.GetPrimarySignatureAsync(token); if (signature != null) { // Verify that the signature is trusted var sigTrustResults = await Task.WhenAll(_verificationProviders.Select(e => e.GetTrustResultAsync(package, signature, settings, token))); valid = IsValid(sigTrustResults); trustResults.AddRange(sigTrustResults); } else { valid = false; } } catch (SignatureException e) { // SignatureException generated while parsing signatures var issues = new[] { SignatureLog.Issue(!settings.AllowIllegal, e.Code, e.Message), SignatureLog.DebugLog(e.ToString()) }; trustResults.Add(new InvalidSignaturePackageVerificationResult( settings.AllowIllegal ? SignatureVerificationStatus.Valid : SignatureVerificationStatus.Disallowed, issues)); valid = settings.AllowIllegal; } catch (CryptographicException e) { // CryptographicException generated while parsing the SignedCms object var issues = new[] { SignatureLog.Issue(!settings.AllowIllegal, NuGetLogCode.NU3003, Strings.ErrorPackageSignatureInvalid), SignatureLog.DebugLog(e.ToString()) }; trustResults.Add(new InvalidSignaturePackageVerificationResult( settings.AllowIllegal ? SignatureVerificationStatus.Valid : SignatureVerificationStatus.Disallowed, issues)); valid = settings.AllowIllegal; } } else if (settings.AllowUnsigned) { // An unsigned package is valid only if unsigned packages are allowed. valid = true; } else { var issues = new[] { SignatureLog.Issue(fatal: true, code: NuGetLogCode.NU3004, message: Strings.ErrorPackageNotSigned) }; trustResults.Add(new UnsignedPackageVerificationResult( settings.AllowIllegal ? SignatureVerificationStatus.Valid : SignatureVerificationStatus.Disallowed, issues)); valid = false; } var status = valid ? NuGetOperationStatus.Succeeded : NuGetOperationStatus.Failed; packageSigningTelemetryEvent.SetResult(isSigned ? PackageSignType.Signed : PackageSignType.Unsigned, status); return(new VerifySignaturesResult(valid, isSigned, trustResults)); } }
internal static async Task <string> DoUpgradeAsync( INuGetUIContext context, INuGetUI uiService, IProjectContextInfo project, IEnumerable <NuGetProjectUpgradeDependencyItem> upgradeDependencyItems, IEnumerable <PackageIdentity> notFoundPackages, IProgress <ProgressDialogData> progress, CancellationToken token) { var startTime = DateTimeOffset.Now; var packagesCount = 0; var status = NuGetOperationStatus.Succeeded; var upgradeInformationTelemetryEvent = new UpgradeInformationTelemetryEvent(); using (var telemetry = TelemetryActivity.Create(upgradeInformationTelemetryEvent)) { try { // 0. Fail if any package was not found if (notFoundPackages.Any()) { status = NuGetOperationStatus.Failed; var notFoundPackageIds = string.Join(",", notFoundPackages.Select(t => t.Id)); uiService.ProjectContext.Log(MessageLevel.Error, string.Format(CultureInfo.CurrentCulture, Resources.Migrator_PackageNotFound, notFoundPackageIds)); return(null); } IServiceBroker serviceBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync(); using (INuGetProjectUpgraderService projectUpgrader = await serviceBroker.GetProxyAsync <INuGetProjectUpgraderService>( NuGetServices.ProjectUpgraderService, token)) { Assumes.NotNull(projectUpgrader); string backupPath; // 1. Backup files (csproj and packages.config) that will change try { backupPath = await projectUpgrader.BackupProjectAsync(project.ProjectId, token); } catch (Exception ex) { status = NuGetOperationStatus.Failed; uiService.ShowError(ex); uiService.ProjectContext.Log( MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Upgrader_BackupFailed)); return(null); } // 2. Uninstall all packages currently in packages.config var progressData = new ProgressDialogData(Resources.NuGetUpgrade_WaitMessage, Resources.NuGetUpgrade_Progress_Uninstalling); progress.Report(progressData); // Don't uninstall packages we couldn't find - that will just fail PackageIdentity[] packagesToUninstall = upgradeDependencyItems.Select(d => d.Identity) .Where(p => !notFoundPackages.Contains(p)) .ToArray(); try { await projectUpgrader.UninstallPackagesAsync(project.ProjectId, packagesToUninstall, token); } catch (Exception ex) { status = NuGetOperationStatus.Failed; // log error message uiService.ShowError(ex); uiService.ProjectContext.Log(MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_UninstallFailed)); return(null); } // Reload the project, and get a reference to the reloaded project await projectUpgrader.SaveProjectAsync(project.ProjectId, token); IProjectContextInfo upgradedProject = await projectUpgrader.UpgradeProjectToPackageReferenceAsync( project.ProjectId, token); // Ensure we use the updated project for installing, and don't display preview or license acceptance windows. context.Projects = new[] { upgradedProject }; var nuGetUI = (NuGetUI)uiService; nuGetUI.Projects = new[] { upgradedProject }; nuGetUI.DisplayPreviewWindow = false; // 4. Install the requested packages var ideExecutionContext = uiService.ProjectContext.ExecutionContext as IDEExecutionContext; if (ideExecutionContext != null) { await ideExecutionContext.SaveExpandedNodeStates(context.SolutionManager); } progressData = new ProgressDialogData(Resources.NuGetUpgrade_WaitMessage, Resources.NuGetUpgrade_Progress_Installing); progress.Report(progressData); List <PackageIdentity> packagesToInstall = GetPackagesToInstall(upgradeDependencyItems).ToList(); packagesCount = packagesToInstall.Count; try { await projectUpgrader.InstallPackagesAsync( project.ProjectId, packagesToInstall, token); if (ideExecutionContext != null) { await ideExecutionContext.CollapseAllNodes(context.SolutionManager); } return(backupPath); } catch (Exception ex) { status = NuGetOperationStatus.Failed; uiService.ShowError(ex); uiService.ProjectContext.Log(MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_InstallFailed, backupPath)); uiService.ProjectContext.Log(MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_RevertSteps, "https://aka.ms/nugetupgraderevertv1")); return(null); } } } catch (Exception ex) { status = NuGetOperationStatus.Failed; uiService.ShowError(ex); return(null); } finally { IEnumerable <string> projectIds = await ProjectUtility.GetSortedProjectIdsAsync(uiService.Projects, token); upgradeInformationTelemetryEvent.SetResult(projectIds, status, packagesCount); } } }
internal static async Task <string> DoUpgradeAsync( INuGetUIContext context, INuGetUI uiService, NuGetProject nuGetProject, IEnumerable <NuGetProjectUpgradeDependencyItem> upgradeDependencyItems, IEnumerable <PackageIdentity> notFoundPackages, IProgress <ProgressDialogData> progress, CancellationToken token) { var startTime = DateTimeOffset.Now; var packagesCount = 0; var status = NuGetOperationStatus.Succeeded; var upgradeInformationTelemetryEvent = new UpgradeInformationTelemetryEvent(); using (var telemetry = TelemetryActivity.Create(upgradeInformationTelemetryEvent)) { try { // 0. Fail if any package was not found if (notFoundPackages.Any()) { status = NuGetOperationStatus.Failed; var notFoundPackageIds = string.Join(",", notFoundPackages.Select(t => t.Id)); uiService.ProjectContext.Log(MessageLevel.Error, string.Format(CultureInfo.CurrentCulture, Resources.Migrator_PackageNotFound, notFoundPackageIds)); return(null); } // 1. Backup files (csproj and packages.config) that will change var solutionManager = context.SolutionManager; var msBuildNuGetProject = (MSBuildNuGetProject)nuGetProject; var msBuildNuGetProjectSystem = msBuildNuGetProject.ProjectSystem; var backupPath = string.Empty; try { backupPath = CreateBackup(msBuildNuGetProject, solutionManager.SolutionDirectory); } catch (Exception ex) { status = NuGetOperationStatus.Failed; // log error message uiService.ShowError(ex); uiService.ProjectContext.Log(MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Upgrader_BackupFailed)); return(null); } // 2. Uninstall all packages currently in packages.config var progressData = new ProgressDialogData(Resources.NuGetUpgrade_WaitMessage, Resources.NuGetUpgrade_Progress_Uninstalling); progress.Report(progressData); // Don't uninstall packages we couldn't find - that will just fail var actions = upgradeDependencyItems.Select(d => d.Identity) .Where(p => !notFoundPackages.Contains(p)) .Select(t => NuGetProjectAction.CreateUninstallProjectAction(t, nuGetProject)); try { await context.PackageManager.ExecuteNuGetProjectActionsAsync(nuGetProject, actions, uiService.ProjectContext, NullSourceCacheContext.Instance, CancellationToken.None); } catch (Exception ex) { status = NuGetOperationStatus.Failed; // log error message uiService.ShowError(ex); uiService.ProjectContext.Log(MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_UninstallFailed)); return(null); } // Reload the project, and get a reference to the reloaded project var uniqueName = msBuildNuGetProjectSystem.ProjectUniqueName; await msBuildNuGetProject.SaveAsync(token); nuGetProject = await solutionManager.GetNuGetProjectAsync(uniqueName); nuGetProject = await solutionManager.UpgradeProjectToPackageReferenceAsync(nuGetProject); // Ensure we use the updated project for installing, and don't display preview or license acceptance windows. context.Projects = new[] { nuGetProject }; var nuGetUI = (NuGetUI)uiService; nuGetUI.Projects = new[] { nuGetProject }; nuGetUI.DisplayPreviewWindow = false; // 4. Install the requested packages var ideExecutionContext = uiService.ProjectContext.ExecutionContext as IDEExecutionContext; if (ideExecutionContext != null) { await ideExecutionContext.SaveExpandedNodeStates(solutionManager); } progressData = new ProgressDialogData(Resources.NuGetUpgrade_WaitMessage, Resources.NuGetUpgrade_Progress_Installing); progress.Report(progressData); var activeSources = new List <SourceRepository>(); PackageSourceMoniker .PopulateList(context.SourceProvider) .ForEach(s => activeSources.AddRange(s.SourceRepositories)); var packagesToInstall = GetPackagesToInstall(upgradeDependencyItems).ToList(); packagesCount = packagesToInstall.Count; // create low level NuGet actions based on number of packages being installed var lowLevelActions = new List <NuGetProjectAction>(); foreach (var packageIdentity in packagesToInstall) { lowLevelActions.Add(NuGetProjectAction.CreateInstallProjectAction(packageIdentity, activeSources.FirstOrDefault(), nuGetProject)); } try { var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; await context.PackageManager.ExecuteBuildIntegratedProjectActionsAsync( buildIntegratedProject, lowLevelActions, uiService.ProjectContext, token); if (ideExecutionContext != null) { await ideExecutionContext.CollapseAllNodes(solutionManager); } return(backupPath); } catch (Exception ex) { status = NuGetOperationStatus.Failed; uiService.ShowError(ex); uiService.ProjectContext.Log(MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_InstallFailed, backupPath)); uiService.ProjectContext.Log(MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_RevertSteps, "https://aka.ms/nugetupgraderevertv1")); return(null); } } catch (Exception ex) { status = NuGetOperationStatus.Failed; uiService.ShowError(ex); return(null); } finally { upgradeInformationTelemetryEvent.SetResult(uiService.Projects, status, packagesCount); } } }