Example #1
0
 public void NotNull()
 {
     Assert.ThrowsAny <Exception>(() => Assumes.NotNull((object?)null));
     Assumes.NotNull("success");
 }
Example #2
0
        private ICollection <object> GetNormalizedCollection(Type itemType, object instance)
        {
            Assumes.NotNull(itemType);

            object collectionObject = null;

            if (this._member.CanRead)
            {
                try
                {
                    collectionObject = this._member.GetValue(instance);
                }
                catch (TargetInvocationException exception)
                {
                    throw new ComposablePartException(
                              CompositionErrorId.ReflectionModel_ImportCollectionGetThrewException,
                              String.Format(CultureInfo.CurrentCulture,
                                            Strings.ReflectionModel_ImportCollectionGetThrewException,
                                            this._member.GetDisplayName()),
                              this.Definition.ToElement(),
                              exception.InnerException);
                }
            }

            if (collectionObject == null)
            {
                ConstructorInfo constructor = this.ImportType.ActualType.GetConstructor(new Type[0]);

                // If it contains a default public constructor create a new instance.
                if (constructor != null)
                {
                    try
                    {
                        collectionObject = constructor.Invoke(new object[] { });
                    }
                    catch (TargetInvocationException exception)
                    {
                        throw new ComposablePartException(
                                  CompositionErrorId.ReflectionModel_ImportCollectionConstructionThrewException,
                                  String.Format(CultureInfo.CurrentCulture,
                                                Strings.ReflectionModel_ImportCollectionConstructionThrewException,
                                                this._member.GetDisplayName(),
                                                this.ImportType.ActualType.FullName),
                                  this.Definition.ToElement(),
                                  exception.InnerException);
                    }

                    SetSingleMemberValue(instance, collectionObject);
                }
            }

            if (collectionObject == null)
            {
                throw new ComposablePartException(
                          CompositionErrorId.ReflectionModel_ImportCollectionNull,
                          String.Format(CultureInfo.CurrentCulture,
                                        Strings.ReflectionModel_ImportCollectionNull,
                                        this._member.GetDisplayName()),
                          this.Definition.ToElement());
            }

            return(CollectionServices.GetCollectionWrapper(itemType, collectionObject));
        }
        public async ValueTask <IReadOnlyList <ProjectAction> > GetInstallActionsAsync(
            IReadOnlyCollection <string> projectIds,
            PackageIdentity packageIdentity,
            VersionConstraints versionConstraints,
            bool includePrelease,
            DependencyBehavior dependencyBehavior,
            IReadOnlyList <string> packageSourceNames,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectIds);
            Assumes.NotNull(packageIdentity);
            Assumes.NotNullOrEmpty(packageSourceNames);
            Assumes.Null(_state.PackageIdentity);
            Assumes.True(_state.ResolvedActions.Count == 0);
            Assumes.NotNull(_state.SourceCacheContext);

            cancellationToken.ThrowIfCancellationRequested();

            return(await CatchAndRethrowExceptionAsync(async() =>
            {
                _state.PackageIdentity = packageIdentity;

                IReadOnlyList <SourceRepository> sourceRepositories = GetSourceRepositories(
                    packageSourceNames,
                    cancellationToken);

                Assumes.NotNullOrEmpty(sourceRepositories);

                INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync <INuGetProjectContext>();
                IReadOnlyList <NuGetProject> projects = await GetProjectsAsync(projectIds, cancellationToken);

                var resolutionContext = new ResolutionContext(
                    dependencyBehavior,
                    includePrelease,
                    includeUnlisted: false,
                    versionConstraints,
                    new GatherCache(),
                    _state.SourceCacheContext);

                NuGetPackageManager packageManager = await _sharedState.GetPackageManagerAsync(cancellationToken);
                IEnumerable <ResolvedAction> resolvedActions = await packageManager.PreviewProjectsInstallPackageAsync(
                    projects,
                    _state.PackageIdentity,
                    resolutionContext,
                    projectContext,
                    sourceRepositories,
                    cancellationToken);

                var projectActions = new List <ProjectAction>();

                foreach (ResolvedAction resolvedAction in resolvedActions)
                {
                    ProjectAction projectAction = CreateProjectAction(resolvedAction);

                    _state.ResolvedActions[projectAction.Id] = resolvedAction;

                    projectActions.Add(projectAction);
                }

                return projectActions;
            }));
        }
