public override void OnExecute(CommandEventArgs e)
        {
            GitPushArgs args = new GitPushArgs();

            string repositoryRoot;
            var repositoryRoots = new HashSet<string>(FileSystemUtil.StringComparer);

            foreach (var projectRoot in GetAllRoots(e))
            {
                if (
                    GitTools.TryGetRepositoryRoot(projectRoot.FullPath, out repositoryRoot) &&
                    !repositoryRoots.Contains(repositoryRoot)
                )
                    repositoryRoots.Add(repositoryRoot);
            }

            if (repositoryRoots.Count > 1)
            {
                throw new InvalidOperationException("Pushing of multiple repository roots is not supported");
            }

            repositoryRoot = repositoryRoots.Single();

            switch (e.Command)
            {
                case VisualGitCommand.PendingChangesPushSpecificBranch:
                case VisualGitCommand.PendingChangesPushSpecificTag:
                    if (!QueryParameters(e, repositoryRoot, args))
                        return;
                    break;
            }

            ProgressRunnerArgs pa = new ProgressRunnerArgs();
            pa.CreateLog = true;
            pa.TransportClientArgs = args;

            GitException exception = null;

            e.GetService<IProgressRunner>().RunModal(CommandStrings.PushingSolution, pa,
                delegate(object sender, ProgressWorkerArgs a)
                {
                    using (var client = e.GetService<IGitClientPool>().GetNoUIClient())
                    {
                        try
                        {
                            client.Push(repositoryRoot, args);
                        }
                        catch (GitException ex)
                        {
                            exception = ex;
                        }
                    }
                });

            if (exception != null)
            {
                e.GetService<IVisualGitErrorHandler>().OnWarning(exception);
            }
        }
