提交 2b914e70 编写于 作者: C Cyrus Najmabadi

Use switch expression

上级 8df9f27a
......@@ -98,35 +98,34 @@ IEnumerable<ActiveStatementDebugInfo> Enumerate()
var exportProvider = exportProviderFactory.CreateExportProvider();
using (var workspace = TestWorkspace.CreateCSharp(
using var workspace = TestWorkspace.CreateCSharp(
ActiveStatementsDescription.ClearTags(markedSource),
exportProvider: exportProvider))
exportProvider: exportProvider);
var baseSolution = workspace.CurrentSolution;
if (adjustSolution != null)
{
var baseSolution = workspace.CurrentSolution;
if (adjustSolution != null)
{
baseSolution = adjustSolution(baseSolution);
}
baseSolution = adjustSolution(baseSolution);
}
var docsIds = from p in baseSolution.Projects
from d in p.DocumentIds
select d;
var docsIds = from p in baseSolution.Projects
from d in p.DocumentIds
select d;
var debuggingSession = new DebuggingSession(baseSolution);
var activeStatementProvider = new TestActiveStatementProvider(activeStatements);
var debuggingSession = new DebuggingSession(baseSolution);
var activeStatementProvider = new TestActiveStatementProvider(activeStatements);
var editSession = new EditSession(
baseSolution,
debuggingSession,
activeStatementProvider,
ImmutableDictionary<ProjectId, ProjectReadOnlyReason>.Empty,
nonRemappableRegions ?? ImmutableDictionary<ActiveMethodId, ImmutableArray<NonRemappableRegion>>.Empty,
stoppedAtException: false);
var editSession = new EditSession(
baseSolution,
debuggingSession,
activeStatementProvider,
ImmutableDictionary<ProjectId, ProjectReadOnlyReason>.Empty,
nonRemappableRegions ?? ImmutableDictionary<ActiveMethodId, ImmutableArray<NonRemappableRegion>>.Empty,
stoppedAtException: false);
return (await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false),
await editSession.BaseActiveExceptionRegions.GetValueAsync(CancellationToken.None).ConfigureAwait(false),
docsIds.ToImmutableArray());
}
return (await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false),
await editSession.BaseActiveExceptionRegions.GetValueAsync(CancellationToken.None).ConfigureAwait(false),
docsIds.ToImmutableArray());
}
private static string Delete(string src, string marker)
......
......@@ -351,15 +351,14 @@ internal void ApplyConflictResolutionEdits(IInlineRenameReplacementInfo conflict
_session.UndoManager.CreateConflictResolutionUndoTransaction(_subjectBuffer, () =>
{
using (var edit = _subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, s_propagateSpansEditTag))
{
foreach (var change in changes)
{
edit.Replace(change.Span.Start, change.Span.Length, change.NewText);
}
using var edit = _subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, s_propagateSpansEditTag);
edit.ApplyAndLogExceptions();
foreach (var change in changes)
{
edit.Replace(change.Span.Start, change.Span.Length, change.NewText);
}
edit.ApplyAndLogExceptions();
});
// 2. We want to update referenceSpanToLinkedRenameSpanMap where spans were affected by conflict resolution.
......
......@@ -55,12 +55,11 @@ public void CreateStartRenameUndoTransaction(ITextBuffer subjectBuffer)
var undoHistory = this.UndoManagers[subjectBuffer].TextUndoHistory;
// Create an undo transaction to mark the starting point of the rename session in this buffer
using (var undoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.Start_Rename))
{
undoTransaction.Complete();
this.UndoManagers[subjectBuffer].StartRenameSessionUndoTransaction = undoTransaction;
this.UndoManagers[subjectBuffer].ConflictResolutionUndoTransaction = null;
}
using var undoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.Start_Rename);
undoTransaction.Complete();
this.UndoManagers[subjectBuffer].StartRenameSessionUndoTransaction = undoTransaction;
this.UndoManagers[subjectBuffer].ConflictResolutionUndoTransaction = null;
}
public void CreateConflictResolutionUndoTransaction(ITextBuffer subjectBuffer, Action applyEdit)
......@@ -123,10 +122,8 @@ public void ApplyCurrentState(ITextBuffer subjectBuffer, object propagateSpansEd
var undoHistory = this.UndoManagers[subjectBuffer].TextUndoHistory;
foreach (var state in this.RedoStack.Reverse())
{
using (var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(state.ReplacementText)))
{
transaction.Complete();
}
using var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(state.ReplacementText));
transaction.Complete();
}
if (this.RedoStack.Any())
......
......@@ -560,33 +560,32 @@ private async Task<XElement> TryDownloadFileAsync(IRemoteControlClient client)
// "ReturnsNull": Only return a file if we have it locally *and* it's not older than our polling time (1 day).
using (var stream = await client.ReadFileAsync(BehaviorOnStale.ReturnNull).ConfigureAwait(false))
using var stream = await client.ReadFileAsync(BehaviorOnStale.ReturnNull).ConfigureAwait(false);
if (stream == null)
{
if (stream == null)
{
await _service.LogInfoAsync("Read file completed. Client returned no data").ConfigureAwait(false);
return null;
}
await _service.LogInfoAsync("Read file completed. Client returned no data").ConfigureAwait(false);
return null;
}
await _service.LogInfoAsync("Read file completed. Client returned data").ConfigureAwait(false);
await _service.LogInfoAsync("Converting data to XElement").ConfigureAwait(false);
await _service.LogInfoAsync("Read file completed. Client returned data").ConfigureAwait(false);
await _service.LogInfoAsync("Converting data to XElement").ConfigureAwait(false);
// We're reading in our own XML file, but even so, use conservative settings
// just to be on the safe side. First, disallow DTDs entirely (we will never
// have one ourself). And also, prevent any external resolution of files when
// processing the XML.
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null
};
// We're reading in our own XML file, but even so, use conservative settings
// just to be on the safe side. First, disallow DTDs entirely (we will never
// have one ourself). And also, prevent any external resolution of files when
// processing the XML.
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null
};
using var reader = XmlReader.Create(stream, settings);
using var reader = XmlReader.Create(stream, settings);
var result = XElement.Load(reader);
await _service.LogInfoAsync("Converting data to XElement completed").ConfigureAwait(false);
return result;
}
var result = XElement.Load(reader);
await _service.LogInfoAsync("Converting data to XElement completed").ConfigureAwait(false);
return result;
}
private async Task RepeatIOAsync(Func<Task> action)
......@@ -656,19 +655,18 @@ private async Task<byte[]> ConvertContentAttributeAsync(XAttribute contentsAttri
var text = contentsAttribute.Value;
var compressedBytes = Convert.FromBase64String(text);
using (var outStream = new MemoryStream())
using var outStream = new MemoryStream();
using (var inStream = new MemoryStream(compressedBytes))
using (var deflateStream = new DeflateStream(inStream, CompressionMode.Decompress))
{
using (var inStream = new MemoryStream(compressedBytes))
using (var deflateStream = new DeflateStream(inStream, CompressionMode.Decompress))
{
await deflateStream.CopyToAsync(outStream).ConfigureAwait(false);
}
await deflateStream.CopyToAsync(outStream).ConfigureAwait(false);
}
var bytes = outStream.ToArray();
var bytes = outStream.ToArray();
await _service.LogInfoAsync($"Parsing complete. bytes.length={bytes.Length}").ConfigureAwait(false);
return bytes;
}
await _service.LogInfoAsync($"Parsing complete. bytes.length={bytes.Length}").ConfigureAwait(false);
return bytes;
}
}
}
......
......@@ -99,43 +99,42 @@ private void Start(CancellationToken cancellationToken)
return;
}
using (var undo = CreateUndoTransaction())
using var undo = CreateUndoTransaction();
// insert the closing brace
using (var edit = SubjectBuffer.CreateEdit())
{
// insert the closing brace
using (var edit = SubjectBuffer.CreateEdit())
{
edit.Insert(closingSnapshotPoint, ClosingBrace.ToString());
edit.Insert(closingSnapshotPoint, ClosingBrace.ToString());
if (edit.HasFailedChanges)
{
Debug.Fail("Unable to insert closing brace");
if (edit.HasFailedChanges)
{
Debug.Fail("Unable to insert closing brace");
// exit without setting the closing point which will take us off the stack
edit.Cancel();
undo.Cancel();
return;
}
else
{
snapshot = edit.ApplyAndLogExceptions();
}
// exit without setting the closing point which will take us off the stack
edit.Cancel();
undo.Cancel();
return;
}
else
{
snapshot = edit.ApplyAndLogExceptions();
}
}
var beforePoint = beforeTrackingPoint.GetPoint(TextView.TextSnapshot);
var beforePoint = beforeTrackingPoint.GetPoint(TextView.TextSnapshot);
// switch from positive to negative tracking so it stays against the closing brace
ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(ClosingPoint.GetPoint(snapshot), PointTrackingMode.Negative);
// switch from positive to negative tracking so it stays against the closing brace
ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(ClosingPoint.GetPoint(snapshot), PointTrackingMode.Negative);
Debug.Assert(ClosingPoint.GetPoint(snapshot).Position > 0 && (new SnapshotSpan(ClosingPoint.GetPoint(snapshot).Subtract(1), 1))
.GetText().Equals(ClosingBrace.ToString()), "The closing point does not match the closing brace character");
Debug.Assert(ClosingPoint.GetPoint(snapshot).Position > 0 && (new SnapshotSpan(ClosingPoint.GetPoint(snapshot).Subtract(1), 1))
.GetText().Equals(ClosingBrace.ToString()), "The closing point does not match the closing brace character");
// move the caret back between the braces
TextView.Caret.MoveTo(beforePoint);
// move the caret back between the braces
TextView.Caret.MoveTo(beforePoint);
_session.AfterStart(this, cancellationToken);
_session.AfterStart(this, cancellationToken);
undo.Complete();
}
undo.Complete();
}
public void PreBackspace(out bool handledCommand)
......
......@@ -97,28 +97,27 @@ private static TypeSyntax TryGetDeclarationTypeToFix(SyntaxNode node)
var onYield = node.IsParentKind(SyntaxKind.YieldReturnStatement);
switch (containingMember)
return containingMember switch
{
case MethodDeclarationSyntax method:
MethodDeclarationSyntax method =>
// string M() { return null; }
// async Task<string> M() { return null; }
// IEnumerable<string> M() { yield return null; }
return TryGetReturnType(method.ReturnType, method.Modifiers, onYield);
TryGetReturnType(method.ReturnType, method.Modifiers, onYield),
case LocalFunctionStatementSyntax localFunction:
LocalFunctionStatementSyntax localFunction =>
// string local() { return null; }
// async Task<string> local() { return null; }
// IEnumerable<string> local() { yield return null; }
return TryGetReturnType(localFunction.ReturnType, localFunction.Modifiers, onYield);
TryGetReturnType(localFunction.ReturnType, localFunction.Modifiers, onYield),
case PropertyDeclarationSyntax property:
PropertyDeclarationSyntax property =>
// string x { get { return null; } }
// IEnumerable<string> Property { get { yield return null; } }
return TryGetReturnType(property.Type, modifiers: default, onYield);
TryGetReturnType(property.Type, modifiers: default, onYield),
default:
return null;
}
_ => null,
};
}
// string x = null;
......
......@@ -1028,27 +1028,19 @@ public override string GetExternalSymbolFullName(ISymbol symbol)
}
public override EnvDTE.vsCMAccess GetAccess(ISymbol symbol)
{
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
return EnvDTE.vsCMAccess.vsCMAccessPublic;
case Accessibility.Private:
return EnvDTE.vsCMAccess.vsCMAccessPrivate;
case Accessibility.Internal:
return EnvDTE.vsCMAccess.vsCMAccessProject;
case Accessibility.Protected:
return EnvDTE.vsCMAccess.vsCMAccessProtected;
case Accessibility.ProtectedOrInternal:
return EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected;
case Accessibility.ProtectedAndInternal:
=> symbol.DeclaredAccessibility switch
{
Accessibility.Public => EnvDTE.vsCMAccess.vsCMAccessPublic,
Accessibility.Private => EnvDTE.vsCMAccess.vsCMAccessPrivate,
Accessibility.Internal => EnvDTE.vsCMAccess.vsCMAccessProject,
Accessibility.Protected => EnvDTE.vsCMAccess.vsCMAccessProtected,
Accessibility.ProtectedOrInternal => EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected,
Accessibility.ProtectedAndInternal =>
// there is no appropriate mapping for private protected in EnvDTE.vsCMAccess
// See https://github.com/dotnet/roslyn/issues/22406
return EnvDTE.vsCMAccess.vsCMAccessProtected;
default:
throw Exceptions.ThrowEFail();
}
}
EnvDTE.vsCMAccess.vsCMAccessProtected,
_ => throw Exceptions.ThrowEFail(),
};
public override EnvDTE.vsCMAccess GetAccess(SyntaxNode node)
{
......
......@@ -15,13 +15,12 @@ public class NameResolverTests
{
private async Task TestAsync(string text, string searchText, params string[] expectedNames)
{
using (var workspace = TestWorkspace.CreateCSharp(text))
{
var nameResolver = new BreakpointResolver(workspace.CurrentSolution, searchText);
var results = await nameResolver.DoAsync(CancellationToken.None);
using var workspace = TestWorkspace.CreateCSharp(text);
Assert.Equal(expectedNames, results.Select(r => r.LocationNameOpt));
}
var nameResolver = new BreakpointResolver(workspace.CurrentSolution, searchText);
var results = await nameResolver.DoAsync(CancellationToken.None);
Assert.Equal(expectedNames, results.Select(r => r.LocationNameOpt));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
......
......@@ -18,20 +18,19 @@ public class OutputPathTests
[InlineData(null)]
public void RefPathPassedToWorkspace(string expectedRefPath)
{
using (var environment = new TestEnvironment())
{
var hierarchyWithRefPath =
environment.CreateHierarchy(
"WithRefPath",
@"Z:\WithRefPath.dll",
expectedRefPath,
"CSharp");
using var environment = new TestEnvironment();
var project = CSharpHelpers.CreateCSharpProject(environment, "WithRefPath", hierarchyWithRefPath);
var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single();
var hierarchyWithRefPath =
environment.CreateHierarchy(
"WithRefPath",
@"Z:\WithRefPath.dll",
expectedRefPath,
"CSharp");
Assert.Equal(expectedRefPath, workspaceProject.OutputRefFilePath);
}
var project = CSharpHelpers.CreateCSharpProject(environment, "WithRefPath", hierarchyWithRefPath);
var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single();
Assert.Equal(expectedRefPath, workspaceProject.OutputRefFilePath);
}
}
}
......@@ -346,35 +346,34 @@ private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextC
SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes)
{
// these are expensive. but hopefully we don't hit this as much except the boundary cases.
using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
{
var spansInLeftText = leftPool.Object;
var spansInRightText = rightPool.Object;
using var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject();
using var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject();
var spansInLeftText = leftPool.Object;
var spansInRightText = rightPool.Object;
if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText))
if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText))
{
for (var i = 0; i < spansInLeftText.Count; i++)
{
for (var i = 0; i < spansInLeftText.Count; i++)
var spanInLeftText = spansInLeftText[i];
var spanInRightText = spansInRightText[i];
if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty)
{
var spanInLeftText = spansInLeftText[i];
var spanInRightText = spansInRightText[i];
if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty)
{
continue;
}
var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);
if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out var textChange))
{
changes.Add(textChange);
}
continue;
}
return true;
var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);
if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out var textChange))
{
changes.Add(textChange);
}
}
return false;
return true;
}
return false;
}
private IEnumerable<TextChange> GetSubTextChanges(
......@@ -705,37 +704,36 @@ public IEnumerable<TextSpan> GetEditorVisibleSpans()
IList<TextSpan> visibleSpansInOriginal,
out IEnumerable<int> affectedVisibleSpansInNew)
{
using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null))
{
var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear();
affectedVisibleSpansInNew = affectedSpans;
using var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null);
var currentVisibleSpanIndex = 0;
foreach (var change in changes)
{
// Find the next visible span that either overlaps or intersects with
while (currentVisibleSpanIndex < visibleSpansInOriginal.Count &&
visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start)
{
currentVisibleSpanIndex++;
}
var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear();
affectedVisibleSpansInNew = affectedSpans;
// no more place to apply text changes
if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count)
{
break;
}
var currentVisibleSpanIndex = 0;
foreach (var change in changes)
{
// Find the next visible span that either overlaps or intersects with
while (currentVisibleSpanIndex < visibleSpansInOriginal.Count &&
visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start)
{
currentVisibleSpanIndex++;
}
var newText = change.NewText;
var span = change.Span.ToSpan();
// no more place to apply text changes
if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count)
{
break;
}
edit.Replace(span, newText);
var newText = change.NewText;
var span = change.Span.ToSpan();
affectedSpans.Add(currentVisibleSpanIndex);
}
edit.Replace(span, newText);
edit.ApplyAndLogExceptions();
affectedSpans.Add(currentVisibleSpanIndex);
}
edit.ApplyAndLogExceptions();
}
private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex)
......@@ -788,29 +786,28 @@ private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int>
{
var root = document.GetSyntaxRootSynchronously(CancellationToken.None);
using (var rulePool = SharedPools.Default<List<AbstractFormattingRule>>().GetPooledObject())
using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
{
var venusFormattingRules = rulePool.Object;
var visibleSpans = spanPool.Object;
using var rulePool = SharedPools.Default<List<AbstractFormattingRule>>().GetPooledObject();
using var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject();
venusFormattingRules.Add(baseIndentationRule);
venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance);
var venusFormattingRules = rulePool.Object;
var visibleSpans = spanPool.Object;
var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document));
venusFormattingRules.Add(baseIndentationRule);
venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance);
var workspace = document.Project.Solution.Workspace;
var changes = Formatter.GetFormattedTextChanges(
root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) },
workspace, options, formattingRules, CancellationToken.None);
var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document));
visibleSpans.Add(visibleSpan);
var newChanges = FilterTextChanges(document.GetTextSynchronously(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span));
var workspace = document.Project.Solution.Workspace;
var changes = Formatter.GetFormattedTextChanges(
root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) },
workspace, options, formattingRules, CancellationToken.None);
foreach (var change in newChanges)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
visibleSpans.Add(visibleSpan);
var newChanges = FilterTextChanges(document.GetTextSynchronously(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span));
foreach (var change in newChanges)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
}
......
......@@ -81,18 +81,14 @@ public static string CalculateHash(this AggregateException exception)
}
public static string GetParameterString(this Exception exception)
{
switch (exception)
=> exception switch
{
case RemoteInvocationException remote:
return $"{remote.ErrorCode} {remote.StackTrace ?? exception.Message}";
case AggregateException aggregate when aggregate.InnerException != null:
RemoteInvocationException remote => $"{remote.ErrorCode} {remote.StackTrace ?? exception.Message}",
AggregateException aggregate when aggregate.InnerException != null =>
// get first exception that is not aggregated exception
return GetParameterString(aggregate.InnerException);
default:
return $"{exception.GetType().ToString()} {(exception.StackTrace ?? exception.ToString())}";
}
}
GetParameterString(aggregate.InnerException),
_ => $"{exception.GetType().ToString()} {(exception.StackTrace ?? exception.ToString())}",
};
/// <summary>
/// hold onto last issue we reported. we use hash
......
......@@ -81,16 +81,14 @@ public void VerifyCorrectIntellisenseSelectionOnEnter()
[WpfFact]
public void VerifyCompletionListForLoadMembers()
{
using (var temporaryTextFile = new TemporaryTextFile(
using var temporaryTextFile = new TemporaryTextFile(
"c.csx",
"int x = 2; class Complex { public int goo() { return 4; } }"))
{
temporaryTextFile.Create();
VisualStudio.InteractiveWindow.SubmitText(string.Format("#load \"{0}\"", temporaryTextFile.FullName));
VisualStudio.InteractiveWindow.InvokeCompletionList();
VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("x", "Complex");
VisualStudio.SendKeys.Send(VirtualKey.Escape);
}
"int x = 2; class Complex { public int goo() { return 4; } }");
temporaryTextFile.Create();
VisualStudio.InteractiveWindow.SubmitText(string.Format("#load \"{0}\"", temporaryTextFile.FullName));
VisualStudio.InteractiveWindow.InvokeCompletionList();
VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("x", "Complex");
VisualStudio.SendKeys.Send(VirtualKey.Escape);
}
}
}
......@@ -132,22 +132,17 @@ public static CodeStyleOption<T> FromXElement(XElement element)
}
private static Func<string, T> GetParser(string type)
{
switch (type)
=> type switch
{
case nameof(Boolean):
nameof(Boolean) =>
// Try to map a boolean value. Either map it to true/false if we're a
// CodeStyleOption<bool> or map it to the 0 or 1 value for an enum if we're
// a CodeStyleOption<SomeEnumType>.
return v => Convert(bool.Parse(v));
case nameof(Int32):
return v => Convert(int.Parse(v));
case nameof(String):
return v => (T)(object)v;
default:
throw new ArgumentException(nameof(type));
}
}
(Func<string, T>)(v => Convert(bool.Parse(v))),
nameof(Int32) => v => Convert(int.Parse(v)),
nameof(String) => v => (T)(object)v,
_ => throw new ArgumentException(nameof(type)),
};
private static T Convert(bool b)
{
......
......@@ -85,42 +85,41 @@ internal static partial class Extensions
{
Task task = null;
using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
using (var stream = new ServerDirectStream())
using var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
using var stream = new ServerDirectStream();
try
{
try
{
// send request to asset source
task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken);
// send request to asset source
task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken);
// if invoke throws an exception, make sure we raise cancellation.
RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken);
// if invoke throws an exception, make sure we raise cancellation.
RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken);
// wait for asset source to respond
await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false);
// wait for asset source to respond
await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false);
// run user task with direct stream
var result = await funcWithDirectStreamAsync(stream, mergedCancellation.Token).ConfigureAwait(false);
// run user task with direct stream
var result = await funcWithDirectStreamAsync(stream, mergedCancellation.Token).ConfigureAwait(false);
// wait task to finish
await task.ConfigureAwait(false);
// wait task to finish
await task.ConfigureAwait(false);
return result;
}
catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken))
{
// important to use cancelationToken here rather than mergedCancellationToken.
// there is a slight delay when merged cancellation token will be notified once cancellation token
// is raised, it can cause one to be in cancelled mode and the other is not. here, one we
// actually care is the cancellation token given in, not the merged cancellation token.
cancellationToken.ThrowIfCancellationRequested();
return result;
}
catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken))
{
// important to use cancelationToken here rather than mergedCancellationToken.
// there is a slight delay when merged cancellation token will be notified once cancellation token
// is raised, it can cause one to be in cancelled mode and the other is not. here, one we
// actually care is the cancellation token given in, not the merged cancellation token.
cancellationToken.ThrowIfCancellationRequested();
// record reason why task got aborted. use NFW here since we don't want to
// crash VS on explicitly killing OOP.
task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed");
// record reason why task got aborted. use NFW here since we don't want to
// crash VS on explicitly killing OOP.
task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed");
throw;
}
throw;
}
}
......@@ -130,40 +129,39 @@ internal static partial class Extensions
{
Task task = null;
using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
using (var stream = new ServerDirectStream())
using var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
using var stream = new ServerDirectStream();
try
{
try
{
// send request by adding direct stream name to end of arguments
task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken);
// send request by adding direct stream name to end of arguments
task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken);
// if invoke throws an exception, make sure we raise cancellation.
RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken);
// if invoke throws an exception, make sure we raise cancellation.
RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken);
// wait for asset source to respond
await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false);
// wait for asset source to respond
await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false);
// run user task with direct stream
actionWithDirectStream(stream, mergedCancellation.Token);
// run user task with direct stream
actionWithDirectStream(stream, mergedCancellation.Token);
// wait task to finish
await task.ConfigureAwait(false);
}
catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken))
{
// important to use cancelationToken here rather than mergedCancellationToken.
// there is a slight delay when merged cancellation token will be notified once cancellation token
// is raised, it can cause one to be in cancelled mode and the other is not. here, one we
// actually care is the cancellation token given in, not the merged cancellation token.
cancellationToken.ThrowIfCancellationRequested();
// wait task to finish
await task.ConfigureAwait(false);
}
catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken))
{
// important to use cancelationToken here rather than mergedCancellationToken.
// there is a slight delay when merged cancellation token will be notified once cancellation token
// is raised, it can cause one to be in cancelled mode and the other is not. here, one we
// actually care is the cancellation token given in, not the merged cancellation token.
cancellationToken.ThrowIfCancellationRequested();
// record reason why task got aborted. use NFW here since we don't want to
// crash VS on explicitly killing OOP.
task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed");
// record reason why task got aborted. use NFW here since we don't want to
// crash VS on explicitly killing OOP.
task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed");
throw;
}
throw;
}
}
......@@ -173,42 +171,41 @@ internal static partial class Extensions
{
Task task = null;
using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
using (var stream = new ServerDirectStream())
using var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
using var stream = new ServerDirectStream();
try
{
try
{
// send request to asset source
task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken);
// send request to asset source
task = rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(stream.Name).ToArray(), cancellationToken);
// if invoke throws an exception, make sure we raise cancellation.
RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken);
// if invoke throws an exception, make sure we raise cancellation.
RaiseCancellationIfInvokeFailed(task, mergedCancellation, cancellationToken);
// wait for asset source to respond
await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false);
// wait for asset source to respond
await stream.WaitForDirectConnectionAsync(mergedCancellation.Token).ConfigureAwait(false);
// run user task with direct stream
var result = funcWithDirectStream(stream, mergedCancellation.Token);
// run user task with direct stream
var result = funcWithDirectStream(stream, mergedCancellation.Token);
// wait task to finish
await task.ConfigureAwait(false);
// wait task to finish
await task.ConfigureAwait(false);
return result;
}
catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken))
{
// important to use cancelationToken here rather than mergedCancellationToken.
// there is a slight delay when merged cancellation token will be notified once cancellation token
// is raised, it can cause one to be in cancelled mode and the other is not. here, one we
// actually care is the cancellation token given in, not the merged cancellation token.
cancellationToken.ThrowIfCancellationRequested();
return result;
}
catch (Exception ex) when (ReportUnlessCanceled(ex, mergedCancellation.Token, cancellationToken))
{
// important to use cancelationToken here rather than mergedCancellationToken.
// there is a slight delay when merged cancellation token will be notified once cancellation token
// is raised, it can cause one to be in cancelled mode and the other is not. here, one we
// actually care is the cancellation token given in, not the merged cancellation token.
cancellationToken.ThrowIfCancellationRequested();
// record reason why task got aborted. use NFW here since we don't want to
// crash VS on explicitly killing OOP.
task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed");
// record reason why task got aborted. use NFW here since we don't want to
// crash VS on explicitly killing OOP.
task.Exception.ReportServiceHubNFW("JsonRpc Invoke Failed");
throw;
}
throw;
}
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册