Example #4
0
File: Pipe.cs Project: zredb/netmq
        /// <summary>
        /// Ask pipe to terminate. The termination will happen asynchronously
        /// and user will be notified about actual deallocation by 'terminated'
        /// event.
        /// </summary>
        /// <param name="delay">if set to <c>true</c>, the pending messages will be processed
        /// before actual shutdown. </param>
        public void Terminate(bool delay)
        {
            // Overload the value specified at pipe creation.
            m_delay = delay;

            // If terminate was already called, we can ignore the duplicate invocation.
            if (m_state == State.Terminated || m_state == State.DoubleTerminated)
            {
                return;
            }

            // If the pipe is in the phase of async termination, it's going to
            // closed anyway. No need to do anything special here.
            if (m_state == State.Terminating)
            {
                return;
            }

            if (m_state == State.Active)
            {
                // The simple sync termination case. Ask the peer to terminate and wait
                // for the ack.
                Assumes.NotNull(m_peer);
                SendPipeTerm(m_peer);
                m_state = State.Terminated;
            }
            else if (m_state == State.Pending && !m_delay)
            {
                // There are still pending messages available, but the user calls
                // 'terminate'. We can act as if all the pending messages were read.
                m_outboundPipe = null;
                Assumes.NotNull(m_peer);
                SendPipeTermAck(m_peer);
                m_state = State.Terminating;
            }
            else if (m_state == State.Pending)
            {
                // If there are pending messages still available, do nothing.
            }
            else if (m_state == State.Delimited)
            {
                // We've already got delimiter, but not term command yet. We can ignore
                // the delimiter and ack synchronously terminate as if we were in
                // active state.
                Assumes.NotNull(m_peer);
                SendPipeTerm(m_peer);
                m_state = State.Terminated;
            }
            else
            {
                // There are no other states.
                Debug.Assert(false);
            }

            // Stop outbound flow of messages.
            m_outActive = false;

            if (m_outboundPipe != null)
            {
                // Drop any unfinished outbound messages.
                Rollback();

                // Write the delimiter into the pipe. Note that watermarks are not
                // checked; thus the delimiter can be written even when the pipe is full.

                var msg = new Msg();
                msg.InitDelimiter();
                m_outboundPipe.Write(ref msg, false);
                Flush();
            }
        }
Example #5
0
 public static IEnumerable <T> WhereNotNull <T>(this IEnumerable <T> source) where T : class
 {
     Assumes.NotNull(source);
     return(source.Where(NotNull)); // Use non-generic NotNull for performance reasons
 }
Example #6
0
 private static CachingResult LoadFloat(ILGenerator ilGenerator, float value)
 {
     Assumes.NotNull(ilGenerator);
     ilGenerator.Emit(OpCodes.Ldc_R4, value);
     return CachingResult.SucceededResult;
 }
Example #7
0
 public GenerationServices(ModuleBuilder moduleBuilder)
 {
     Assumes.NotNull(moduleBuilder);
     this._standardDictionaryGenerators = GenerationServices.GetStandardDictionaryGenerators(moduleBuilder);
 }
        protected override async Task <bool> TryHandleCommandAsync(IProjectTree node, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
        {
            if (!ShouldHandle(node))
            {
                return(false);
            }

            if (await IsReadyToBuildAsync())
            {
                // Build manager APIs require UI thread access.
                await _threadingService.SwitchToUIThread();

                Assumes.NotNull(Project.Services.HostObject);

                // Save documents before build.
                var projectVsHierarchy = (IVsHierarchy)Project.Services.HostObject;
                ErrorHandler.ThrowOnFailure(_buildManager !.SaveDocumentsBeforeBuild(projectVsHierarchy, (uint)VSConstants.VSITEMID.Root, docCookie: 0));

                // We need to make sure dependencies are built so they can go into the package
                ErrorHandler.ThrowOnFailure(_buildManager.CalculateProjectDependencies());

                // Assembly our list of projects to build
                var projects = new List <IVsHierarchy>
                {
                    projectVsHierarchy
                };

                // First we find out how many dependent projects there are
                uint[] dependencyCounts = new uint[1];
                ErrorHandler.ThrowOnFailure(_buildManager.GetProjectDependencies(projectVsHierarchy, 0, null, dependencyCounts));

                if (dependencyCounts[0] > 0)
                {
                    // Get all of the dependent projects, and add them to our list
                    var projectsArray = new IVsHierarchy[dependencyCounts[0]];
                    ErrorHandler.ThrowOnFailure(_buildManager.GetProjectDependencies(projectVsHierarchy, dependencyCounts[0], projectsArray, dependencyCounts));
                    projects.AddRange(projectsArray);
                }

                // Turn off "GeneratePackageOnBuild" because otherwise the Pack target will not do a build, even if there is no built output
                _generatePackageOnBuildPropertyProvider.OverrideGeneratePackageOnBuild(false);

                uint dwFlags = (uint)(VSSOLNBUILDUPDATEFLAGS.SBF_SUPPRESS_SAVEBEFOREBUILD_QUERY | VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_BUILD);

                uint[] buildFlags = new uint[projects.Count];
                // We tell the Solution Build Manager to Package our project, which will call the Pack target, which will build if necessary.
                // Any dependent projects will just do a normal build
                buildFlags[0] = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_PACKAGE;

                ErrorHandler.ThrowOnFailure(_buildManager.StartUpdateSpecificProjectConfigurations(cProjs: (uint)projects.Count,
                                                                                                   rgpHier: projects.ToArray(),
                                                                                                   rgpcfg: null,
                                                                                                   rgdwCleanFlags: null,
                                                                                                   rgdwBuildFlags: buildFlags,
                                                                                                   rgdwDeployFlags: null,
                                                                                                   dwFlags: dwFlags,
                                                                                                   fSuppressUI: 0));
            }

            return(true);
        }
        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 = context.ServiceBroker;

                    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.UIContext.ServiceBroker,
                        uiService.Projects,
                        token);

                    upgradeInformationTelemetryEvent.SetResult(projectIds, status, packagesCount);
                }
            }
        }
        public static T GetValue <T>(this SerializationInfo info, string name)
        {
            Assumes.NotNull(info, name);

            return((T)info.GetValue(name, typeof(T)));
        }