Example #2
0
 /// <summary>
 /// Get node collection from dataGridView
 /// </summary>
 /// <returns>HashSet of nodes</returns>
 public HashSet<Node> GetNodes()
 {
     HashSet<Node> Nodes = new HashSet<Node>();
     // Enlist all nodes
     for (int row = 0; row < dataTable.Rows.Count; row++)
         Nodes.Add(new Node((string)dataTable.Rows[row][0], (int)dataTable.Rows[row][1]));
     // Create dependencies
     for (int row = 0; row < dataTable.Rows.Count; row++)
         if (dataTable.Rows[row][2] != null)
             foreach (string dependency in dataTable.Rows[row][2].ToString().Split(separators, StringSplitOptions.RemoveEmptyEntries))
                 Nodes.ElementAt(row).Dependencies.Add(Nodes.Single(new Func<Node, bool>(delegate(Node node)
                 {
                     return node.ID == dependency;
                 })));
     return Nodes;
 }
        /// <summary>
        /// Take a Dictionary of pins and write it to an XML file
        /// </summary>
        /// <param name="pinMap">A Dictionary of frame X and Y rotations to a list of pins on that frame</param>
        /// <param name="outfile">The file to write the formatted XML to</param>
        public void Pack(Dictionary<Tuple<int, int>, List<Pin>> pinMap, string outfile)
        {
            List<FrameData> frames = new List<FrameData>();

            HashSet<DissectionPinData> pins = new HashSet<DissectionPinData>();
            int nextId = 0;

            foreach (var pair in pinMap)
            {
                List<Pin> framePins = pair.Value;                                   // All the pins on this frame
                Tuple<int, int> frame = pair.Key;                                   // The 2D rotation of this frame

                FrameData frameData = new FrameData();                              // Data for the frame to be represented in XML
                frameData.Rotation = new Vector3(frame.Item1, frame.Item2, 0.0f);

                List<FramePinData> framePinDatas = new List<FramePinData>();        // The links between this frame and its pins

                foreach (Pin pin in framePins)
                {
                    DissectionPinData data = ConvertToData(pin);
                    if (pins.Add(data))
                    {
                        // This pin doesn't already exist, so give it an id
                        data.Id = nextId++;
                    }
                    else
                    {
                        // This pin is in the HashSet so get the original instance
                        data = pins.Single((DissectionPinData x) => { return x.Equals(data); });
                    }

                    framePinDatas.Add(new FramePinData(new Vector2(pin.X, pin.Y), data.Id));
                }

                frameData.Pins = framePinDatas.ToArray();
                frames.Add(frameData);
            }

            PinContainer container = new PinContainer();
            container.Frames = frames.ToArray();
            container.Pins = pins.ToArray();

            WriteXml(container, outfile);
        }
        private double CalculateRPNValue(Stack<string> RPNStack, IEnumerable<SolvedCalculatorParameter> parameters)
        {
            var resultStack = new Stack<double>();

            var parameterSet = new HashSet<SolvedCalculatorParameter>(parameters);

            while (RPNStack.Count > 0) {
                var val = RPNStack.Pop();

                if (IsNumber(val)) {
                    resultStack.Push(double.Parse(val.Replace('.', ',')));
                } else if (parameterSet.Any(x => x.Name == val)) {
                    var paramVal = parameterSet.Single(x => x.Name == val);
                    resultStack.Push(paramVal.Value);
                } else {
                    var op = this.OperatorFactory.GetOperatorByCode(val);

                    if (resultStack.Count < op.ParameterCount) {
                        throw new CalculatorException(string.Format("Not enough parameters for function {0}", op.Name));
                    }

                    var operatorParams = new List<double>();

                    for (int i = 0; i < op.ParameterCount; i++) {
                        operatorParams.Add(resultStack.Pop());
                    }

                    operatorParams.Reverse();

                    var operationResult = op.DoOperation(operatorParams);

                    resultStack.Push(operationResult);
                }
            }

            if (resultStack.Count > 1) {
                throw new CalculatorException("The equation has too many values");
            }

            return resultStack.Pop();
        }
		void UpdateCompilerComboBox()
		{
			if (listView.SelectedItems.Count > 0) {
				// Fetch list of available compiler versions
				HashSet<CompilerVersion> availableVersionsSet = new HashSet<CompilerVersion>();
				HashSet<CompilerVersion> currentVersions = new HashSet<CompilerVersion>();
				foreach (Entry entry in listView.SelectedItems) {
					if (entry.CompilerVersion != null)
						currentVersions.Add(entry.CompilerVersion);
					availableVersionsSet.AddRange(entry.Project.GetAvailableCompilerVersions());
				}
				List<CompilerVersion> availableVersions = availableVersionsSet.OrderBy(n => n.MSBuildVersion).ThenBy(n => n.DisplayName).ToList();
				if (currentVersions.Count != 1) {
					availableVersions.Insert(0, new UnchangedCompilerVersion());
				}
				// Assign available versions to newVersionComboBox
				// Unless the user has already chosen a version, automatically set the selection to the
				// current version of the chosen projects, or to 'do not change' if there are different
				// current versions.
				newCompilerSelectionChangingByCode = true;
				newVersionComboBox.ItemsSource = availableVersions;
				
				CompilerVersion oldSelectedVersion = newVersionComboBox.SelectedValue as CompilerVersion;
				if (!newCompilerSelectionSetByUser || oldSelectedVersion == null) {
					newCompilerSelectionSetByUser = false;
					if (currentVersions.Count == 1)
						newVersionComboBox.SelectedValue = currentVersions.Single();
					else
						newVersionComboBox.SelectedValue = new UnchangedCompilerVersion();
				}
				newCompilerSelectionChangingByCode = false;
				UpdateTargetFrameworkComboBox();
			}
		}