Example #11
0
        public async Task UpgradeNuGetProjectAsync(INuGetUI uiService, IProjectContextInfo project)
        {
            Assumes.NotNull(uiService);
            Assumes.NotNull(project);

            INuGetUIContext context = uiService.UIContext;
            // Restore the project before proceeding
            string solutionDirectory = await context.SolutionManagerService.GetSolutionDirectoryAsync(CancellationToken.None);

            await context.PackageRestoreManager.RestoreMissingPackagesInSolutionAsync(
                solutionDirectory,
                uiService.ProjectContext,
                new LoggerAdapter(uiService.ProjectContext),
                CancellationToken.None);

            IServiceBroker serviceBroker = context.ServiceBroker;
            NuGetProjectUpgradeWindowModel upgradeInformationWindowModel;

            using (INuGetProjectManagerService projectManager = await serviceBroker.GetProxyAsync <INuGetProjectManagerService>(
                       NuGetServices.ProjectManagerService,
                       CancellationToken.None))
            {
                Assumes.NotNull(projectManager);

                IReadOnlyCollection <PackageDependencyInfo> packagesDependencyInfo = await projectManager.GetInstalledPackagesDependencyInfoAsync(
                    project.ProjectId,
                    includeUnresolved : true,
                    CancellationToken.None);

                upgradeInformationWindowModel = await NuGetProjectUpgradeWindowModel.CreateAsync(
                    serviceBroker,
                    project,
                    packagesDependencyInfo.ToList(),
                    CancellationToken.None);
            }

            var result = uiService.ShowNuGetUpgradeWindow(upgradeInformationWindowModel);

            if (!result)
            {
                // raise upgrade telemetry event with Cancelled status
                var packagesCount = upgradeInformationWindowModel.UpgradeDependencyItems.Count;

                var upgradeTelemetryEvent       = new UpgradeInformationTelemetryEvent();
                IEnumerable <string> projectIds = await ProjectUtility.GetSortedProjectIdsAsync(
                    uiService.UIContext.ServiceBroker,
                    uiService.Projects,
                    CancellationToken.None);

                upgradeTelemetryEvent.SetResult(
                    projectIds,
                    NuGetOperationStatus.Cancelled,
                    packagesCount);

                TelemetryActivity.EmitTelemetryEvent(upgradeTelemetryEvent);

                return;
            }

            var    progressDialogData = new ProgressDialogData(Resources.NuGetUpgrade_WaitMessage);
            string projectName        = await project.GetUniqueNameOrNameAsync(
                uiService.UIContext.ServiceBroker,
                CancellationToken.None);

            string backupPath;

            var windowTitle = string.Format(
                CultureInfo.CurrentCulture,
                Resources.WindowTitle_NuGetMigrator,
                projectName);

            using (IModalProgressDialogSession progressDialogSession = await context.StartModalProgressDialogAsync(windowTitle, progressDialogData, uiService))
            {
                backupPath = await PackagesConfigToPackageReferenceMigrator.DoUpgradeAsync(
                    context,
                    uiService,
                    project,
                    upgradeInformationWindowModel.UpgradeDependencyItems,
                    upgradeInformationWindowModel.NotFoundPackages,
                    progressDialogSession.Progress,
                    progressDialogSession.UserCancellationToken);
            }

            if (!string.IsNullOrEmpty(backupPath))
            {
                string htmlLogFile = GenerateUpgradeReport(projectName, backupPath, upgradeInformationWindowModel);

                Process process = null;
                try
                {
                    process = Process.Start(htmlLogFile);
                }
                catch { }
            }
        }
Example #12
0
            public void OnProjectBuildCompleted()
            {
                _project.Services.ThreadingPolicy.RunAndForget(
                    async() =>
                {
                    await TaskScheduler.Default;

                    await CheckAsync(_projectAsynchronousTasksService.UnloadCancellationToken);
                },
                    unconfiguredProject: _project);

                return;

                async Task CheckAsync(CancellationToken cancellationToken)
                {
                    var sw = Stopwatch.StartNew();

                    IBuildUpToDateCheckValidator validator = _upToDateCheckValidator.Value;

                    if (validator is IBuildUpToDateCheckProvider provider)
                    {
                        if (!await provider.IsUpToDateCheckEnabledAsync(cancellationToken))
                        {
                            // The fast up-to-date check has been disabled. We can't know the reason why.
                            // We currently do not flag errors in this case, so stop processing immediately.
                            return;
                        }
                    }

                    List <IIncrementalBuildFailureReporter>?reporters = await GetEnabledReportersAsync();

                    if (reporters is null)
                    {
                        // No reporter is enabled, so return immediately without checking anything
                        return;
                    }

                    (bool isUpToDate, string?failureReason) = await validator.ValidateUpToDateAsync(cancellationToken);

                    if (isUpToDate)
                    {
                        // The project is up-to-date, as expected. Nothing more to do.
                        return;
                    }

                    Assumes.NotNull(failureReason);

                    TimeSpan checkDuration = sw.Elapsed;

                    foreach (IIncrementalBuildFailureReporter reporter in reporters)
                    {
                        await reporter.ReportFailureAsync(failureReason, checkDuration, cancellationToken);
                    }

                    return;

                    async Task <List <IIncrementalBuildFailureReporter>?> GetEnabledReportersAsync()
                    {
                        List <IIncrementalBuildFailureReporter>?reporters = null;

                        foreach (IIncrementalBuildFailureReporter reporter in Reporters.ExtensionValues())
                        {
                            if (await reporter.IsEnabledAsync(cancellationToken))
                            {
                                reporters ??= new();
                                reporters.Add(reporter);
                            }
                        }

                        return(reporters);
                    }
                }
            }
        protected override IPackageReferenceContextInfo?DeserializeCore(ref MessagePackReader reader, MessagePackSerializerOptions options)
        {
            PackageIdentity?identity                = null;
            NuGetFramework? framework               = null;
            bool            isUserInstalled         = false;
            bool            isAutoReferenced        = false;
            bool            isDevelopmentDependency = false;
            string?         allowedVersions         = null;

            int propertyCount = reader.ReadMapHeader();

            for (int propertyIndex = 0; propertyIndex < propertyCount; propertyIndex++)
            {
                switch (reader.ReadString())
                {
                case IdentityPropertyName:
                    identity = PackageIdentityFormatter.Instance.Deserialize(ref reader, options);
                    break;

                case FrameworkPropertyName:
                    framework = NuGetFrameworkFormatter.Instance.Deserialize(ref reader, options);
                    break;

                case IsUserInstalledPropertyName:
                    isUserInstalled = reader.ReadBoolean();
                    break;

                case IsAutoReferencedPropertyName:
                    isAutoReferenced = reader.ReadBoolean();
                    break;

                case IsDevelopmentDependencyPropertyName:
                    isDevelopmentDependency = reader.ReadBoolean();
                    break;

                case AllowedVersionsPropertyName:
                    if (!reader.TryReadNil())     // Advances beyond the current value if the current value is nil and returns true; otherwise leaves the reader's position unchanged and returns false.
                    {
                        allowedVersions = reader.ReadString();
                    }
                    break;

                default:
                    reader.Skip();
                    break;
                }
            }

            Assumes.NotNull(identity);

            var packageReferenceContextInfo = new PackageReferenceContextInfo(identity, framework)
            {
                IsUserInstalled         = isUserInstalled,
                IsAutoReferenced        = isAutoReferenced,
                IsDevelopmentDependency = isDevelopmentDependency
            };

            if (!string.IsNullOrWhiteSpace(allowedVersions) && VersionRange.TryParse(allowedVersions, out VersionRange versionRange))
            {
                packageReferenceContextInfo.AllowedVersions = versionRange;
            }

            return(packageReferenceContextInfo);
        }
Example #14
0
        public ExportFactoryCreator(Type exportFactoryType)
        {
            Assumes.NotNull(exportFactoryType);

            this._exportFactoryType = exportFactoryType;
        }