Example #6
0
        private void btnDeleteCommander_Click(object sender, EventArgs e)
        {
            var cells = dataGridViewCommanders.SelectedCells;

            HashSet<int> rowindexes = new HashSet<int>();

            foreach (var cell in cells.OfType<DataGridViewCell>())
            {
                if (!rowindexes.Contains(cell.RowIndex))
                {
                    rowindexes.Add(cell.RowIndex);
                }
            }

            if (rowindexes.Count == 1)
            {
                var row = dataGridViewCommanders.Rows[rowindexes.Single()].DataBoundItem as EDCommander;
                var result = MessageBox.Show("Do you wish to delete commander " + row.Name + "?", "Delete commander", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.Yes)
                {
                    EDDConfig.Instance.DeleteCommander(row);
                    _discoveryForm.TravelControl.LoadCommandersListBox();
                    UpdateCommandersListBox();
                    _discoveryForm.RefreshHistoryAsync();           // will do a new parse on commander list adding/removing scanners
                }
            }
        }
Example #7
0
			public CimInstanceRegularFilter(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
			{
				HashSet<BehaviorOnNoMatch> behaviorOnNoMatches = new HashSet<BehaviorOnNoMatch>();
				foreach (object allowedPropertyValue in allowedPropertyValues)
				{
					ClientSideQuery.PropertyValueFilter propertyValueRegularFilter = new ClientSideQuery.PropertyValueRegularFilter(propertyName, allowedPropertyValue, wildcardsEnabled, behaviorOnNoMatch);
					base.AddPropertyValueFilter(propertyValueRegularFilter);
					behaviorOnNoMatches.Add(propertyValueRegularFilter.BehaviorOnNoMatch);
				}
				if (behaviorOnNoMatches.Count != 1)
				{
					base.BehaviorOnNoMatch = behaviorOnNoMatch;
					return;
				}
				else
				{
					base.BehaviorOnNoMatch = behaviorOnNoMatches.Single<BehaviorOnNoMatch>();
					return;
				}
			}
Example #8
0
            public CimInstanceRegularFilter(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
            {
                var valueBehaviors = new HashSet<BehaviorOnNoMatch>();

                foreach (object allowedPropertyValue in allowedPropertyValues)
                {
                    PropertyValueFilter filter =
                        new PropertyValueRegularFilter(
                            propertyName,
                            allowedPropertyValue,
                            wildcardsEnabled,
                            behaviorOnNoMatch);
                    this.AddPropertyValueFilter(filter);

                    valueBehaviors.Add(filter.BehaviorOnNoMatch);
                }

                if (valueBehaviors.Count == 1)
                {
                    this.BehaviorOnNoMatch = valueBehaviors.Single();
                }
                else
                {
                    this.BehaviorOnNoMatch = behaviorOnNoMatch;
                }
            }
        private void UpdateSeverityMenuItemsChecked()
        {
            _setSeverityErrorMenuItem.Checked = false;
            _setSeverityWarningMenuItem.Checked = false;
            _setSeverityInfoMenuItem.Checked = false;
            _setSeverityHiddenMenuItem.Checked = false;
            _setSeverityNoneMenuItem.Checked = false;

            var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl;
            if (workspace == null)
            {
                return;
            }

            HashSet<ReportDiagnostic> selectedItemSeverities = new HashSet<ReportDiagnostic>();

            var groups = _tracker.SelectedDiagnosticItems.GroupBy(item => item.AnalyzerItem.AnalyzersFolder.ProjectId);

            foreach (var group in groups)
            {
                var project = (AbstractProject)workspace.GetHostProject(group.Key);
                IRuleSetFile ruleSet = project.RuleSetFile;

                if (ruleSet != null)
                {
                    var specificOptions = ruleSet.GetSpecificDiagnosticOptions();

                    foreach (var diagnosticItem in group)
                    {
                        ReportDiagnostic ruleSetSeverity;
                        if (specificOptions.TryGetValue(diagnosticItem.Descriptor.Id, out ruleSetSeverity))
                        {
                            selectedItemSeverities.Add(ruleSetSeverity);
                        }
                        else
                        {
                            // The rule has no setting.
                            selectedItemSeverities.Add(ReportDiagnostic.Default);
                        }
                    }
                }
            }
            
            if (selectedItemSeverities.Count != 1)
            {
                return;
            }

            switch (selectedItemSeverities.Single())
            {
                case ReportDiagnostic.Default:
                    break;
                case ReportDiagnostic.Error:
                    _setSeverityErrorMenuItem.Checked = true;
                    break;
                case ReportDiagnostic.Warn:
                    _setSeverityWarningMenuItem.Checked = true;
                    break;
                case ReportDiagnostic.Info:
                    _setSeverityInfoMenuItem.Checked = true;
                    break;
                case ReportDiagnostic.Hidden:
                    _setSeverityHiddenMenuItem.Checked = true;
                    break;
                case ReportDiagnostic.Suppress:
                    _setSeverityNoneMenuItem.Checked = true;
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// Determines whether the given query view matches the discriminator map pattern.
        /// </summary>
        internal static bool TryCreateDiscriminatorMap(EntitySet entitySet, DbExpression queryView, out DiscriminatorMap discriminatorMap)
        {
            discriminatorMap = null;

            if (queryView.ExpressionKind != DbExpressionKind.Project) { return false; }
            var project = (DbProjectExpression)queryView;

            if (project.Projection.ExpressionKind != DbExpressionKind.Case) { return false; }
            var caseExpression = (DbCaseExpression)project.Projection;
            if (project.Projection.ResultType.EdmType.BuiltInTypeKind != BuiltInTypeKind.EntityType) { return false; }

            // determine value domain by walking filter
            if (project.Input.Expression.ExpressionKind != DbExpressionKind.Filter) { return false; }
            var filterExpression = (DbFilterExpression)project.Input.Expression;

            HashSet<object> discriminatorDomain = new HashSet<object>();
            if (!ViewSimplifier.TryMatchDiscriminatorPredicate(filterExpression, (equalsExp, discriminatorValue) => discriminatorDomain.Add(discriminatorValue)))
            {
                return false;
            }
                        
            var typeMap = new List<KeyValuePair<object, EntityType>>();
            var propertyMap = new Dictionary<EdmProperty, DbExpression>();
            var relPropertyMap = new Dictionary<Query.InternalTrees.RelProperty, DbExpression>();
            var typeToRelPropertyMap = new Dictionary<EntityType, List<Query.InternalTrees.RelProperty>>();
            DbPropertyExpression discriminator = null;

            EdmProperty discriminatorProperty = null;
            for (int i = 0; i < caseExpression.When.Count; i++)
            {
                var when = caseExpression.When[i];
                var then = caseExpression.Then[i];

                var projectionVariableName = project.Input.VariableName;

                DbPropertyExpression currentDiscriminator;
                object discriminatorValue;
                if (!ViewSimplifier.TryMatchPropertyEqualsValue(when, projectionVariableName, out currentDiscriminator, out discriminatorValue)) { return false; }

                // must be the same discriminator in every case
                if (null == discriminatorProperty) { discriminatorProperty = (EdmProperty)currentDiscriminator.Property; }
                else if (discriminatorProperty != currentDiscriminator.Property) { return false; }
                discriminator = currentDiscriminator;

                // right hand side must be entity type constructor
                EntityType currentType;
                if (!TryMatchEntityTypeConstructor(then, propertyMap, relPropertyMap, typeToRelPropertyMap, out currentType)) { return false; }

                // remember type + discriminator value
                typeMap.Add(new KeyValuePair<object, EntityType>(discriminatorValue, currentType));

                // remove discriminator value from domain
                discriminatorDomain.Remove(discriminatorValue);
            }

            // make sure only one member of discriminator domain remains...
            if (1 != discriminatorDomain.Count) { return false; }

            // check default case
            EntityType elseType;
            if (null == caseExpression.Else ||
                !TryMatchEntityTypeConstructor(caseExpression.Else, propertyMap, relPropertyMap, typeToRelPropertyMap, out elseType)) { return false; }
            typeMap.Add(new KeyValuePair<object, EntityType>(discriminatorDomain.Single(), elseType));

            // Account for cases where some type in the hierarchy specifies a rel-property, but another
            // type in the hierarchy does not
            if (!CheckForMissingRelProperties(relPropertyMap, typeToRelPropertyMap))
            {
                return false;
            }

            // since the store may right-pad strings, ensure discriminator values are unique in their trimmed
            // form
            var discriminatorValues = typeMap.Select(map => map.Key);
            int uniqueValueCount = discriminatorValues.Distinct(TrailingSpaceComparer.Instance).Count();
            int valueCount = typeMap.Count;
            if (uniqueValueCount != valueCount) { return false; }

            discriminatorMap = new DiscriminatorMap(discriminator, typeMap, propertyMap, relPropertyMap, entitySet);
            return true;
        }
Example #11
0
        public override void OnExecute(CommandEventArgs e)
        {
            GitPullArgs args = new GitPullArgs();

            string repositoryRoot;
            var repositoryRoots = new HashSet<string>(FileSystemUtil.StringComparer);

            foreach (var projectRoot in GetAllRoots(e))
            {
                if (
                    GitTools.TryGetRepositoryRoot(projectRoot.FullPath, out repositoryRoot) &&
                    !repositoryRoots.Contains(repositoryRoot)
                )
                    repositoryRoots.Add(repositoryRoot);
            }

            if (repositoryRoots.Count > 1)
            {
                throw new InvalidOperationException("Pulling of multiple repository roots is not supported");
            }

            repositoryRoot = repositoryRoots.Single();

            if (e.Command == VisualGitCommand.PendingChangesPullEx)
            {
                if (!QueryParameters(e, repositoryRoot, args))
                    return;
            }
            else
            {
                args.MergeStrategy = GitMergeStrategy.DefaultForBranch;
            }

            GitPullResult result = null;

            ProgressRunnerArgs pa = new ProgressRunnerArgs();
            pa.CreateLog = true;
            pa.TransportClientArgs = args;

            // Get a list of all documents below the specified paths that are open in editors inside VS
            HybridCollection<string> lockPaths = new HybridCollection<string>(StringComparer.OrdinalIgnoreCase);
            IVisualGitOpenDocumentTracker documentTracker = e.GetService<IVisualGitOpenDocumentTracker>();

            foreach (string file in documentTracker.GetDocumentsBelow(repositoryRoot))
            {
                if (!lockPaths.Contains(file))
                    lockPaths.Add(file);
            }

            documentTracker.SaveDocuments(lockPaths); // Make sure all files are saved before merging!

            using (DocumentLock lck = documentTracker.LockDocuments(lockPaths, DocumentLockType.NoReload))
            using (lck.MonitorChangesForReload())
            {
                GitException exception = null;

                e.GetService<IProgressRunner>().RunModal(CommandStrings.PullingSolution, pa,
                    delegate(object sender, ProgressWorkerArgs a)
                    {
                        e.GetService<IConflictHandler>().RegisterConflictHandler(args, a.Synchronizer);

                        try
                        {
                            a.Client.Pull(repositoryRoot, args, out result);
                        }
                        catch (GitException ex)
                        {
                            exception = ex;
                        }
                    });

                if (exception != null)
                {
                    e.GetService<IVisualGitErrorHandler>().OnWarning(exception);
                }
            }
        }
Example #12
0
        public List<Account> GetUserList(string searchString)
        {
            Require.NotEmpty(searchString, nameof(searchString));

            var allProjectMemberships = _projectMembershipRepostiory.GetAllProjectMemberships().ToList();

            var allUsers = new HashSet<Account>(_userRepository.GetAllAccounts());

            var allUsersToSearchByRole =
                new HashSet<Account>(
                    allProjectMemberships.Select(membership => allUsers.Single(account => account.UserId == membership.DeveloperId)));

            var userRolesDictionary = allUsersToSearchByRole.ToDictionary(user => user,
                user =>
                    allProjectMemberships.Where(membership => membership.DeveloperId == user.UserId)
                        .Select(that => that.Role));

            return userRolesDictionary.Where(
                pair =>
                    pair.Value.Any(role => Extensions.Contains(role, searchString)))
                .Select(pair => pair.Key)
                .Union(
                    allUsers.Where(
                        account =>
                            Extensions.Contains($"{account.Firstname} {account.Lastname}",
                                searchString))).ToList();
        }
        public void HashSetExtensions_Single_ThrowsExceptionIfHashSetHasMultipleItems()
        {
            var set = new HashSet<Int32>() { 1, 2 };

            set.Single();
        }
        public void HashSetExtensions_Single_ThrowsExceptionIfHashSetIsEmpty()
        {
            var set = new HashSet<Int32>();

            set.Single();
        }
Example #15
0
        private void btnDeleteCommander_Click(object sender, EventArgs e)
        {
            var cells = dataGridViewCommanders.SelectedCells;

            HashSet<int> rowindexes = new HashSet<int>();

            foreach (var cell in cells.OfType<DataGridViewCell>())
            {
                if (!rowindexes.Contains(cell.RowIndex))
                {
                    rowindexes.Add(cell.RowIndex);
                }
            }

            if (rowindexes.Count == 1)
            {
                var row = dataGridViewCommanders.Rows[rowindexes.Single()].DataBoundItem as EDCommander;
                var result = MessageBox.Show("Do you wish to delete commander " + row.Name + "?", "Delete commander", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.Yes)
                {
                    EDDConfig.Instance.DeleteCommander(row);
                    //dataGridViewCommanders.DataSource = null;           // changing data source ends up, after this, screwing the column sizing..
                    dataGridViewCommanders.DataSource = EDDConfig.Instance.listCommanders;   // can't solve it, TBD
                    dataGridViewCommanders.Update();
                    _discoveryForm.TravelControl.LoadCommandersListBox();

                }
            }
        }
        private bool ApplySuppressionFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog)
        {
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap = null;
            ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap = null;

            var title = isAddSuppression ? ServicesVSResources.SuppressMultipleOccurrences : ServicesVSResources.RemoveSuppressMultipleOccurrences;
            var waitDialogMessage = isAddSuppression ? ServicesVSResources.ComputingSuppressionFix : ServicesVSResources.ComputingRemoveSuppressionFix;

            // Get the diagnostics to fix from the suppression state service.
            Action<CancellationToken> computeDiagnosticsToFix = cancellationToken =>
            {
                var diagnosticsToFix = _suppressionStateService.GetItemsAsync(
                                selectedEntriesOnly,
                                isAddSuppression,
                                isSuppressionInSource,
                                onlyCompilerDiagnostics,
                                cancellationToken)
                            .WaitAndGetResult(cancellationToken);

                if (diagnosticsToFix.IsEmpty)
                {
                    return;
                }

                cancellationToken.ThrowIfCancellationRequested();
                documentDiagnosticsToFixMap = GetDocumentDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, cancellationToken).WaitAndGetResult(cancellationToken);

                cancellationToken.ThrowIfCancellationRequested();
                projectDiagnosticsToFixMap = isSuppressionInSource ?
                    ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty :
                    GetProjectDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, cancellationToken).WaitAndGetResult(cancellationToken);
            };

            var result = InvokeWithWaitDialog(computeDiagnosticsToFix, title, waitDialogMessage);

            // Bail out if the user cancelled.
            if (result == WaitIndicatorResult.Canceled ||
                documentDiagnosticsToFixMap == null ||
                projectDiagnosticsToFixMap == null)
            {
                return false;
            }

            if (documentDiagnosticsToFixMap.IsEmpty && projectDiagnosticsToFixMap.IsEmpty)
            {
                // Nothing to fix.
                return true;
            }

            // Equivalence key determines what fix will be applied.
            // Make sure we don't include any specific diagnostic ID, as we want all of the given diagnostics (which can have varied ID) to be fixed.
            var equivalenceKey = isAddSuppression ?
                (isSuppressionInSource ? FeaturesResources.SuppressWithPragma : FeaturesResources.SuppressWithGlobalSuppressMessage) :
                FeaturesResources.RemoveSuppressionEquivalenceKeyPrefix;

            // We have different suppression fixers for every language.
            // So we need to group diagnostics by the containing project language and apply fixes separately.
            var languages = new HashSet<string>(projectDiagnosticsToFixMap.Keys.Select(p => p.Language).Concat(documentDiagnosticsToFixMap.Select(kvp => kvp.Key.Project.Language)));
            var newSolution = _workspace.CurrentSolution;

            foreach (var language in languages)
            {
                // Use the Fix multiple occurrences service to compute a bulk suppression fix for the specified document and project diagnostics,
                // show a preview changes dialog and then apply the fix to the workspace.

                var documentDiagnosticsPerLanguage = GetDocumentDiagnosticsMappedToNewSolution(documentDiagnosticsToFixMap, newSolution, language);
                if (!documentDiagnosticsPerLanguage.IsEmpty)
                {
                    var suppressionFixer = GetSuppressionFixer(documentDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
                    if (suppressionFixer != null)
                    {
                        var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
                        newSolution = _fixMultipleOccurencesService.GetFix(
                            documentDiagnosticsPerLanguage,
                            _workspace,
                            suppressionFixer,
                            suppressionFixAllProvider,
                            equivalenceKey,
                            title,
                            waitDialogMessage,
                            cancellationToken: CancellationToken.None);
                        if (newSolution == null)
                        {
                            // User cancelled or fixer threw an exception, so we just bail out.
                            return false;
                        }
                    }
                }

                var projectDiagnosticsPerLanguage = GetProjectDiagnosticsMappedToNewSolution(projectDiagnosticsToFixMap, newSolution, language);
                if (!projectDiagnosticsPerLanguage.IsEmpty)
                {
                    var suppressionFixer = GetSuppressionFixer(projectDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
                    if (suppressionFixer != null)
                    {
                        var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
                        newSolution = _fixMultipleOccurencesService.GetFix(
                             projectDiagnosticsPerLanguage,
                             _workspace,
                             suppressionFixer,
                             suppressionFixAllProvider,
                             equivalenceKey,
                             title,
                             waitDialogMessage,
                             CancellationToken.None);
                        if (newSolution == null)
                        {
                            // User cancelled or fixer threw an exception, so we just bail out.
                            return false;
                        }
                    }
                }
            }

            if (showPreviewChangesDialog)
            {
                newSolution = FixAllGetFixesService.PreviewChanges(
                    _workspace.CurrentSolution,
                    newSolution,
                    fixAllPreviewChangesTitle: title,
                    fixAllTopLevelHeader: title,
                    languageOpt: languages.Count == 1 ? languages.Single() : null,
                    workspace: _workspace);
                if (newSolution == null)
                {
                    return false;
                }
            }

            waitDialogMessage = isAddSuppression ? ServicesVSResources.ApplyingSuppressionFix : ServicesVSResources.ApplyingRemoveSuppressionFix;
            Action<CancellationToken> applyFix = cancellationToken =>
            {
                var operations = SpecializedCollections.SingletonEnumerable<CodeActionOperation>(new ApplyChangesOperation(newSolution));
                _editHandlerService.Apply(
                    _workspace,
                    fromDocument: null,
                    operations: operations,
                    title: title,
                    cancellationToken: cancellationToken);
            };

            result = InvokeWithWaitDialog(applyFix, title, waitDialogMessage);
            return result == WaitIndicatorResult.Completed;
        }
        public void HashSetExtensions_Single_ReturnsSingleItemInHashSet()
        {
            var set = new HashSet<Int32>() { 4 };

            var result = set.Single();

            TheResultingValue(result).ShouldBe(4);
        }
Example #18
0
        private int lua_RequestStatic(string path, Type typ, string methodname)
        {
            MethodInfo[] allmethods = typ.GetMethods(BindingFlags.Static | BindingFlags.Public);
            HashSet<MethodInfo> candidates = new HashSet<MethodInfo>();
            foreach (MethodInfo method in allmethods)
            {
                if (method.Name == methodname)
                    candidates.Add(method);
            }

            if (candidates.Count == 0)
            {
                Logger.Error(string.Format("Failed to locate static method {0} on type {1}!", methodname, typ));
                return 0;
            }
            else
                if (candidates.Count == 1)
                {
                    lua.RegisterFunction(path, null, candidates.Single());
                    return 1;
                }
                else
                {
                    // Lets filter out any methods that use generic, in or out params
                    var filtered = candidates.Where((x) =>
                    {
                        if (x.IsGenericMethod || x.ContainsGenericParameters) return false;
                        foreach (ParameterInfo pinfo in x.GetParameters())
                        {
                            if (!pinfo.IsRetval)
                            {
                                if (pinfo.IsOut) return false;
                                if (pinfo.IsIn) return false;
                            }
                        }
                        return true;
                    }).ToArray();
                    if (filtered.Length == 1)
                    {
                        lua.RegisterFunction(path, null, filtered[0]);
                        return 1;
                    }
                    else
                    {
                        //LogError(string.Format("Failed to locate suitable static method {0} on type {1}! (there were {2} candidates)", methodname, typ, filtered.Length));
                        /*for (int i = 0; i < filtered.Length; i++)
                            lua[path + "_Overload" + i.ToString()] = filtered[i];*/
                        lua[path] = filtered;
                        return filtered.Length;
                    }
                }
        }
        public void HashSetExtensions_Single_ThrowsExceptionIfHashSetHasMultipleItems()
        {
            var set = new HashSet<Int32>() { 1, 2 };

            Assert.That(() => set.Single(),
                Throws.TypeOf<InvalidOperationException>());
        }
Example #20
0
            private static NotSupportedException InvalidCompiledQueryParameterException(Expression expression)
            {
                ParameterExpression parameterExp;
                if (expression.NodeType == ExpressionType.Parameter)
                {
                    parameterExp = (ParameterExpression)expression;
                }
                else
                {
                    // If this is a simple query parameter (involving a single delegate parameter) report the
                    // type of that parameter. Otherwise, report the type of the part of the parameter.
                    HashSet<ParameterExpression> parameters = new HashSet<ParameterExpression>();
                    EntityExpressionVisitor.Visit(expression, (exp, baseVisit) =>
                    {
                        if (null != exp && exp.NodeType == ExpressionType.Parameter)
                        {
                            parameters.Add((ParameterExpression)exp);
                        }
                        return baseVisit(exp);
                    });

                    if (parameters.Count != 1)
                    {
                        return EntityUtil.NotSupported(Strings.CompiledELinq_UnsupportedParameterTypes(expression.Type.FullName));
                    }
                    
                    parameterExp = parameters.Single();
                }

                if (parameterExp.Type.Equals(expression.Type))
                {
                    // If the expression type is the same as the parameter type, indicate that the parameter type is not valid.
                    return EntityUtil.NotSupported(Strings.CompiledELinq_UnsupportedNamedParameterType(parameterExp.Name, parameterExp.Type.FullName));                    
                }
                else
                {
                    // Otherwise, indicate that using the specified parameter to produce a value of the expression's type is not supported in compiled query
                    return EntityUtil.NotSupported(Strings.CompiledELinq_UnsupportedNamedParameterUseAsType(parameterExp.Name, expression.Type.FullName));
                }
            }
        public void HashSetExtensions_Single_ThrowsExceptionIfHashSetIsEmpty()
        {
            var set = new HashSet<Int32>();

            Assert.That(() => set.Single(),
                Throws.TypeOf<InvalidOperationException>());
        }