Example #15
0
        private CachingResult LoadGenericDictionary<TKey, TValue>(ILGenerator ilGenerator, IDictionary<TKey, TValue> dictionary, bool isStandardDictionary)
        {
            Assumes.NotNull(ilGenerator);
            Assumes.NotNull(dictionary);

            CachingResult result = CachingResult.SucceededResult;
            Type keyType = GenerationServices.NormalizeCollectionElementType(typeof(TKey));
            Type valueType = GenerationServices.NormalizeCollectionElementType(typeof(TValue));

            Type dictionaryType = null;
            MethodInfo dictionaryAddMethod = null;
            ConstructorInfo dictionaryConstructor = null;
            if (isStandardDictionary)
            {
                dictionaryType = GenerationServices.standardDictionaryType;
                dictionaryAddMethod = GenerationServices.standardDictionaryAddMethod;
                dictionaryConstructor = dictionaryType.GetConstructor(new Type[] { Int32Type });
            }
            else
            {
                dictionaryType = GenerationServices.GenericDictionaryType.MakeGenericType(keyType, valueType);
                dictionaryAddMethod = dictionaryType.GetMethod("Add", new Type[] { keyType, valueType });
                dictionaryConstructor = dictionaryType.GetConstructor(new Type[] { Int32Type });
            }

            //
            // Dictionary<TKey, TValue> metadata = new Dictionary<TKey, TValue>(capacity)
            //

            // create and load the dictionary
            GenerationServices.LoadInt(ilGenerator, dictionary.Count);
            ilGenerator.Emit(OpCodes.Newobj, dictionaryConstructor);


            // 
            // Generate a sequence of "Add" statements
            //
            
            foreach (KeyValuePair<TKey, TValue> dictionaryItem in dictionary)
            {
                //
                // metadata.Add(key, value)
                //

                // the dictionary is on top of the stack - load it again
                ilGenerator.Emit(OpCodes.Dup);
               

                // load the key, boxing if necessary
                result = result.MergeResult(this.LoadValue(ilGenerator, dictionaryItem.Key));
                // key = string for standard dictionaries, so no boxing is ever required
                if (!isStandardDictionary && GenerationServices.IsBoxingRequiredForValue(dictionaryItem.Key) && !keyType.IsValueType)
                {
                    ilGenerator.Emit(OpCodes.Box, dictionaryItem.Key.GetType());
                }

                // load the value, boxing if necessary
                result = result.MergeResult(this.LoadValue(ilGenerator, dictionaryItem.Value));
                // key = object for standard dictionaries, so value type is never a struct
                if (GenerationServices.IsBoxingRequiredForValue(dictionaryItem.Value) && (isStandardDictionary || !valueType.IsValueType) )
                {
                    ilGenerator.Emit(OpCodes.Box, dictionaryItem.Value.GetType());
                }

                // Caal the "Add"
                ilGenerator.EmitCall(OpCodes.Call, dictionaryAddMethod, null);

                // At this point the dictionary, key and value have been popped off the stack, and we ended up with the origical state of the dictionary on top of the stack
            }

            // 
            // the dicationary is already loaded on the stack - exit
            //
            return result;

        }
Example #16
0
        public static async ValueTask <NuGetUIContext> CreateAsync(
            IServiceBroker serviceBroker,
            ISourceRepositoryProvider sourceRepositoryProvider,
            ISettings settings,
            IVsSolutionManager solutionManager,
            IPackageRestoreManager packageRestoreManager,
            IOptionsPageActivator optionsPageActivator,
            IUserSettingsManager userSettingsManager,
            IDeleteOnRestartManager deleteOnRestartManager,
            IEnumerable <IVsPackageManagerProvider> packageManagerProviders,
            INuGetLockService lockService,
            CancellationToken cancellationToken)
        {
            Assumes.NotNull(serviceBroker);
            Assumes.NotNull(sourceRepositoryProvider);
            Assumes.NotNull(settings);
            Assumes.NotNull(solutionManager);
            Assumes.NotNull(packageRestoreManager);
            Assumes.NotNull(optionsPageActivator);
            Assumes.NotNull(userSettingsManager);
            Assumes.NotNull(deleteOnRestartManager);
            Assumes.NotNull(packageManagerProviders);
            Assumes.NotNull(lockService);

            cancellationToken.ThrowIfCancellationRequested();

            var solutionManagerServiceWrapper = new NuGetSolutionManagerServiceWrapper();
            INuGetSolutionManagerService solutionManagerService = await GetSolutionManagerServiceAsync(serviceBroker, cancellationToken);

            // The initial Swap(...) should return a null implementation of the interface that does not require disposal.
            // However, there's no harm in following form.
            using (solutionManagerServiceWrapper.Swap(solutionManagerService))
            {
            }

            var sourceServiceWrapper           = new NuGetSourcesServiceWrapper();
            INuGetSourcesService sourceService = await GetSourceServiceAsync(serviceBroker, cancellationToken);

            using (sourceServiceWrapper.Swap(sourceService))
            {
            }

#pragma warning disable CA2000 // Dispose objects before losing scope - NuGetUIContext owns the instance and should dispose it.
            var searchService = await NuGetSearchServiceReconnector.CreateAsync(serviceBroker, NuGetUIThreadHelper.JoinableTaskFactory, cancellationToken);

#pragma warning restore CA2000 // Dispose objects before losing scope

            var packageManager = new NuGetPackageManager(
                sourceRepositoryProvider,
                settings,
                solutionManager,
                deleteOnRestartManager);

            var actionEngine = new UIActionEngine(
                sourceRepositoryProvider,
                packageManager,
                lockService);

            return(new NuGetUIContext(
                       serviceBroker,
                       searchService.Object,
                       solutionManager,
                       solutionManagerServiceWrapper,
                       packageManager,
                       actionEngine,
                       packageRestoreManager,
                       optionsPageActivator,
                       userSettingsManager,
                       packageManagerProviders,
                       sourceServiceWrapper));
        }
Example #17
0
 private static CachingResult LoadLong(ILGenerator ilGenerator, long value)
 {
     Assumes.NotNull(ilGenerator);
     ilGenerator.Emit(OpCodes.Ldc_I8, value);
     return CachingResult.SucceededResult;
 }
Example #18
0
 public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo)
 {
     Assumes.NotNull(creationInfo);
     this._creationInfo = creationInfo;
 }
Example #19
0
 private static CachingResult LoadDouble(ILGenerator ilGenerator, double value)
 {
     Assumes.NotNull(ilGenerator);
     ilGenerator.Emit(OpCodes.Ldc_R8, value);
     return CachingResult.SucceededResult;
 }
Example #20
0
        public ProjectAction?Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
        {
            if (reader.TryReadNil())
            {
                return(null);
            }

            // stack overflow mitigation - see https://github.com/neuecc/MessagePack-CSharp/security/advisories/GHSA-7q36-4xx7-xcxf
            options.Security.DepthStep(ref reader);

            try
            {
                string?id = null;
                ImplicitProjectAction[]? implicitActions = null;
                PackageIdentity?       packageIdentity   = null;
                NuGetProjectActionType?projectActionType = null;
                string?projectId = null;

                int propertyCount = reader.ReadMapHeader();

                for (var propertyIndex = 0; propertyIndex < propertyCount; ++propertyIndex)
                {
                    switch (reader.ReadString())
                    {
                    case IdPropertyName:
                        id = reader.ReadString();
                        break;

                    case ImplicitActionsPropertyName:
                        int elementCount = reader.ReadArrayHeader();
                        implicitActions = new ImplicitProjectAction[elementCount];

                        for (var i = 0; i < elementCount; ++i)
                        {
                            ImplicitProjectAction?implicitAction = ImplicitProjectActionFormatter.Instance.Deserialize(ref reader, options);

                            Assumes.NotNull(implicitAction);

                            implicitActions[i] = implicitAction;
                        }
                        break;

                    case PackageIdentityPropertyName:
                        packageIdentity = PackageIdentityFormatter.Instance.Deserialize(ref reader, options);
                        break;

                    case ProjectActionTypePropertyName:
                        projectActionType = options.Resolver.GetFormatter <NuGetProjectActionType>().Deserialize(ref reader, options);
                        break;

                    case ProjectIdPropertyName:
                        projectId = reader.ReadString();
                        break;

                    default:
                        reader.Skip();
                        break;
                    }
                }

                Assumes.NotNullOrEmpty(id);
                Assumes.NotNull(packageIdentity);
                Assumes.True(projectActionType.HasValue);
                Assumes.NotNullOrEmpty(projectId);

                return(new ProjectAction(id, projectId, packageIdentity, projectActionType.Value, implicitActions));
            }
            finally
            {
                // stack overflow mitigation - see https://github.com/neuecc/MessagePack-CSharp/security/advisories/GHSA-7q36-4xx7-xcxf
                reader.Depth--;
            }
        }
Example #21
0
        /// Generates the code that loads the supplied value on the stack
        /// This is not as simple as it seems, as different instructions need to be generated depending
        /// on its type.
        /// We support:
        /// 1. All primitive types and IntPtrs
        /// 2. Strings
        /// 3. Enums
        /// 4. typeofs
        /// 5. nulls
        /// 6. Dictionaries of (string, object) recursively containing all of the above
        /// 7. Enumerables
        /// Everything else cannot be represented as literals
        /// <param name="ilGenerator"></param>
        /// <param name="item"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        internal CachingResult LoadValue(ILGenerator ilGenerator, object value)
        {
            Assumes.NotNull(ilGenerator);
            CachingResult result = CachingResult.SucceededResult;

            //
            // Get nulls out of the way - they are basically typeless, so we just load null
            //
            if (value == null)
            {
                return GenerationServices.LoadNull(ilGenerator);
            }

            //
            // Prepare for literal loading - decide whether we should box, and handle enums properly
            //
            Type valueType = value.GetType();
            object rawValue = value;
            if (valueType.IsEnum)
            {
                // enums are special - we need to load the underlying constant on the stack
                rawValue = Convert.ChangeType(value, Enum.GetUnderlyingType(valueType), null);
                valueType = rawValue.GetType();
            }

            //
            // Generate IL depending on the valueType - this is messier than it should ever be, but sadly necessary
            //
            Type dictionaryKeyType;
            Type dictionaryValueType;
            IDictionary<string, object> standardDictionary = value as IDictionary<string, object>;
            if (standardDictionary != null)
            {
                if (standardDictionary.Count < GenerationServices.StandardDictionaryGeneratorsCount)
                {
                    return this.LoadStandardDictionaryFast(ilGenerator, standardDictionary);
                }
                else
                {
                    return this.LoadGenericDictionary(ilGenerator, standardDictionary, true);
                }
            }
            else if (GenerationServices.TryGetDictionaryElementType(valueType, out dictionaryKeyType, out dictionaryValueType))
            {
                result = result.MergeResult(this.LoadDictionary(ilGenerator, rawValue, dictionaryKeyType, dictionaryValueType));
            }
            else if (valueType == GenerationServices.StringType)
            {
                // we need to check for strings before enumerables, because strings are IEnumerable<char>
                result = result.MergeResult(GenerationServices.LoadString(ilGenerator,(string)rawValue));
            }
            else if (GenerationServices.TypeType.IsAssignableFrom(valueType))
            {
                result = result.MergeResult(GenerationServices.LoadTypeOf(ilGenerator, (Type)rawValue));
            }
            else if (GenerationServices.IEnumerableType.IsAssignableFrom(valueType))
            {
                // NOTE : strings and dictionaries are also enumerables, but we have already handled those
                result = result.MergeResult(this.LoadEnumerable(ilGenerator, (IEnumerable) rawValue));
            }
            else if (
                (valueType == GenerationServices.CharType) ||
                (valueType == GenerationServices.BooleanType) ||
                (valueType == GenerationServices.ByteType) ||
                (valueType == GenerationServices.SByteType) ||
                (valueType == GenerationServices.Int16Type) ||
                (valueType == GenerationServices.UInt16Type) ||
                (valueType == GenerationServices.Int32Type)
                )
            {
                // NOTE : Everything that is 32 bit or less uses ldc.i4. We need to pass int32, even if the actual types is shorter - this is IL memory model
                // direct casting to (int) won't work, because the value is boxed, thus we need to use Convert.
                // Sadly, this will not work for all cases - namely large uint32 - because they can't semantically fit into 32 signed bits
                // We have a special case for that next
                result = result.MergeResult(GenerationServices.LoadInt(ilGenerator, (int)Convert.ChangeType(rawValue, typeof(int), CultureInfo.InvariantCulture)));
            }
            else if (valueType == GenerationServices.UInt32Type)
            {
                // NOTE : This one is a bit tricky. Ldc.I4 takes an Int32 as an argument, although it really treats it as a 32bit number
                // That said, some UInt32 values are larger that Int32.MaxValue, so the Convert call above will fail, which is why 
                // we need to treat this case individually and cast to uint, and then - unchecked - to int.
                result = result.MergeResult(GenerationServices.LoadInt(ilGenerator, unchecked((int)((uint)rawValue))));
            }
            else if (valueType == GenerationServices.Int64Type)
            {
                result = result.MergeResult(GenerationServices.LoadLong(ilGenerator, (long)rawValue));
            }
            else if (valueType == GenerationServices.UInt64Type)
            {
                // NOTE : This one is a bit tricky. Ldc.I8 takes an Int64 as an argument, although it really treats it as a 64bit number
                // That said, some UInt64 values are larger that Int64.MaxValue, so the direct case we use above (or Convert, for that matter)will fail, which is why
                // we need to treat this case individually and cast to ulong, and then - unchecked - to long.
                result = result.MergeResult(GenerationServices.LoadLong(ilGenerator, unchecked((long)((ulong)rawValue))));
            }
            else if (valueType == GenerationServices.SingleType)
            {
                result = result.MergeResult(GenerationServices.LoadFloat(ilGenerator, (float)rawValue));
            }
            else if (valueType == GenerationServices.DoubleType)
            {
                result = result.MergeResult(GenerationServices.LoadDouble(ilGenerator, (double)rawValue));
            }
            else
            {
                result = result.MergeError(Strings.UnsupportedCacheValue, value.GetType().FullName);

                // Make sure the IL is balanced - generate the ldnull instead
                GenerationServices.LoadNull(ilGenerator);
            }

            return result;
        }
Example #22
0
 public IProjectTree Remove()
 {
     Assumes.NotNull(Parent);
     return(Parent.Remove(this));
 }
Example #23
0
        public static ReadOnlyCollection <T> ToReadOnlyCollection <T>(this IEnumerable <T> source)
        {
            Assumes.NotNull(source);

            return(new ReadOnlyCollection <T>(source.AsArray()));
        }
Example #24
0
        public ReflectionParameter(ParameterInfo parameter)
        {
            Assumes.NotNull(parameter);

            _parameter = parameter;
        }
Example #25
0
 /// <summary>
 /// Register the pipe with this socket.
 /// </summary>
 /// <param name="pipe">the Pipe to attach</param>
 /// <param name="icanhasall">not used</param>
 protected override void XAttachPipe(Pipe pipe, bool icanhasall)
 {
     Assumes.NotNull(pipe);
     m_fairQueueing.Attach(pipe);
 }
        protected AbstractSpecialFolderProjectTreePropertiesProvider(IProjectImageProvider imageProvider)
        {
            Assumes.NotNull(imageProvider);

            _imageProvider = imageProvider;
        }
            public SingleExportComposablePart(Export export)
            {
                Assumes.NotNull(export);

                _export = export;
            }
 public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition)
 {
     Assumes.NotNull(sourceDefinition);
     this._sourceDefinition = sourceDefinition;
     this._metadata         = null;
 }
        public async ValueTask <IReadOnlyList <ProjectAction> > GetUpdateActionsAsync(
            IReadOnlyCollection <string> projectIds,
            IReadOnlyCollection <PackageIdentity> packageIdentities,
            VersionConstraints versionConstraints,
            bool includePrelease,
            DependencyBehavior dependencyBehavior,
            IReadOnlyList <string> packageSourceNames,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectIds);
            Assumes.NotNullOrEmpty(packageIdentities);
            Assumes.NotNullOrEmpty(packageSourceNames);
            Assumes.NotNull(_state.SourceCacheContext);
            Assumes.NotNull(_state.ResolvedActions);
            Assumes.Null(_state.PackageIdentity);

            return(await CatchAndRethrowExceptionAsync(async() =>
            {
                var primarySources = new List <SourceRepository>();
                var secondarySources = new List <SourceRepository>();

                IEnumerable <SourceRepository> sourceRepositories = _sharedState.SourceRepositoryProvider.GetRepositories();
                var packageSourceNamesSet = new HashSet <string>(packageSourceNames, StringComparer.OrdinalIgnoreCase);

                foreach (SourceRepository sourceRepository in sourceRepositories)
                {
                    if (packageSourceNamesSet.Contains(sourceRepository.PackageSource.Name))
                    {
                        primarySources.Add(sourceRepository);
                    }

                    if (sourceRepository.PackageSource.IsEnabled)
                    {
                        secondarySources.Add(sourceRepository);
                    }
                }

                INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync <INuGetProjectContext>();
                IReadOnlyList <NuGetProject> projects = await GetProjectsAsync(projectIds, cancellationToken);

                var resolutionContext = new ResolutionContext(
                    dependencyBehavior,
                    includePrelease,
                    includeUnlisted: true,
                    versionConstraints,
                    new GatherCache(),
                    _state.SourceCacheContext);

                NuGetPackageManager packageManager = await _sharedState.GetPackageManagerAsync(cancellationToken);
                IEnumerable <NuGetProjectAction> actions = await packageManager.PreviewUpdatePackagesAsync(
                    packageIdentities.ToList(),
                    projects,
                    resolutionContext,
                    projectContext,
                    primarySources,
                    secondarySources,
                    cancellationToken);

                var projectActions = new List <ProjectAction>();

                foreach (NuGetProjectAction action in actions)
                {
                    var resolvedAction = new ResolvedAction(action.Project, action);
                    ProjectAction projectAction = CreateProjectAction(resolvedAction);

                    _state.ResolvedActions[projectAction.Id] = resolvedAction;

                    projectActions.Add(projectAction);
                }

                return projectActions;
            }));
        }
        /// <summary>
        /// This is where the information entered in the form should be saved in CPS
        /// </summary>
        public int Apply()
        {
            Assumes.NotNull(_threadHandling);

            return(_threadHandling.ExecuteSynchronously(OnApply));
        }